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