]> code.delx.au - gnu-emacs/blob - src/alloc.c
(set-display-table-and-terminal-coding-system):
[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 Garbage collection happens automatically if you cons more than
4259 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
4260 `garbage-collect' normally returns a list with info on amount of space in use:
4261 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
4262 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS
4263 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)
4264 (USED-STRINGS . FREE-STRINGS))
4265 However, if there was overflow in pure space, `garbage-collect'
4266 returns nil, because real GC can't be done. */)
4267 ()
4268 {
4269 register struct specbinding *bind;
4270 struct catchtag *catch;
4271 struct handler *handler;
4272 register struct backtrace *backlist;
4273 char stack_top_variable;
4274 register int i;
4275 int message_p;
4276 Lisp_Object total[8];
4277 int count = SPECPDL_INDEX ();
4278 EMACS_TIME t1, t2, t3;
4279
4280 if (abort_on_gc)
4281 abort ();
4282
4283 EMACS_GET_TIME (t1);
4284
4285 /* Can't GC if pure storage overflowed because we can't determine
4286 if something is a pure object or not. */
4287 if (pure_bytes_used_before_overflow)
4288 return Qnil;
4289
4290 /* In case user calls debug_print during GC,
4291 don't let that cause a recursive GC. */
4292 consing_since_gc = 0;
4293
4294 /* Save what's currently displayed in the echo area. */
4295 message_p = push_message ();
4296 record_unwind_protect (pop_message_unwind, Qnil);
4297
4298 /* Save a copy of the contents of the stack, for debugging. */
4299 #if MAX_SAVE_STACK > 0
4300 if (NILP (Vpurify_flag))
4301 {
4302 i = &stack_top_variable - stack_bottom;
4303 if (i < 0) i = -i;
4304 if (i < MAX_SAVE_STACK)
4305 {
4306 if (stack_copy == 0)
4307 stack_copy = (char *) xmalloc (stack_copy_size = i);
4308 else if (stack_copy_size < i)
4309 stack_copy = (char *) xrealloc (stack_copy, (stack_copy_size = i));
4310 if (stack_copy)
4311 {
4312 if ((EMACS_INT) (&stack_top_variable - stack_bottom) > 0)
4313 bcopy (stack_bottom, stack_copy, i);
4314 else
4315 bcopy (&stack_top_variable, stack_copy, i);
4316 }
4317 }
4318 }
4319 #endif /* MAX_SAVE_STACK > 0 */
4320
4321 if (garbage_collection_messages)
4322 message1_nolog ("Garbage collecting...");
4323
4324 BLOCK_INPUT;
4325
4326 shrink_regexp_cache ();
4327
4328 /* Don't keep undo information around forever. */
4329 {
4330 register struct buffer *nextb = all_buffers;
4331
4332 while (nextb)
4333 {
4334 /* If a buffer's undo list is Qt, that means that undo is
4335 turned off in that buffer. Calling truncate_undo_list on
4336 Qt tends to return NULL, which effectively turns undo back on.
4337 So don't call truncate_undo_list if undo_list is Qt. */
4338 if (! EQ (nextb->undo_list, Qt))
4339 nextb->undo_list
4340 = truncate_undo_list (nextb->undo_list, undo_limit,
4341 undo_strong_limit);
4342
4343 /* Shrink buffer gaps, but skip indirect and dead buffers. */
4344 if (nextb->base_buffer == 0 && !NILP (nextb->name))
4345 {
4346 /* If a buffer's gap size is more than 10% of the buffer
4347 size, or larger than 2000 bytes, then shrink it
4348 accordingly. Keep a minimum size of 20 bytes. */
4349 int size = min (2000, max (20, (nextb->text->z_byte / 10)));
4350
4351 if (nextb->text->gap_size > size)
4352 {
4353 struct buffer *save_current = current_buffer;
4354 current_buffer = nextb;
4355 make_gap (-(nextb->text->gap_size - size));
4356 current_buffer = save_current;
4357 }
4358 }
4359
4360 nextb = nextb->next;
4361 }
4362 }
4363
4364 gc_in_progress = 1;
4365
4366 /* clear_marks (); */
4367
4368 /* Mark all the special slots that serve as the roots of accessibility.
4369
4370 Usually the special slots to mark are contained in particular structures.
4371 Then we know no slot is marked twice because the structures don't overlap.
4372 In some cases, the structures point to the slots to be marked.
4373 For these, we use MARKBIT to avoid double marking of the slot. */
4374
4375 for (i = 0; i < staticidx; i++)
4376 mark_object (*staticvec[i]);
4377
4378 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
4379 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
4380 mark_stack ();
4381 #else
4382 {
4383 register struct gcpro *tail;
4384 for (tail = gcprolist; tail; tail = tail->next)
4385 for (i = 0; i < tail->nvars; i++)
4386 if (!XMARKBIT (tail->var[i]))
4387 {
4388 /* Explicit casting prevents compiler warning about
4389 discarding the `volatile' qualifier. */
4390 mark_object (tail->var[i]);
4391 XMARK (tail->var[i]);
4392 }
4393 }
4394 #endif
4395
4396 mark_byte_stack ();
4397 for (bind = specpdl; bind != specpdl_ptr; bind++)
4398 {
4399 /* These casts avoid a warning for discarding `volatile'. */
4400 mark_object (bind->symbol);
4401 mark_object (bind->old_value);
4402 }
4403 for (catch = catchlist; catch; catch = catch->next)
4404 {
4405 mark_object (catch->tag);
4406 mark_object (catch->val);
4407 }
4408 for (handler = handlerlist; handler; handler = handler->next)
4409 {
4410 mark_object (handler->handler);
4411 mark_object (handler->var);
4412 }
4413 for (backlist = backtrace_list; backlist; backlist = backlist->next)
4414 {
4415 if (!XMARKBIT (*backlist->function))
4416 {
4417 mark_object (*backlist->function);
4418 XMARK (*backlist->function);
4419 }
4420 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
4421 i = 0;
4422 else
4423 i = backlist->nargs - 1;
4424 for (; i >= 0; i--)
4425 if (!XMARKBIT (backlist->args[i]))
4426 {
4427 mark_object (backlist->args[i]);
4428 XMARK (backlist->args[i]);
4429 }
4430 }
4431 mark_kboards ();
4432
4433 /* Look thru every buffer's undo list
4434 for elements that update markers that were not marked,
4435 and delete them. */
4436 {
4437 register struct buffer *nextb = all_buffers;
4438
4439 while (nextb)
4440 {
4441 /* If a buffer's undo list is Qt, that means that undo is
4442 turned off in that buffer. Calling truncate_undo_list on
4443 Qt tends to return NULL, which effectively turns undo back on.
4444 So don't call truncate_undo_list if undo_list is Qt. */
4445 if (! EQ (nextb->undo_list, Qt))
4446 {
4447 Lisp_Object tail, prev;
4448 tail = nextb->undo_list;
4449 prev = Qnil;
4450 while (CONSP (tail))
4451 {
4452 if (GC_CONSP (XCAR (tail))
4453 && GC_MARKERP (XCAR (XCAR (tail)))
4454 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
4455 {
4456 if (NILP (prev))
4457 nextb->undo_list = tail = XCDR (tail);
4458 else
4459 {
4460 tail = XCDR (tail);
4461 XSETCDR (prev, tail);
4462 }
4463 }
4464 else
4465 {
4466 prev = tail;
4467 tail = XCDR (tail);
4468 }
4469 }
4470 }
4471
4472 nextb = nextb->next;
4473 }
4474 }
4475
4476 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4477 mark_stack ();
4478 #endif
4479
4480 #ifdef USE_GTK
4481 {
4482 extern void xg_mark_data ();
4483 xg_mark_data ();
4484 }
4485 #endif
4486
4487 gc_sweep ();
4488
4489 /* Clear the mark bits that we set in certain root slots. */
4490
4491 #if (GC_MARK_STACK == GC_USE_GCPROS_AS_BEFORE \
4492 || GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES)
4493 {
4494 register struct gcpro *tail;
4495
4496 for (tail = gcprolist; tail; tail = tail->next)
4497 for (i = 0; i < tail->nvars; i++)
4498 XUNMARK (tail->var[i]);
4499 }
4500 #endif
4501
4502 unmark_byte_stack ();
4503 for (backlist = backtrace_list; backlist; backlist = backlist->next)
4504 {
4505 XUNMARK (*backlist->function);
4506 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
4507 i = 0;
4508 else
4509 i = backlist->nargs - 1;
4510 for (; i >= 0; i--)
4511 XUNMARK (backlist->args[i]);
4512 }
4513 VECTOR_UNMARK (&buffer_defaults);
4514 VECTOR_UNMARK (&buffer_local_symbols);
4515
4516 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
4517 dump_zombies ();
4518 #endif
4519
4520 UNBLOCK_INPUT;
4521
4522 /* clear_marks (); */
4523 gc_in_progress = 0;
4524
4525 consing_since_gc = 0;
4526 if (gc_cons_threshold < 10000)
4527 gc_cons_threshold = 10000;
4528
4529 if (garbage_collection_messages)
4530 {
4531 if (message_p || minibuf_level > 0)
4532 restore_message ();
4533 else
4534 message1_nolog ("Garbage collecting...done");
4535 }
4536
4537 unbind_to (count, Qnil);
4538
4539 total[0] = Fcons (make_number (total_conses),
4540 make_number (total_free_conses));
4541 total[1] = Fcons (make_number (total_symbols),
4542 make_number (total_free_symbols));
4543 total[2] = Fcons (make_number (total_markers),
4544 make_number (total_free_markers));
4545 total[3] = make_number (total_string_size);
4546 total[4] = make_number (total_vector_size);
4547 total[5] = Fcons (make_number (total_floats),
4548 make_number (total_free_floats));
4549 total[6] = Fcons (make_number (total_intervals),
4550 make_number (total_free_intervals));
4551 total[7] = Fcons (make_number (total_strings),
4552 make_number (total_free_strings));
4553
4554 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4555 {
4556 /* Compute average percentage of zombies. */
4557 double nlive = 0;
4558
4559 for (i = 0; i < 7; ++i)
4560 if (CONSP (total[i]))
4561 nlive += XFASTINT (XCAR (total[i]));
4562
4563 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
4564 max_live = max (nlive, max_live);
4565 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
4566 max_zombies = max (nzombies, max_zombies);
4567 ++ngcs;
4568 }
4569 #endif
4570
4571 if (!NILP (Vpost_gc_hook))
4572 {
4573 int count = inhibit_garbage_collection ();
4574 safe_run_hooks (Qpost_gc_hook);
4575 unbind_to (count, Qnil);
4576 }
4577
4578 /* Accumulate statistics. */
4579 EMACS_GET_TIME (t2);
4580 EMACS_SUB_TIME (t3, t2, t1);
4581 if (FLOATP (Vgc_elapsed))
4582 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed) +
4583 EMACS_SECS (t3) +
4584 EMACS_USECS (t3) * 1.0e-6);
4585 gcs_done++;
4586
4587 return Flist (sizeof total / sizeof *total, total);
4588 }
4589
4590
4591 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
4592 only interesting objects referenced from glyphs are strings. */
4593
4594 static void
4595 mark_glyph_matrix (matrix)
4596 struct glyph_matrix *matrix;
4597 {
4598 struct glyph_row *row = matrix->rows;
4599 struct glyph_row *end = row + matrix->nrows;
4600
4601 for (; row < end; ++row)
4602 if (row->enabled_p)
4603 {
4604 int area;
4605 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
4606 {
4607 struct glyph *glyph = row->glyphs[area];
4608 struct glyph *end_glyph = glyph + row->used[area];
4609
4610 for (; glyph < end_glyph; ++glyph)
4611 if (GC_STRINGP (glyph->object)
4612 && !STRING_MARKED_P (XSTRING (glyph->object)))
4613 mark_object (glyph->object);
4614 }
4615 }
4616 }
4617
4618
4619 /* Mark Lisp faces in the face cache C. */
4620
4621 static void
4622 mark_face_cache (c)
4623 struct face_cache *c;
4624 {
4625 if (c)
4626 {
4627 int i, j;
4628 for (i = 0; i < c->used; ++i)
4629 {
4630 struct face *face = FACE_FROM_ID (c->f, i);
4631
4632 if (face)
4633 {
4634 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
4635 mark_object (face->lface[j]);
4636 }
4637 }
4638 }
4639 }
4640
4641
4642 #ifdef HAVE_WINDOW_SYSTEM
4643
4644 /* Mark Lisp objects in image IMG. */
4645
4646 static void
4647 mark_image (img)
4648 struct image *img;
4649 {
4650 mark_object (img->spec);
4651
4652 if (!NILP (img->data.lisp_val))
4653 mark_object (img->data.lisp_val);
4654 }
4655
4656
4657 /* Mark Lisp objects in image cache of frame F. It's done this way so
4658 that we don't have to include xterm.h here. */
4659
4660 static void
4661 mark_image_cache (f)
4662 struct frame *f;
4663 {
4664 forall_images_in_image_cache (f, mark_image);
4665 }
4666
4667 #endif /* HAVE_X_WINDOWS */
4668
4669
4670 \f
4671 /* Mark reference to a Lisp_Object.
4672 If the object referred to has not been seen yet, recursively mark
4673 all the references contained in it. */
4674
4675 #define LAST_MARKED_SIZE 500
4676 Lisp_Object last_marked[LAST_MARKED_SIZE];
4677 int last_marked_index;
4678
4679 /* For debugging--call abort when we cdr down this many
4680 links of a list, in mark_object. In debugging,
4681 the call to abort will hit a breakpoint.
4682 Normally this is zero and the check never goes off. */
4683 int mark_object_loop_halt;
4684
4685 void
4686 mark_object (arg)
4687 Lisp_Object arg;
4688 {
4689 register Lisp_Object obj = arg;
4690 #ifdef GC_CHECK_MARKED_OBJECTS
4691 void *po;
4692 struct mem_node *m;
4693 #endif
4694 int cdr_count = 0;
4695
4696 loop:
4697 XUNMARK (obj);
4698
4699 if (PURE_POINTER_P (XPNTR (obj)))
4700 return;
4701
4702 last_marked[last_marked_index++] = obj;
4703 if (last_marked_index == LAST_MARKED_SIZE)
4704 last_marked_index = 0;
4705
4706 /* Perform some sanity checks on the objects marked here. Abort if
4707 we encounter an object we know is bogus. This increases GC time
4708 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
4709 #ifdef GC_CHECK_MARKED_OBJECTS
4710
4711 po = (void *) XPNTR (obj);
4712
4713 /* Check that the object pointed to by PO is known to be a Lisp
4714 structure allocated from the heap. */
4715 #define CHECK_ALLOCATED() \
4716 do { \
4717 m = mem_find (po); \
4718 if (m == MEM_NIL) \
4719 abort (); \
4720 } while (0)
4721
4722 /* Check that the object pointed to by PO is live, using predicate
4723 function LIVEP. */
4724 #define CHECK_LIVE(LIVEP) \
4725 do { \
4726 if (!LIVEP (m, po)) \
4727 abort (); \
4728 } while (0)
4729
4730 /* Check both of the above conditions. */
4731 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
4732 do { \
4733 CHECK_ALLOCATED (); \
4734 CHECK_LIVE (LIVEP); \
4735 } while (0) \
4736
4737 #else /* not GC_CHECK_MARKED_OBJECTS */
4738
4739 #define CHECK_ALLOCATED() (void) 0
4740 #define CHECK_LIVE(LIVEP) (void) 0
4741 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
4742
4743 #endif /* not GC_CHECK_MARKED_OBJECTS */
4744
4745 switch (SWITCH_ENUM_CAST (XGCTYPE (obj)))
4746 {
4747 case Lisp_String:
4748 {
4749 register struct Lisp_String *ptr = XSTRING (obj);
4750 CHECK_ALLOCATED_AND_LIVE (live_string_p);
4751 MARK_INTERVAL_TREE (ptr->intervals);
4752 MARK_STRING (ptr);
4753 #ifdef GC_CHECK_STRING_BYTES
4754 /* Check that the string size recorded in the string is the
4755 same as the one recorded in the sdata structure. */
4756 CHECK_STRING_BYTES (ptr);
4757 #endif /* GC_CHECK_STRING_BYTES */
4758 }
4759 break;
4760
4761 case Lisp_Vectorlike:
4762 #ifdef GC_CHECK_MARKED_OBJECTS
4763 m = mem_find (po);
4764 if (m == MEM_NIL && !GC_SUBRP (obj)
4765 && po != &buffer_defaults
4766 && po != &buffer_local_symbols)
4767 abort ();
4768 #endif /* GC_CHECK_MARKED_OBJECTS */
4769
4770 if (GC_BUFFERP (obj))
4771 {
4772 if (!VECTOR_MARKED_P (XBUFFER (obj)))
4773 {
4774 #ifdef GC_CHECK_MARKED_OBJECTS
4775 if (po != &buffer_defaults && po != &buffer_local_symbols)
4776 {
4777 struct buffer *b;
4778 for (b = all_buffers; b && b != po; b = b->next)
4779 ;
4780 if (b == NULL)
4781 abort ();
4782 }
4783 #endif /* GC_CHECK_MARKED_OBJECTS */
4784 mark_buffer (obj);
4785 }
4786 }
4787 else if (GC_SUBRP (obj))
4788 break;
4789 else if (GC_COMPILEDP (obj))
4790 /* We could treat this just like a vector, but it is better to
4791 save the COMPILED_CONSTANTS element for last and avoid
4792 recursion there. */
4793 {
4794 register struct Lisp_Vector *ptr = XVECTOR (obj);
4795 register EMACS_INT size = ptr->size;
4796 register int i;
4797
4798 if (VECTOR_MARKED_P (ptr))
4799 break; /* Already marked */
4800
4801 CHECK_LIVE (live_vector_p);
4802 VECTOR_MARK (ptr); /* Else mark it */
4803 size &= PSEUDOVECTOR_SIZE_MASK;
4804 for (i = 0; i < size; i++) /* and then mark its elements */
4805 {
4806 if (i != COMPILED_CONSTANTS)
4807 mark_object (ptr->contents[i]);
4808 }
4809 obj = ptr->contents[COMPILED_CONSTANTS];
4810 goto loop;
4811 }
4812 else if (GC_FRAMEP (obj))
4813 {
4814 register struct frame *ptr = XFRAME (obj);
4815
4816 if (VECTOR_MARKED_P (ptr)) break; /* Already marked */
4817 VECTOR_MARK (ptr); /* Else mark it */
4818
4819 CHECK_LIVE (live_vector_p);
4820 mark_object (ptr->name);
4821 mark_object (ptr->icon_name);
4822 mark_object (ptr->title);
4823 mark_object (ptr->focus_frame);
4824 mark_object (ptr->selected_window);
4825 mark_object (ptr->minibuffer_window);
4826 mark_object (ptr->param_alist);
4827 mark_object (ptr->scroll_bars);
4828 mark_object (ptr->condemned_scroll_bars);
4829 mark_object (ptr->menu_bar_items);
4830 mark_object (ptr->face_alist);
4831 mark_object (ptr->menu_bar_vector);
4832 mark_object (ptr->buffer_predicate);
4833 mark_object (ptr->buffer_list);
4834 mark_object (ptr->menu_bar_window);
4835 mark_object (ptr->tool_bar_window);
4836 mark_face_cache (ptr->face_cache);
4837 #ifdef HAVE_WINDOW_SYSTEM
4838 mark_image_cache (ptr);
4839 mark_object (ptr->tool_bar_items);
4840 mark_object (ptr->desired_tool_bar_string);
4841 mark_object (ptr->current_tool_bar_string);
4842 #endif /* HAVE_WINDOW_SYSTEM */
4843 }
4844 else if (GC_BOOL_VECTOR_P (obj))
4845 {
4846 register struct Lisp_Vector *ptr = XVECTOR (obj);
4847
4848 if (VECTOR_MARKED_P (ptr))
4849 break; /* Already marked */
4850 CHECK_LIVE (live_vector_p);
4851 VECTOR_MARK (ptr); /* Else mark it */
4852 }
4853 else if (GC_WINDOWP (obj))
4854 {
4855 register struct Lisp_Vector *ptr = XVECTOR (obj);
4856 struct window *w = XWINDOW (obj);
4857 register int i;
4858
4859 /* Stop if already marked. */
4860 if (VECTOR_MARKED_P (ptr))
4861 break;
4862
4863 /* Mark it. */
4864 CHECK_LIVE (live_vector_p);
4865 VECTOR_MARK (ptr);
4866
4867 /* There is no Lisp data above The member CURRENT_MATRIX in
4868 struct WINDOW. Stop marking when that slot is reached. */
4869 for (i = 0;
4870 (char *) &ptr->contents[i] < (char *) &w->current_matrix;
4871 i++)
4872 mark_object (ptr->contents[i]);
4873
4874 /* Mark glyphs for leaf windows. Marking window matrices is
4875 sufficient because frame matrices use the same glyph
4876 memory. */
4877 if (NILP (w->hchild)
4878 && NILP (w->vchild)
4879 && w->current_matrix)
4880 {
4881 mark_glyph_matrix (w->current_matrix);
4882 mark_glyph_matrix (w->desired_matrix);
4883 }
4884 }
4885 else if (GC_HASH_TABLE_P (obj))
4886 {
4887 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
4888
4889 /* Stop if already marked. */
4890 if (VECTOR_MARKED_P (h))
4891 break;
4892
4893 /* Mark it. */
4894 CHECK_LIVE (live_vector_p);
4895 VECTOR_MARK (h);
4896
4897 /* Mark contents. */
4898 /* Do not mark next_free or next_weak.
4899 Being in the next_weak chain
4900 should not keep the hash table alive.
4901 No need to mark `count' since it is an integer. */
4902 mark_object (h->test);
4903 mark_object (h->weak);
4904 mark_object (h->rehash_size);
4905 mark_object (h->rehash_threshold);
4906 mark_object (h->hash);
4907 mark_object (h->next);
4908 mark_object (h->index);
4909 mark_object (h->user_hash_function);
4910 mark_object (h->user_cmp_function);
4911
4912 /* If hash table is not weak, mark all keys and values.
4913 For weak tables, mark only the vector. */
4914 if (GC_NILP (h->weak))
4915 mark_object (h->key_and_value);
4916 else
4917 VECTOR_MARK (XVECTOR (h->key_and_value));
4918 }
4919 else
4920 {
4921 register struct Lisp_Vector *ptr = XVECTOR (obj);
4922 register EMACS_INT size = ptr->size;
4923 register int i;
4924
4925 if (VECTOR_MARKED_P (ptr)) break; /* Already marked */
4926 CHECK_LIVE (live_vector_p);
4927 VECTOR_MARK (ptr); /* Else mark it */
4928 if (size & PSEUDOVECTOR_FLAG)
4929 size &= PSEUDOVECTOR_SIZE_MASK;
4930
4931 for (i = 0; i < size; i++) /* and then mark its elements */
4932 mark_object (ptr->contents[i]);
4933 }
4934 break;
4935
4936 case Lisp_Symbol:
4937 {
4938 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
4939 struct Lisp_Symbol *ptrx;
4940
4941 if (ptr->gcmarkbit) break;
4942 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
4943 ptr->gcmarkbit = 1;
4944 mark_object (ptr->value);
4945 mark_object (ptr->function);
4946 mark_object (ptr->plist);
4947
4948 if (!PURE_POINTER_P (XSTRING (ptr->xname)))
4949 MARK_STRING (XSTRING (ptr->xname));
4950 MARK_INTERVAL_TREE (STRING_INTERVALS (ptr->xname));
4951
4952 /* Note that we do not mark the obarray of the symbol.
4953 It is safe not to do so because nothing accesses that
4954 slot except to check whether it is nil. */
4955 ptr = ptr->next;
4956 if (ptr)
4957 {
4958 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
4959 XSETSYMBOL (obj, ptrx);
4960 goto loop;
4961 }
4962 }
4963 break;
4964
4965 case Lisp_Misc:
4966 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
4967 if (XMARKER (obj)->gcmarkbit)
4968 break;
4969 XMARKER (obj)->gcmarkbit = 1;
4970 switch (XMISCTYPE (obj))
4971 {
4972 case Lisp_Misc_Buffer_Local_Value:
4973 case Lisp_Misc_Some_Buffer_Local_Value:
4974 {
4975 register struct Lisp_Buffer_Local_Value *ptr
4976 = XBUFFER_LOCAL_VALUE (obj);
4977 /* If the cdr is nil, avoid recursion for the car. */
4978 if (EQ (ptr->cdr, Qnil))
4979 {
4980 obj = ptr->realvalue;
4981 goto loop;
4982 }
4983 mark_object (ptr->realvalue);
4984 mark_object (ptr->buffer);
4985 mark_object (ptr->frame);
4986 obj = ptr->cdr;
4987 goto loop;
4988 }
4989
4990 case Lisp_Misc_Marker:
4991 /* DO NOT mark thru the marker's chain.
4992 The buffer's markers chain does not preserve markers from gc;
4993 instead, markers are removed from the chain when freed by gc. */
4994 case Lisp_Misc_Intfwd:
4995 case Lisp_Misc_Boolfwd:
4996 case Lisp_Misc_Objfwd:
4997 case Lisp_Misc_Buffer_Objfwd:
4998 case Lisp_Misc_Kboard_Objfwd:
4999 /* Don't bother with Lisp_Buffer_Objfwd,
5000 since all markable slots in current buffer marked anyway. */
5001 /* Don't need to do Lisp_Objfwd, since the places they point
5002 are protected with staticpro. */
5003 break;
5004
5005 case Lisp_Misc_Overlay:
5006 {
5007 struct Lisp_Overlay *ptr = XOVERLAY (obj);
5008 mark_object (ptr->start);
5009 mark_object (ptr->end);
5010 mark_object (ptr->plist);
5011 if (ptr->next)
5012 {
5013 XSETMISC (obj, ptr->next);
5014 goto loop;
5015 }
5016 }
5017 break;
5018
5019 default:
5020 abort ();
5021 }
5022 break;
5023
5024 case Lisp_Cons:
5025 {
5026 register struct Lisp_Cons *ptr = XCONS (obj);
5027 if (XMARKBIT (ptr->car)) break;
5028 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
5029 XMARK (ptr->car);
5030 /* If the cdr is nil, avoid recursion for the car. */
5031 if (EQ (ptr->cdr, Qnil))
5032 {
5033 obj = ptr->car;
5034 cdr_count = 0;
5035 goto loop;
5036 }
5037 mark_object (ptr->car);
5038 obj = ptr->cdr;
5039 cdr_count++;
5040 if (cdr_count == mark_object_loop_halt)
5041 abort ();
5042 goto loop;
5043 }
5044
5045 case Lisp_Float:
5046 CHECK_ALLOCATED_AND_LIVE (live_float_p);
5047 FLOAT_MARK (XFLOAT (obj));
5048 break;
5049
5050 case Lisp_Int:
5051 break;
5052
5053 default:
5054 abort ();
5055 }
5056
5057 #undef CHECK_LIVE
5058 #undef CHECK_ALLOCATED
5059 #undef CHECK_ALLOCATED_AND_LIVE
5060 }
5061
5062 /* Mark the pointers in a buffer structure. */
5063
5064 static void
5065 mark_buffer (buf)
5066 Lisp_Object buf;
5067 {
5068 register struct buffer *buffer = XBUFFER (buf);
5069 register Lisp_Object *ptr, tmp;
5070 Lisp_Object base_buffer;
5071
5072 VECTOR_MARK (buffer);
5073
5074 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
5075
5076 if (CONSP (buffer->undo_list))
5077 {
5078 Lisp_Object tail;
5079 tail = buffer->undo_list;
5080
5081 /* We mark the undo list specially because
5082 its pointers to markers should be weak. */
5083
5084 while (CONSP (tail))
5085 {
5086 register struct Lisp_Cons *ptr = XCONS (tail);
5087
5088 if (XMARKBIT (ptr->car))
5089 break;
5090 XMARK (ptr->car);
5091 if (GC_CONSP (ptr->car)
5092 && ! XMARKBIT (XCAR (ptr->car))
5093 && GC_MARKERP (XCAR (ptr->car)))
5094 {
5095 XMARK (XCAR_AS_LVALUE (ptr->car));
5096 mark_object (XCDR (ptr->car));
5097 }
5098 else
5099 mark_object (ptr->car);
5100
5101 if (CONSP (ptr->cdr))
5102 tail = ptr->cdr;
5103 else
5104 break;
5105 }
5106
5107 mark_object (XCDR (tail));
5108 }
5109 else
5110 mark_object (buffer->undo_list);
5111
5112 if (buffer->overlays_before)
5113 {
5114 XSETMISC (tmp, buffer->overlays_before);
5115 mark_object (tmp);
5116 }
5117 if (buffer->overlays_after)
5118 {
5119 XSETMISC (tmp, buffer->overlays_after);
5120 mark_object (tmp);
5121 }
5122
5123 for (ptr = &buffer->name;
5124 (char *)ptr < (char *)buffer + sizeof (struct buffer);
5125 ptr++)
5126 mark_object (*ptr);
5127
5128 /* If this is an indirect buffer, mark its base buffer. */
5129 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
5130 {
5131 XSETBUFFER (base_buffer, buffer->base_buffer);
5132 mark_buffer (base_buffer);
5133 }
5134 }
5135
5136
5137 /* Value is non-zero if OBJ will survive the current GC because it's
5138 either marked or does not need to be marked to survive. */
5139
5140 int
5141 survives_gc_p (obj)
5142 Lisp_Object obj;
5143 {
5144 int survives_p;
5145
5146 switch (XGCTYPE (obj))
5147 {
5148 case Lisp_Int:
5149 survives_p = 1;
5150 break;
5151
5152 case Lisp_Symbol:
5153 survives_p = XSYMBOL (obj)->gcmarkbit;
5154 break;
5155
5156 case Lisp_Misc:
5157 survives_p = XMARKER (obj)->gcmarkbit;
5158 break;
5159
5160 case Lisp_String:
5161 {
5162 struct Lisp_String *s = XSTRING (obj);
5163 survives_p = STRING_MARKED_P (s);
5164 }
5165 break;
5166
5167 case Lisp_Vectorlike:
5168 if (GC_BUFFERP (obj))
5169 survives_p = VECTOR_MARKED_P (XBUFFER (obj));
5170 else if (GC_SUBRP (obj))
5171 survives_p = 1;
5172 else
5173 survives_p = VECTOR_MARKED_P (XVECTOR (obj));
5174 break;
5175
5176 case Lisp_Cons:
5177 survives_p = XMARKBIT (XCAR (obj));
5178 break;
5179
5180 case Lisp_Float:
5181 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
5182 break;
5183
5184 default:
5185 abort ();
5186 }
5187
5188 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
5189 }
5190
5191
5192 \f
5193 /* Sweep: find all structures not marked, and free them. */
5194
5195 static void
5196 gc_sweep ()
5197 {
5198 /* Remove or mark entries in weak hash tables.
5199 This must be done before any object is unmarked. */
5200 sweep_weak_hash_tables ();
5201
5202 sweep_strings ();
5203 #ifdef GC_CHECK_STRING_BYTES
5204 if (!noninteractive)
5205 check_string_bytes (1);
5206 #endif
5207
5208 /* Put all unmarked conses on free list */
5209 {
5210 register struct cons_block *cblk;
5211 struct cons_block **cprev = &cons_block;
5212 register int lim = cons_block_index;
5213 register int num_free = 0, num_used = 0;
5214
5215 cons_free_list = 0;
5216
5217 for (cblk = cons_block; cblk; cblk = *cprev)
5218 {
5219 register int i;
5220 int this_free = 0;
5221 for (i = 0; i < lim; i++)
5222 if (!XMARKBIT (cblk->conses[i].car))
5223 {
5224 this_free++;
5225 *(struct Lisp_Cons **)&cblk->conses[i].cdr = cons_free_list;
5226 cons_free_list = &cblk->conses[i];
5227 #if GC_MARK_STACK
5228 cons_free_list->car = Vdead;
5229 #endif
5230 }
5231 else
5232 {
5233 num_used++;
5234 XUNMARK (cblk->conses[i].car);
5235 }
5236 lim = CONS_BLOCK_SIZE;
5237 /* If this block contains only free conses and we have already
5238 seen more than two blocks worth of free conses then deallocate
5239 this block. */
5240 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
5241 {
5242 *cprev = cblk->next;
5243 /* Unhook from the free list. */
5244 cons_free_list = *(struct Lisp_Cons **) &cblk->conses[0].cdr;
5245 lisp_free (cblk);
5246 n_cons_blocks--;
5247 }
5248 else
5249 {
5250 num_free += this_free;
5251 cprev = &cblk->next;
5252 }
5253 }
5254 total_conses = num_used;
5255 total_free_conses = num_free;
5256 }
5257
5258 /* Put all unmarked floats on free list */
5259 {
5260 register struct float_block *fblk;
5261 struct float_block **fprev = &float_block;
5262 register int lim = float_block_index;
5263 register int num_free = 0, num_used = 0;
5264
5265 float_free_list = 0;
5266
5267 for (fblk = float_block; fblk; fblk = *fprev)
5268 {
5269 register int i;
5270 int this_free = 0;
5271 for (i = 0; i < lim; i++)
5272 if (!FLOAT_MARKED_P (&fblk->floats[i]))
5273 {
5274 this_free++;
5275 *(struct Lisp_Float **)&fblk->floats[i].data = float_free_list;
5276 float_free_list = &fblk->floats[i];
5277 }
5278 else
5279 {
5280 num_used++;
5281 FLOAT_UNMARK (&fblk->floats[i]);
5282 }
5283 lim = FLOAT_BLOCK_SIZE;
5284 /* If this block contains only free floats and we have already
5285 seen more than two blocks worth of free floats then deallocate
5286 this block. */
5287 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
5288 {
5289 *fprev = fblk->next;
5290 /* Unhook from the free list. */
5291 float_free_list = *(struct Lisp_Float **) &fblk->floats[0].data;
5292 lisp_align_free (fblk);
5293 n_float_blocks--;
5294 }
5295 else
5296 {
5297 num_free += this_free;
5298 fprev = &fblk->next;
5299 }
5300 }
5301 total_floats = num_used;
5302 total_free_floats = num_free;
5303 }
5304
5305 /* Put all unmarked intervals on free list */
5306 {
5307 register struct interval_block *iblk;
5308 struct interval_block **iprev = &interval_block;
5309 register int lim = interval_block_index;
5310 register int num_free = 0, num_used = 0;
5311
5312 interval_free_list = 0;
5313
5314 for (iblk = interval_block; iblk; iblk = *iprev)
5315 {
5316 register int i;
5317 int this_free = 0;
5318
5319 for (i = 0; i < lim; i++)
5320 {
5321 if (!iblk->intervals[i].gcmarkbit)
5322 {
5323 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
5324 interval_free_list = &iblk->intervals[i];
5325 this_free++;
5326 }
5327 else
5328 {
5329 num_used++;
5330 iblk->intervals[i].gcmarkbit = 0;
5331 }
5332 }
5333 lim = INTERVAL_BLOCK_SIZE;
5334 /* If this block contains only free intervals and we have already
5335 seen more than two blocks worth of free intervals then
5336 deallocate this block. */
5337 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
5338 {
5339 *iprev = iblk->next;
5340 /* Unhook from the free list. */
5341 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
5342 lisp_free (iblk);
5343 n_interval_blocks--;
5344 }
5345 else
5346 {
5347 num_free += this_free;
5348 iprev = &iblk->next;
5349 }
5350 }
5351 total_intervals = num_used;
5352 total_free_intervals = num_free;
5353 }
5354
5355 /* Put all unmarked symbols on free list */
5356 {
5357 register struct symbol_block *sblk;
5358 struct symbol_block **sprev = &symbol_block;
5359 register int lim = symbol_block_index;
5360 register int num_free = 0, num_used = 0;
5361
5362 symbol_free_list = NULL;
5363
5364 for (sblk = symbol_block; sblk; sblk = *sprev)
5365 {
5366 int this_free = 0;
5367 struct Lisp_Symbol *sym = sblk->symbols;
5368 struct Lisp_Symbol *end = sym + lim;
5369
5370 for (; sym < end; ++sym)
5371 {
5372 /* Check if the symbol was created during loadup. In such a case
5373 it might be pointed to by pure bytecode which we don't trace,
5374 so we conservatively assume that it is live. */
5375 int pure_p = PURE_POINTER_P (XSTRING (sym->xname));
5376
5377 if (!sym->gcmarkbit && !pure_p)
5378 {
5379 *(struct Lisp_Symbol **) &sym->value = symbol_free_list;
5380 symbol_free_list = sym;
5381 #if GC_MARK_STACK
5382 symbol_free_list->function = Vdead;
5383 #endif
5384 ++this_free;
5385 }
5386 else
5387 {
5388 ++num_used;
5389 if (!pure_p)
5390 UNMARK_STRING (XSTRING (sym->xname));
5391 sym->gcmarkbit = 0;
5392 }
5393 }
5394
5395 lim = SYMBOL_BLOCK_SIZE;
5396 /* If this block contains only free symbols and we have already
5397 seen more than two blocks worth of free symbols then deallocate
5398 this block. */
5399 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
5400 {
5401 *sprev = sblk->next;
5402 /* Unhook from the free list. */
5403 symbol_free_list = *(struct Lisp_Symbol **)&sblk->symbols[0].value;
5404 lisp_free (sblk);
5405 n_symbol_blocks--;
5406 }
5407 else
5408 {
5409 num_free += this_free;
5410 sprev = &sblk->next;
5411 }
5412 }
5413 total_symbols = num_used;
5414 total_free_symbols = num_free;
5415 }
5416
5417 /* Put all unmarked misc's on free list.
5418 For a marker, first unchain it from the buffer it points into. */
5419 {
5420 register struct marker_block *mblk;
5421 struct marker_block **mprev = &marker_block;
5422 register int lim = marker_block_index;
5423 register int num_free = 0, num_used = 0;
5424
5425 marker_free_list = 0;
5426
5427 for (mblk = marker_block; mblk; mblk = *mprev)
5428 {
5429 register int i;
5430 int this_free = 0;
5431
5432 for (i = 0; i < lim; i++)
5433 {
5434 if (!mblk->markers[i].u_marker.gcmarkbit)
5435 {
5436 if (mblk->markers[i].u_marker.type == Lisp_Misc_Marker)
5437 unchain_marker (&mblk->markers[i].u_marker);
5438 /* Set the type of the freed object to Lisp_Misc_Free.
5439 We could leave the type alone, since nobody checks it,
5440 but this might catch bugs faster. */
5441 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
5442 mblk->markers[i].u_free.chain = marker_free_list;
5443 marker_free_list = &mblk->markers[i];
5444 this_free++;
5445 }
5446 else
5447 {
5448 num_used++;
5449 mblk->markers[i].u_marker.gcmarkbit = 0;
5450 }
5451 }
5452 lim = MARKER_BLOCK_SIZE;
5453 /* If this block contains only free markers and we have already
5454 seen more than two blocks worth of free markers then deallocate
5455 this block. */
5456 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
5457 {
5458 *mprev = mblk->next;
5459 /* Unhook from the free list. */
5460 marker_free_list = mblk->markers[0].u_free.chain;
5461 lisp_free (mblk);
5462 n_marker_blocks--;
5463 }
5464 else
5465 {
5466 num_free += this_free;
5467 mprev = &mblk->next;
5468 }
5469 }
5470
5471 total_markers = num_used;
5472 total_free_markers = num_free;
5473 }
5474
5475 /* Free all unmarked buffers */
5476 {
5477 register struct buffer *buffer = all_buffers, *prev = 0, *next;
5478
5479 while (buffer)
5480 if (!VECTOR_MARKED_P (buffer))
5481 {
5482 if (prev)
5483 prev->next = buffer->next;
5484 else
5485 all_buffers = buffer->next;
5486 next = buffer->next;
5487 lisp_free (buffer);
5488 buffer = next;
5489 }
5490 else
5491 {
5492 VECTOR_UNMARK (buffer);
5493 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
5494 prev = buffer, buffer = buffer->next;
5495 }
5496 }
5497
5498 /* Free all unmarked vectors */
5499 {
5500 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
5501 total_vector_size = 0;
5502
5503 while (vector)
5504 if (!VECTOR_MARKED_P (vector))
5505 {
5506 if (prev)
5507 prev->next = vector->next;
5508 else
5509 all_vectors = vector->next;
5510 next = vector->next;
5511 lisp_free (vector);
5512 n_vectors--;
5513 vector = next;
5514
5515 }
5516 else
5517 {
5518 VECTOR_UNMARK (vector);
5519 if (vector->size & PSEUDOVECTOR_FLAG)
5520 total_vector_size += (PSEUDOVECTOR_SIZE_MASK & vector->size);
5521 else
5522 total_vector_size += vector->size;
5523 prev = vector, vector = vector->next;
5524 }
5525 }
5526
5527 #ifdef GC_CHECK_STRING_BYTES
5528 if (!noninteractive)
5529 check_string_bytes (1);
5530 #endif
5531 }
5532
5533
5534
5535 \f
5536 /* Debugging aids. */
5537
5538 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
5539 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
5540 This may be helpful in debugging Emacs's memory usage.
5541 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
5542 ()
5543 {
5544 Lisp_Object end;
5545
5546 XSETINT (end, (EMACS_INT) sbrk (0) / 1024);
5547
5548 return end;
5549 }
5550
5551 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
5552 doc: /* Return a list of counters that measure how much consing there has been.
5553 Each of these counters increments for a certain kind of object.
5554 The counters wrap around from the largest positive integer to zero.
5555 Garbage collection does not decrease them.
5556 The elements of the value are as follows:
5557 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
5558 All are in units of 1 = one object consed
5559 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
5560 objects consed.
5561 MISCS include overlays, markers, and some internal types.
5562 Frames, windows, buffers, and subprocesses count as vectors
5563 (but the contents of a buffer's text do not count here). */)
5564 ()
5565 {
5566 Lisp_Object consed[8];
5567
5568 consed[0] = make_number (min (MOST_POSITIVE_FIXNUM, cons_cells_consed));
5569 consed[1] = make_number (min (MOST_POSITIVE_FIXNUM, floats_consed));
5570 consed[2] = make_number (min (MOST_POSITIVE_FIXNUM, vector_cells_consed));
5571 consed[3] = make_number (min (MOST_POSITIVE_FIXNUM, symbols_consed));
5572 consed[4] = make_number (min (MOST_POSITIVE_FIXNUM, string_chars_consed));
5573 consed[5] = make_number (min (MOST_POSITIVE_FIXNUM, misc_objects_consed));
5574 consed[6] = make_number (min (MOST_POSITIVE_FIXNUM, intervals_consed));
5575 consed[7] = make_number (min (MOST_POSITIVE_FIXNUM, strings_consed));
5576
5577 return Flist (8, consed);
5578 }
5579
5580 int suppress_checking;
5581 void
5582 die (msg, file, line)
5583 const char *msg;
5584 const char *file;
5585 int line;
5586 {
5587 fprintf (stderr, "\r\nEmacs fatal error: %s:%d: %s\r\n",
5588 file, line, msg);
5589 abort ();
5590 }
5591 \f
5592 /* Initialization */
5593
5594 void
5595 init_alloc_once ()
5596 {
5597 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
5598 purebeg = PUREBEG;
5599 pure_size = PURESIZE;
5600 pure_bytes_used = 0;
5601 pure_bytes_used_before_overflow = 0;
5602
5603 /* Initialize the list of free aligned blocks. */
5604 free_ablock = NULL;
5605
5606 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
5607 mem_init ();
5608 Vdead = make_pure_string ("DEAD", 4, 4, 0);
5609 #endif
5610
5611 all_vectors = 0;
5612 ignore_warnings = 1;
5613 #ifdef DOUG_LEA_MALLOC
5614 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
5615 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
5616 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
5617 #endif
5618 init_strings ();
5619 init_cons ();
5620 init_symbol ();
5621 init_marker ();
5622 init_float ();
5623 init_intervals ();
5624
5625 #ifdef REL_ALLOC
5626 malloc_hysteresis = 32;
5627 #else
5628 malloc_hysteresis = 0;
5629 #endif
5630
5631 spare_memory = (char *) malloc (SPARE_MEMORY);
5632
5633 ignore_warnings = 0;
5634 gcprolist = 0;
5635 byte_stack_list = 0;
5636 staticidx = 0;
5637 consing_since_gc = 0;
5638 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
5639 #ifdef VIRT_ADDR_VARIES
5640 malloc_sbrk_unused = 1<<22; /* A large number */
5641 malloc_sbrk_used = 100000; /* as reasonable as any number */
5642 #endif /* VIRT_ADDR_VARIES */
5643 }
5644
5645 void
5646 init_alloc ()
5647 {
5648 gcprolist = 0;
5649 byte_stack_list = 0;
5650 #if GC_MARK_STACK
5651 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
5652 setjmp_tested_p = longjmps_done = 0;
5653 #endif
5654 #endif
5655 Vgc_elapsed = make_float (0.0);
5656 gcs_done = 0;
5657 }
5658
5659 void
5660 syms_of_alloc ()
5661 {
5662 DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold,
5663 doc: /* *Number of bytes of consing between garbage collections.
5664 Garbage collection can happen automatically once this many bytes have been
5665 allocated since the last garbage collection. All data types count.
5666
5667 Garbage collection happens automatically only when `eval' is called.
5668
5669 By binding this temporarily to a large number, you can effectively
5670 prevent garbage collection during a part of the program. */);
5671
5672 DEFVAR_INT ("pure-bytes-used", &pure_bytes_used,
5673 doc: /* Number of bytes of sharable Lisp data allocated so far. */);
5674
5675 DEFVAR_INT ("cons-cells-consed", &cons_cells_consed,
5676 doc: /* Number of cons cells that have been consed so far. */);
5677
5678 DEFVAR_INT ("floats-consed", &floats_consed,
5679 doc: /* Number of floats that have been consed so far. */);
5680
5681 DEFVAR_INT ("vector-cells-consed", &vector_cells_consed,
5682 doc: /* Number of vector cells that have been consed so far. */);
5683
5684 DEFVAR_INT ("symbols-consed", &symbols_consed,
5685 doc: /* Number of symbols that have been consed so far. */);
5686
5687 DEFVAR_INT ("string-chars-consed", &string_chars_consed,
5688 doc: /* Number of string characters that have been consed so far. */);
5689
5690 DEFVAR_INT ("misc-objects-consed", &misc_objects_consed,
5691 doc: /* Number of miscellaneous objects that have been consed so far. */);
5692
5693 DEFVAR_INT ("intervals-consed", &intervals_consed,
5694 doc: /* Number of intervals that have been consed so far. */);
5695
5696 DEFVAR_INT ("strings-consed", &strings_consed,
5697 doc: /* Number of strings that have been consed so far. */);
5698
5699 DEFVAR_LISP ("purify-flag", &Vpurify_flag,
5700 doc: /* Non-nil means loading Lisp code in order to dump an executable.
5701 This means that certain objects should be allocated in shared (pure) space. */);
5702
5703 DEFVAR_INT ("undo-limit", &undo_limit,
5704 doc: /* Keep no more undo information once it exceeds this size.
5705 This limit is applied when garbage collection happens.
5706 The size is counted as the number of bytes occupied,
5707 which includes both saved text and other data. */);
5708 undo_limit = 20000;
5709
5710 DEFVAR_INT ("undo-strong-limit", &undo_strong_limit,
5711 doc: /* Don't keep more than this much size of undo information.
5712 A command which pushes past this size is itself forgotten.
5713 This limit is applied when garbage collection happens.
5714 The size is counted as the number of bytes occupied,
5715 which includes both saved text and other data. */);
5716 undo_strong_limit = 30000;
5717
5718 DEFVAR_BOOL ("garbage-collection-messages", &garbage_collection_messages,
5719 doc: /* Non-nil means display messages at start and end of garbage collection. */);
5720 garbage_collection_messages = 0;
5721
5722 DEFVAR_LISP ("post-gc-hook", &Vpost_gc_hook,
5723 doc: /* Hook run after garbage collection has finished. */);
5724 Vpost_gc_hook = Qnil;
5725 Qpost_gc_hook = intern ("post-gc-hook");
5726 staticpro (&Qpost_gc_hook);
5727
5728 DEFVAR_LISP ("memory-signal-data", &Vmemory_signal_data,
5729 doc: /* Precomputed `signal' argument for memory-full error. */);
5730 /* We build this in advance because if we wait until we need it, we might
5731 not be able to allocate the memory to hold it. */
5732 Vmemory_signal_data
5733 = list2 (Qerror,
5734 build_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
5735
5736 DEFVAR_LISP ("memory-full", &Vmemory_full,
5737 doc: /* Non-nil means we are handling a memory-full error. */);
5738 Vmemory_full = Qnil;
5739
5740 staticpro (&Qgc_cons_threshold);
5741 Qgc_cons_threshold = intern ("gc-cons-threshold");
5742
5743 staticpro (&Qchar_table_extra_slots);
5744 Qchar_table_extra_slots = intern ("char-table-extra-slots");
5745
5746 DEFVAR_LISP ("gc-elapsed", &Vgc_elapsed,
5747 doc: /* Accumulated time elapsed in garbage collections.
5748 The time is in seconds as a floating point value.
5749 Programs may reset this to get statistics in a specific period. */);
5750 DEFVAR_INT ("gcs-done", &gcs_done,
5751 doc: /* Accumulated number of garbage collections done.
5752 Programs may reset this to get statistics in a specific period. */);
5753
5754 defsubr (&Scons);
5755 defsubr (&Slist);
5756 defsubr (&Svector);
5757 defsubr (&Smake_byte_code);
5758 defsubr (&Smake_list);
5759 defsubr (&Smake_vector);
5760 defsubr (&Smake_char_table);
5761 defsubr (&Smake_string);
5762 defsubr (&Smake_bool_vector);
5763 defsubr (&Smake_symbol);
5764 defsubr (&Smake_marker);
5765 defsubr (&Spurecopy);
5766 defsubr (&Sgarbage_collect);
5767 defsubr (&Smemory_limit);
5768 defsubr (&Smemory_use_counts);
5769
5770 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5771 defsubr (&Sgc_status);
5772 #endif
5773 }