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