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