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