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