Preserve progn-like clauses for coverage
[sbcl.git] / src / runtime / gc-common.c
blob10e8673b190faffae51e1254766cc0d3109ce0c0
1 /*
2 * Garbage Collection common functions for scavenging, moving and sizing
3 * objects. These are for use with both GC (stop & copy GC) and GENCGC
4 */
6 /*
7 * This software is part of the SBCL system. See the README file for
8 * more information.
10 * This software is derived from the CMU CL system, which was
11 * written at Carnegie Mellon University and released into the
12 * public domain. The software is in the public domain and is
13 * provided with absolutely no warranty. See the COPYING and CREDITS
14 * files for more information.
18 * For a review of garbage collection techniques (e.g. generational
19 * GC) and terminology (e.g. "scavenging") see Paul R. Wilson,
20 * "Uniprocessor Garbage Collection Techniques". As of 20000618, this
21 * had been accepted for _ACM Computing Surveys_ and was available
22 * as a PostScript preprint through
23 * <http://www.cs.utexas.edu/users/oops/papers.html>
24 * as
25 * <ftp://ftp.cs.utexas.edu/pub/garbage/bigsurv.ps>.
28 #include <stdio.h>
29 #include <signal.h>
30 #include <string.h>
31 #include "sbcl.h"
32 #include "runtime.h"
33 #include "os.h"
34 #include "interr.h"
35 #include "globals.h"
36 #include "interrupt.h"
37 #include "validate.h"
38 #include "lispregs.h"
39 #include "arch.h"
40 #include "gc.h"
41 #include "genesis/primitive-objects.h"
42 #include "genesis/static-symbols.h"
43 #include "genesis/layout.h"
44 #include "genesis/hash-table.h"
45 #define WANT_SCAV_TRANS_SIZE_TABLES
46 #include "gc-internal.h"
47 #include "forwarding-ptr.h"
48 #include "var-io.h"
50 #ifdef LISP_FEATURE_SPARC
51 #define LONG_FLOAT_SIZE 4
52 #elif defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
53 #define LONG_FLOAT_SIZE 3
54 #endif
56 os_vm_size_t dynamic_space_size = DEFAULT_DYNAMIC_SPACE_SIZE;
57 os_vm_size_t thread_control_stack_size = DEFAULT_CONTROL_STACK_SIZE;
59 sword_t (*scavtab[256])(lispobj *where, lispobj object);
60 lispobj (*transother[256])(lispobj object);
61 sword_t (*sizetab[256])(lispobj *where);
62 struct weak_pointer *weak_pointers;
64 os_vm_size_t bytes_consed_between_gcs = 12*1024*1024;
66 /// These sizing macros return the number of *payload* words,
67 /// exclusive of the object header word. Payload length is always
68 /// an odd number so that total word count is an even number.
69 #define BOXED_NWORDS(obj) (HeaderValue(obj) | 1)
70 // Payload count expressed in 15 bits
71 #define SHORT_BOXED_NWORDS(obj) ((HeaderValue(obj) & SHORT_HEADER_MAX_WORDS) | 1)
72 // Payload count expressed in 8 bits
73 #define TINY_BOXED_NWORDS(obj) ((HeaderValue(obj) & 0xFF) | 1)
76 * copying objects
79 /* gc_general_copy_object is inline from gc-internal.h */
81 /* to copy a boxed object */
82 lispobj
83 copy_object(lispobj object, sword_t nwords)
85 return gc_general_copy_object(object, nwords, BOXED_PAGE_FLAG);
88 lispobj
89 copy_code_object(lispobj object, sword_t nwords)
91 return gc_general_copy_object(object, nwords, CODE_PAGE_FLAG);
94 static sword_t scav_lose(lispobj *where, lispobj object); /* forward decl */
96 static inline void scav1(lispobj* object_ptr, lispobj object)
98 // GENCGC only:
99 // * With 32-bit words, is_lisp_pointer(object) returns true if object_ptr
100 // points to a forwarding pointer, so we need a sanity check inside the
101 // branch for is_lisp_pointer(). For maximum efficiency, check that only
102 // after from_space_p() returns false, so that valid pointers into
103 // from_space incur no extra test. This could be improved further by
104 // skipping the FP check if 'object' points within dynamic space, i.e.,
105 // when find_page_index() returns >= 0. That would entail injecting
106 // from_space_p() explicitly into the loop, so as to separate the
107 // "was a page found at all" condition from the page generation test.
109 // * With 64-bit words, is_lisp_pointer(object) is false when object_ptr
110 // points to a forwarding pointer, and the fixnump() test also returns
111 // false, so we'll indirect through scavtab[]. This will safely invoke
112 // scav_lose(), detecting corruption without any extra cost.
113 // The major difference between that and the explicit test is that you
114 // won't see 'start' and 'n_words', but if you need those, chances are
115 // you'll want to run under an external debugger in the first place.
116 // [And btw it sure would be nice to assert statically
117 // that is_lisp_pointer(0x01) is indeed false]
119 #define FIX_POINTER() { \
120 lispobj *ptr = native_pointer(object); \
121 if (forwarding_pointer_p(ptr)) \
122 *object_ptr = LOW_WORD(forwarding_pointer_value(ptr)); \
123 else /* Scavenge that pointer. */ \
124 (void)scavtab[widetag_of(object)](object_ptr, object); \
126 #ifdef LISP_FEATURE_IMMOBILE_SPACE
127 page_index_t page;
128 // It would be fine, though suboptimal, to use from_space_p() here.
129 // If it returns false, we don't want to call immobile_space_p()
130 // unless the pointer is *not* into dynamic space.
131 if ((page = find_page_index((void*)object)) >= 0) {
132 if (page_table[page].gen == from_space && !pinned_p(object, page))
133 FIX_POINTER();
134 } else if (immobile_space_p(object)) {
135 lispobj *ptr = native_pointer(object);
136 if (immobile_obj_gen_bits(ptr) == from_space)
137 promote_immobile_obj(ptr, 1);
139 #else
140 if (from_space_p(object)) {
141 FIX_POINTER();
142 } else {
143 #if (N_WORD_BITS == 32) && defined(LISP_FEATURE_GENCGC)
144 if (forwarding_pointer_p(object_ptr))
145 lose("unexpected forwarding pointer in scavenge @ %p\n",
146 object_ptr);
147 #endif
148 /* It points somewhere other than oldspace. Leave it
149 * alone. */
151 #endif
154 // Scavenge a block of memory from 'start' to 'end'
155 // that may contain object headers.
156 void heap_scavenge(lispobj *start, lispobj *end)
158 lispobj *object_ptr;
160 for (object_ptr = start; object_ptr < end;) {
161 lispobj object = *object_ptr;
162 if (other_immediate_lowtag_p(object))
163 /* It's some sort of header object or another. */
164 object_ptr += (scavtab[widetag_of(object)])(object_ptr, object);
165 else { // it's a cons
166 if (is_lisp_pointer(object))
167 scav1(object_ptr, object);
168 object = *++object_ptr;
169 if (is_lisp_pointer(object))
170 scav1(object_ptr, object);
171 ++object_ptr;
174 // This assertion is usually the one that fails when something
175 // is subtly wrong with the heap, so definitely always do it.
176 gc_assert_verbose(object_ptr == end, "Final object pointer %p, start %p, end %p\n",
177 object_ptr, start, end);
180 // Scavenge a block of memory from 'start' extending for 'n_words'
181 // that must not contain any object headers.
182 sword_t scavenge(lispobj *start, sword_t n_words)
184 lispobj *end = start + n_words;
185 lispobj *object_ptr;
186 for (object_ptr = start; object_ptr < end; object_ptr++) {
187 lispobj object = *object_ptr;
188 if (is_lisp_pointer(object)) scav1(object_ptr, object);
190 return n_words;
193 static lispobj trans_fun_header(lispobj object); /* forward decls */
194 static lispobj trans_short_boxed(lispobj object);
196 static sword_t
197 scav_fun_pointer(lispobj *where, lispobj object)
199 gc_dcheck(lowtag_of(object) == FUN_POINTER_LOWTAG);
201 /* Object is a pointer into from_space - not a FP. */
202 lispobj *first_pointer = native_pointer(object);
204 /* must transport object -- object may point to either a function
205 * header, a funcallable instance header, or a closure header. */
206 lispobj copy = widetag_of(*first_pointer) == SIMPLE_FUN_WIDETAG
207 ? trans_fun_header(object) : trans_short_boxed(object);
209 if (copy != object) {
210 /* Set forwarding pointer */
211 set_forwarding_pointer(first_pointer,copy);
214 CHECK_COPY_POSTCONDITIONS(copy, FUN_POINTER_LOWTAG);
216 *where = copy;
218 return 1;
222 static struct code *
223 trans_code(struct code *code)
225 /* if object has already been transported, just return pointer */
226 if (forwarding_pointer_p((lispobj *)code)) {
227 #ifdef DEBUG_CODE_GC
228 printf("Was already transported\n");
229 #endif
230 return (struct code *)native_pointer(forwarding_pointer_value((lispobj*)code));
233 gc_dcheck(widetag_of(code->header) == CODE_HEADER_WIDETAG);
235 /* prepare to transport the code vector */
236 lispobj l_code = (lispobj) LOW_WORD(code) | OTHER_POINTER_LOWTAG;
237 sword_t nheader_words = code_header_words(code->header);
238 sword_t ncode_words = code_instruction_words(code->code_size);
239 sword_t nwords = nheader_words + ncode_words;
240 lispobj l_new_code = copy_code_object(l_code, nwords);
241 struct code *new_code = (struct code *) native_pointer(l_new_code);
243 #if defined(DEBUG_CODE_GC)
244 printf("Old code object at 0x%08x, new code object at 0x%08x.\n",
245 (uword_t) code, (uword_t) new_code);
246 printf("Code object is %d words long.\n", nwords);
247 #endif
249 #ifdef LISP_FEATURE_GENCGC
250 if (new_code == code)
251 return new_code;
252 #endif
254 set_forwarding_pointer((lispobj *)code, l_new_code);
256 /* set forwarding pointers for all the function headers in the */
257 /* code object. also fix all self pointers */
258 /* Do this by scanning the new code, since the old header is unusable */
260 uword_t displacement = l_new_code - l_code;
262 for_each_simple_fun(i, nfheaderp, new_code, 1, {
263 /* Calculate the old raw function pointer */
264 struct simple_fun* fheaderp =
265 (struct simple_fun*)LOW_WORD((char*)nfheaderp - displacement);
266 /* Calculate the new lispobj */
267 lispobj nfheaderl = make_lispobj(nfheaderp, FUN_POINTER_LOWTAG);
269 #ifdef DEBUG_CODE_GC
270 printf("fheaderp->header (at %x) <- %x\n",
271 &(fheaderp->header) , nfheaderl);
272 #endif
273 set_forwarding_pointer((lispobj *)fheaderp, nfheaderl);
275 /* fix self pointer. */
276 nfheaderp->self =
277 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
278 FUN_RAW_ADDR_OFFSET +
279 #endif
280 nfheaderl;
282 #ifdef LISP_FEATURE_GENCGC
283 /* Cheneygc doesn't need this os_flush_icache, it flushes the whole
284 spaces once when all copying is done. */
285 os_flush_icache((os_vm_address_t) (((sword_t *)new_code) + nheader_words),
286 ncode_words * sizeof(sword_t));
288 #endif
290 #ifdef LISP_FEATURE_X86
291 gencgc_apply_code_fixups(code, new_code);
292 #endif
294 return new_code;
297 static sword_t
298 scav_code_header(lispobj *where, lispobj header)
300 struct code *code = (struct code *) where;
301 sword_t n_header_words = code_header_words(header);
303 /* Scavenge the boxed section of the code data block. */
304 scavenge(where + 1, n_header_words - 1);
306 /* Scavenge the boxed section of each function object in the
307 * code data block. */
308 for_each_simple_fun(i, function_ptr, code, 1, {
309 scavenge(SIMPLE_FUN_SCAV_START(function_ptr),
310 SIMPLE_FUN_SCAV_NWORDS(function_ptr));
313 return n_header_words + code_instruction_words(code->code_size);
316 static lispobj
317 trans_code_header(lispobj object)
319 struct code *ncode = trans_code((struct code *) native_pointer(object));
320 return (lispobj) LOW_WORD(ncode) | OTHER_POINTER_LOWTAG;
323 static sword_t
324 size_code_header(lispobj *where)
326 return code_header_words(((struct code *)where)->header)
327 + code_instruction_words(((struct code *)where)->code_size);
330 #ifdef RETURN_PC_WIDETAG
331 static sword_t
332 scav_return_pc_header(lispobj *where, lispobj object)
334 lose("attempted to scavenge a return PC header where=%p object=%#lx\n",
335 where, (uword_t) object);
336 return 0; /* bogus return value to satisfy static type checking */
339 static lispobj
340 trans_return_pc_header(lispobj object)
342 struct simple_fun *return_pc = (struct simple_fun *) native_pointer(object);
343 uword_t offset = HeaderValue(return_pc->header) * N_WORD_BYTES;
345 /* Transport the whole code object */
346 struct code *code = (struct code *) ((uword_t) return_pc - offset);
347 struct code *ncode = trans_code(code);
349 return ((lispobj) LOW_WORD(ncode) + offset) | OTHER_POINTER_LOWTAG;
351 #endif /* RETURN_PC_WIDETAG */
353 /* On the 386, closures hold a pointer to the raw address instead of the
354 * function object, so we can use CALL [$FDEFN+const] to invoke
355 * the function without loading it into a register. Given that code
356 * objects don't move, we don't need to update anything, but we do
357 * have to figure out that the function is still live. */
359 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
360 static sword_t
361 scav_closure(lispobj *where, lispobj header)
363 struct closure *closure = (struct closure *)where;
364 int payload_words = SHORT_BOXED_NWORDS(header);
365 lispobj fun = closure->fun - FUN_RAW_ADDR_OFFSET;
366 scavenge(&fun, 1);
367 #ifdef LISP_FEATURE_GENCGC
368 /* The function may have moved so update the raw address. But
369 * don't write unnecessarily. */
370 if (closure->fun != fun + FUN_RAW_ADDR_OFFSET)
371 closure->fun = fun + FUN_RAW_ADDR_OFFSET;
372 #endif
373 // Payload includes 'fun' which was just looked at, so subtract it.
374 scavenge(closure->info, payload_words - 1);
375 return 1 + payload_words;
377 #endif
379 #if !(defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
380 static sword_t
381 scav_fun_header(lispobj *where, lispobj object)
383 lose("attempted to scavenge a function header where=%p object=%#lx\n",
384 where, (uword_t) object);
385 return 0; /* bogus return value to satisfy static type checking */
387 #endif /* LISP_FEATURE_X86 */
389 static lispobj
390 trans_fun_header(lispobj object)
392 struct simple_fun *fheader = (struct simple_fun *) native_pointer(object);
393 uword_t offset = HeaderValue(fheader->header) * N_WORD_BYTES;
395 /* Transport the whole code object */
396 struct code *code = (struct code *) ((uword_t) fheader - offset);
397 struct code *ncode = trans_code(code);
399 return ((lispobj) LOW_WORD(ncode) + offset) | FUN_POINTER_LOWTAG;
404 * instances
407 static lispobj
408 trans_instance(lispobj object)
410 gc_dcheck(lowtag_of(object) == INSTANCE_POINTER_LOWTAG);
411 lispobj header = *(lispobj*)(object - INSTANCE_POINTER_LOWTAG);
412 return copy_object(object, 1 + (instance_length(header)|1));
415 static sword_t
416 scav_instance_pointer(lispobj *where, lispobj object)
418 /* Object is a pointer into from space - not a FP. */
419 lispobj copy = trans_instance(object);
421 gc_dcheck(copy != object);
423 set_forwarding_pointer(native_pointer(object), copy);
424 *where = copy;
426 return 1;
431 * lists and conses
434 static lispobj trans_list(lispobj object);
436 static sword_t
437 scav_list_pointer(lispobj *where, lispobj object)
439 gc_dcheck(lowtag_of(object) == LIST_POINTER_LOWTAG);
441 lispobj copy = trans_list(object);
442 gc_dcheck(copy != object);
444 CHECK_COPY_POSTCONDITIONS(copy, LIST_POINTER_LOWTAG);
446 *where = copy;
447 return 1;
451 static lispobj
452 trans_list(lispobj object)
454 /* Copy 'object'. */
455 struct cons *copy = (struct cons *)
456 gc_general_alloc(sizeof(struct cons), BOXED_PAGE_FLAG, ALLOC_QUICK);
457 lispobj new_list_pointer = make_lispobj(copy, LIST_POINTER_LOWTAG);
458 copy->car = CONS(object)->car;
459 /* Grab the cdr: set_forwarding_pointer will clobber it in GENCGC */
460 lispobj cdr = CONS(object)->cdr;
461 set_forwarding_pointer((lispobj *)CONS(object), new_list_pointer);
463 /* Try to linearize the list in the cdr direction to help reduce
464 * paging. */
465 while (lowtag_of(cdr) == LIST_POINTER_LOWTAG && from_space_p(cdr)) {
466 lispobj* native_cdr = (lispobj*)CONS(cdr);
467 if (forwarding_pointer_p(native_cdr)) { // Might as well fix now.
468 cdr = forwarding_pointer_value(native_cdr);
469 break;
471 /* Copy 'cdr'. */
472 struct cons *cdr_copy = (struct cons*)
473 gc_general_alloc(sizeof(struct cons), BOXED_PAGE_FLAG, ALLOC_QUICK);
474 cdr_copy->car = ((struct cons*)native_cdr)->car;
475 /* Grab the cdr before it is clobbered. */
476 lispobj next = ((struct cons*)native_cdr)->cdr;
477 /* Set cdr of the predecessor, and store an FP. */
478 set_forwarding_pointer(native_cdr,
479 copy->cdr = make_lispobj(cdr_copy,
480 LIST_POINTER_LOWTAG));
481 copy = cdr_copy;
482 cdr = next;
484 copy->cdr = cdr;
485 return new_list_pointer;
490 * scavenging and transporting other pointers
493 static sword_t
494 scav_other_pointer(lispobj *where, lispobj object)
496 gc_dcheck(lowtag_of(object) == OTHER_POINTER_LOWTAG);
498 /* Object is a pointer into from space - not FP. */
499 lispobj *first_pointer = (lispobj *)(object - OTHER_POINTER_LOWTAG);
500 lispobj copy = transother[widetag_of(*first_pointer)](object);
502 // If the object was large, then instead of transporting it,
503 // gencgc might simply promote the pages and return the same pointer.
504 // That decision is made in general_copy_large_object().
505 if (copy != object) {
506 set_forwarding_pointer(first_pointer, copy);
507 #ifdef LISP_FEATURE_GENCGC
508 *where = copy;
509 #endif
511 #ifndef LISP_FEATURE_GENCGC
512 *where = copy;
513 #endif
514 CHECK_COPY_POSTCONDITIONS(copy, OTHER_POINTER_LOWTAG);
515 return 1;
519 * immediate, boxed, and unboxed objects
522 /* The immediate object scavenger basically wants to be "scav_cons",
523 * and so returns 2. To see why it's right, observe that scavenge() will
524 * not invoke a scavtab entry on any object except for one satisfying
525 * is_lisp_pointer(). So if a scavtab[] function got here,
526 * then it must be via heap_scavenge(). But heap_scavenge() should only
527 * dispatch via scavtab[] if it thought it saw an object header.
528 * So why do we act like it saw a cons? Because conses can contain an
529 * immediate object that satisfies both other_immediate_lowtag_p()
530 * and is_lisp_immediate(), namely, the objects specifically mentioned at
531 * is_cons_half(). So heap_scavenge() is nearly testing is_cons_half()
532 * but even more efficiently, by ignoring the unusual immediate widetags
533 * until we get to scav_immediate.
535 * And just to hammer the point home: we won't blow past the end of a specific
536 * range of words when scavenging a binding or control stack or anything else,
537 * because scavenge() skips immediate objects all by itself,
538 * or rather it skips anything not satisfying is_lisp_pointer().
540 * As to the unbound marker, see rev. 09c78105eabc6bf2b339f421d4ed1df4678003db
541 * which says that we might see it in conses for reasons somewhat unknown.
543 static sword_t
544 scav_immediate(lispobj *where, lispobj object)
546 object = *++where;
547 if (is_lisp_pointer(object)) scav1(where, object);
548 return 2;
551 static lispobj
552 trans_immediate(lispobj object)
554 lose("trying to transport an immediate\n");
555 return NIL; /* bogus return value to satisfy static type checking */
558 static sword_t
559 size_immediate(lispobj *where)
561 return 1;
564 static inline boolean bignum_logbitp_inline(int index, struct bignum* bignum)
566 int len = HeaderValue(bignum->header);
567 int word_index = index / N_WORD_BITS;
568 int bit_index = index % N_WORD_BITS;
569 return word_index < len ? (bignum->digits[word_index] >> bit_index) & 1 : 0;
571 boolean positive_bignum_logbitp(int index, struct bignum* bignum)
573 /* If the bignum in the layout has another pointer to it (besides the layout)
574 acting as a root, and which is scavenged first, then transporting the
575 bignum causes the layout to see a FP, as would copying an instance whose
576 layout that is. This is a nearly impossible scenario to create organically
577 in Lisp, because mostly nothing ever looks again at that exact (EQ) bignum
578 except for a few things that would cause it to be pinned anyway,
579 such as it being kept in a local variable during structure manipulation.
580 See 'interleaved-raw.impure.lisp' for a way to trigger this */
581 if (forwarding_pointer_p((lispobj*)bignum)) {
582 lispobj forwarded = forwarding_pointer_value((lispobj*)bignum);
583 #if 0
584 fprintf(stderr, "GC bignum_logbitp(): fwd from %p to %p\n",
585 (void*)bignum, (void*)forwarded);
586 #endif
587 bignum = (struct bignum*)native_pointer(forwarded);
589 return bignum_logbitp_inline(index, bignum);
592 // Helper function for stepping through the tagged slots of an instance in
593 // scav_instance and verify_space.
594 void
595 instance_scan(void (*proc)(lispobj*, sword_t),
596 lispobj *instance_slots,
597 sword_t nslots, /* number of payload words */
598 lispobj layout_bitmap)
600 sword_t index;
602 if (fixnump(layout_bitmap)) {
603 sword_t bitmap = (sword_t)layout_bitmap >> N_FIXNUM_TAG_BITS; // signed integer!
604 for (index = 0; index < nslots ; index++, bitmap >>= 1)
605 if (bitmap & 1)
606 proc(instance_slots + index, 1);
607 } else { /* huge bitmap */
608 struct bignum * bitmap;
609 bitmap = (struct bignum*)native_pointer(layout_bitmap);
610 if (forwarding_pointer_p((lispobj*)bitmap))
611 bitmap = (struct bignum*)
612 native_pointer(forwarding_pointer_value((lispobj*)bitmap));
613 for (index = 0; index < nslots ; index++)
614 if (bignum_logbitp_inline(index, bitmap))
615 proc(instance_slots + index, 1);
619 static sword_t
620 scav_instance(lispobj *where, lispobj header)
622 lispobj* layout = (lispobj*)instance_layout(where);
623 lispobj lbitmap = make_fixnum(-1);
625 if (layout) {
626 layout = native_pointer((lispobj)layout);
627 #ifdef LISP_FEATURE_COMPACT_INSTANCE_HEADER
628 if (__immobile_obj_gen_bits(layout) == from_space)
629 promote_immobile_obj(layout, 1);
630 #else
631 if (forwarding_pointer_p(layout))
632 layout = native_pointer(forwarding_pointer_value(layout));
633 #endif
634 lbitmap = ((struct layout*)layout)->bitmap;
636 sword_t nslots = instance_length(header) | 1;
637 if (lbitmap == make_fixnum(-1))
638 scavenge(where+1, nslots);
639 else if (!fixnump(lbitmap))
640 instance_scan((void(*)(lispobj*,sword_t))scavenge,
641 where+1, nslots, lbitmap);
642 else {
643 sword_t bitmap = (sword_t)lbitmap >> N_FIXNUM_TAG_BITS; // signed integer!
644 sword_t n = nslots;
645 lispobj obj;
646 for ( ; n-- ; bitmap >>= 1) {
647 ++where;
648 if ((bitmap & 1) && is_lisp_pointer(obj = *where))
649 scav1(where, obj);
652 return 1 + nslots;
655 #ifdef LISP_FEATURE_COMPACT_INSTANCE_HEADER
656 static sword_t
657 scav_funinstance(lispobj *where, lispobj header)
659 // This works because the layout is in the header word of all instances,
660 // ordinary and funcallable, when compact headers are enabled.
661 // The trampoline slot in the funcallable-instance is raw, but can be
662 // scavenged, because it points to readonly space, never oldspace.
663 // (And for certain backends it looks like a fixnum, not a pointer)
664 return scav_instance(where, header);
666 #endif
668 //// Boxed object scav/trans/size functions
670 #define DEF_SCAV_BOXED(suffix, sizer) \
671 static sword_t __attribute__((unused)) \
672 scav_##suffix(lispobj *where, lispobj header) { \
673 return 1 + scavenge(where+1, sizer(header)); \
675 static lispobj trans_##suffix(lispobj object) { \
676 return copy_object(object, 1 + sizer(*native_pointer(object))); \
678 static sword_t size_##suffix(lispobj *where) { return 1 + sizer(*where); }
680 DEF_SCAV_BOXED(boxed, BOXED_NWORDS)
681 DEF_SCAV_BOXED(short_boxed, SHORT_BOXED_NWORDS)
682 DEF_SCAV_BOXED(tiny_boxed, TINY_BOXED_NWORDS)
684 /* Note: on the sparc we don't have to do anything special for fdefns, */
685 /* 'cause the raw-addr has a function lowtag. */
686 #if !defined(LISP_FEATURE_SPARC) && !defined(LISP_FEATURE_ARM)
687 static sword_t
688 scav_fdefn(lispobj *where, lispobj object)
690 struct fdefn *fdefn = (struct fdefn *)where;
692 /* FSHOW((stderr, "scav_fdefn, function = %p, raw_addr = %p\n",
693 fdefn->fun, fdefn->raw_addr)); */
695 scavenge(where + 1, 2); // 'name' and 'fun'
696 #ifndef LISP_FEATURE_IMMOBILE_CODE
697 lispobj raw_fun = (lispobj)fdefn->raw_addr;
698 if (raw_fun > READ_ONLY_SPACE_END) {
699 lispobj simple_fun = raw_fun - FUN_RAW_ADDR_OFFSET;
700 scavenge(&simple_fun, 1);
701 /* Don't write unnecessarily. */
702 if (simple_fun != raw_fun - FUN_RAW_ADDR_OFFSET)
703 fdefn->raw_addr = (char *)simple_fun + FUN_RAW_ADDR_OFFSET;
705 #elif defined(LISP_FEATURE_X86_64)
706 lispobj obj = fdefn_raw_referent(fdefn);
707 if (obj) {
708 lispobj new = obj;
709 scavenge(&new, 1); // enliven
710 gc_dcheck(new == obj); // must not move
712 #else
713 # error "Need to implement scav_fdefn"
714 #endif
715 return 4;
717 #endif
719 static sword_t
720 scav_unboxed(lispobj *where, lispobj object)
722 sword_t length = HeaderValue(object) + 1;
723 return CEILING(length, 2);
726 static lispobj
727 trans_unboxed(lispobj object)
729 gc_dcheck(lowtag_of(object) == OTHER_POINTER_LOWTAG);
730 sword_t length = HeaderValue(*native_pointer(object)) + 1;
731 return copy_unboxed_object(object, CEILING(length, 2));
734 static lispobj
735 trans_ratio_or_complex(lispobj object)
737 gc_dcheck(lowtag_of(object) == OTHER_POINTER_LOWTAG);
738 lispobj* x = native_pointer(object);
739 lispobj a = x[1];
740 lispobj b = x[2];
742 /* A zero ratio or complex means it was just allocated by fixed-alloc and
743 a bignum can still be written there. Not a problem with a conservative GC
744 since it will be pinned down. */
745 if (fixnump(a) && fixnump(b)
746 #ifndef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
747 && a && b
748 #endif
751 return copy_unboxed_object(object, 4);
753 return copy_object(object, 4);
756 /* vector-like objects */
757 static lispobj
758 trans_vector(lispobj object)
760 gc_dcheck(lowtag_of(object) == OTHER_POINTER_LOWTAG);
762 sword_t length =
763 fixnum_value(((struct vector*)native_pointer(object))->length);
764 return copy_large_object(object, CEILING(length + 2, 2));
767 static sword_t
768 size_vector(lispobj *where)
770 sword_t length = fixnum_value(((struct vector*)where)->length);
771 return CEILING(length + 2, 2);
774 static inline uword_t
775 NWORDS(uword_t x, uword_t n_bits)
777 /* A good compiler should be able to constant-fold this whole thing,
778 even with the conditional. */
779 if(n_bits <= N_WORD_BITS) {
780 uword_t elements_per_word = N_WORD_BITS/n_bits;
782 return CEILING(x, elements_per_word)/elements_per_word;
784 else {
785 /* FIXME: should have some sort of assertion that N_WORD_BITS
786 evenly divides n_bits */
787 return x * (n_bits/N_WORD_BITS);
791 #define DEF_SCAV_TRANS_SIZE_UB(nbits) \
792 DEF_SPECIALIZED_VECTOR(vector_unsigned_byte_##nbits, NWORDS(length, nbits))
793 #define DEF_SPECIALIZED_VECTOR(name, nwords) \
794 static sword_t __attribute__((unused)) scav_##name(lispobj *where, lispobj header) { \
795 sword_t length = fixnum_value(((struct vector*)where)->length); \
796 return CEILING(nwords + 2, 2); \
798 static lispobj __attribute__((unused)) trans_##name(lispobj object) { \
799 gc_dcheck(lowtag_of(object) == OTHER_POINTER_LOWTAG); \
800 sword_t length = fixnum_value(((struct vector*)(object-OTHER_POINTER_LOWTAG))->length); \
801 return copy_large_unboxed_object(object, CEILING(nwords + 2, 2)); \
803 static sword_t __attribute__((unused)) size_##name(lispobj *where) { \
804 sword_t length = fixnum_value(((struct vector*)where)->length); \
805 return CEILING(nwords + 2, 2); \
808 DEF_SPECIALIZED_VECTOR(vector_nil, 0*length)
809 DEF_SPECIALIZED_VECTOR(vector_bit, NWORDS(length,1))
810 /* NOTE: strings contain one more element of data (a terminating '\0'
811 * to help interface with C functions) than indicated by the length slot.
812 * This is true even for UCS4 strings, despite that C APIs are unlikely
813 * to have a convention that expects 4 zero bytes. */
814 DEF_SPECIALIZED_VECTOR(base_string, NWORDS((length+1), 8))
815 DEF_SPECIALIZED_VECTOR(character_string, NWORDS((length+1), 32))
816 DEF_SCAV_TRANS_SIZE_UB(2)
817 DEF_SCAV_TRANS_SIZE_UB(4)
818 DEF_SCAV_TRANS_SIZE_UB(8)
819 DEF_SCAV_TRANS_SIZE_UB(16)
820 DEF_SCAV_TRANS_SIZE_UB(32)
821 DEF_SCAV_TRANS_SIZE_UB(64)
822 DEF_SCAV_TRANS_SIZE_UB(128)
823 #ifdef LONG_FLOAT_SIZE
824 DEF_SPECIALIZED_VECTOR(vector_long_float, length * LONG_FLOAT_SIZE)
825 DEF_SPECIALIZED_VECTOR(vector_complex_long_float, length * (2 * LONG_FLOAT_SIZE))
826 #endif
828 static lispobj
829 trans_weak_pointer(lispobj object)
831 lispobj copy;
832 gc_dcheck(lowtag_of(object) == OTHER_POINTER_LOWTAG);
834 #if defined(DEBUG_WEAK)
835 printf("Transporting weak pointer from 0x%08x\n", object);
836 #endif
838 /* Need to remember where all the weak pointers are that have */
839 /* been transported so they can be fixed up in a post-GC pass. */
841 copy = copy_object(object, WEAK_POINTER_NWORDS);
842 #ifndef LISP_FEATURE_GENCGC
843 struct weak_pointer *wp = (struct weak_pointer *) native_pointer(copy);
845 gc_dcheck(widetag_of(wp->header)==WEAK_POINTER_WIDETAG);
846 /* Push the weak pointer onto the list of weak pointers. */
847 if (weak_pointer_breakable_p(wp)) {
848 wp->next = (struct weak_pointer *)LOW_WORD(weak_pointers);
849 weak_pointers = wp;
851 #endif
852 return copy;
855 void scan_weak_pointers(void)
857 struct weak_pointer *wp, *next_wp;
858 for (wp = weak_pointers, next_wp = NULL; wp != NULL; wp = next_wp) {
859 gc_assert(widetag_of(wp->header)==WEAK_POINTER_WIDETAG);
861 next_wp = wp->next;
862 wp->next = NULL;
863 if (next_wp == wp) /* gencgc uses a ref to self for end of list */
864 next_wp = NULL;
866 lispobj pointee = wp->value;
867 gc_assert(is_lisp_pointer(pointee));
868 lispobj *objaddr = native_pointer(pointee);
870 /* Now, we need to check whether the object has been forwarded. If
871 * it has been, the weak pointer is still good and needs to be
872 * updated. Otherwise, the weak pointer needs to be broken. */
874 if (from_space_p(pointee)) {
875 wp->value = forwarding_pointer_p(objaddr) ?
876 LOW_WORD(forwarding_pointer_value(objaddr)) : UNBOUND_MARKER_WIDETAG;
878 #ifdef LISP_FEATURE_IMMOBILE_SPACE
879 else if (immobile_space_p(pointee) &&
880 immobile_obj_gen_bits(objaddr) == from_space) {
881 wp->value = UNBOUND_MARKER_WIDETAG;
883 #endif
884 else
885 lose("unbreakable pointer %p", wp);
890 /* Hash tables */
892 #if N_WORD_BITS == 32
893 #define EQ_HASH_MASK 0x1fffffff
894 #elif N_WORD_BITS == 64
895 #define EQ_HASH_MASK 0x1fffffffffffffff
896 #endif
898 /* Compute the EQ-hash of KEY. This must match POINTER-HASH in
899 * target-hash-table.lisp. */
900 #define EQ_HASH(key) ((key) & EQ_HASH_MASK)
902 /* List of weak hash tables chained through their NEXT-WEAK-HASH-TABLE
903 * slot. Set to NULL at the end of a collection.
905 * This is not optimal because, when a table is tenured, it won't be
906 * processed automatically; only the yougest generation is GC'd by
907 * default. On the other hand, all applications will need an
908 * occasional full GC anyway, so it's not that bad either. */
909 struct hash_table *weak_hash_tables = NULL;
911 /* Return true if OBJ has already survived the current GC. */
912 static inline int pointer_survived_gc_yet(lispobj obj)
914 #ifdef LISP_FEATURE_CHENEYGC
915 // This is the most straightforward definition.
916 return (!from_space_p(obj) || forwarding_pointer_p(native_pointer(obj)));
917 #else
918 /* Check for a pointer to dynamic space before considering immobile space.
919 Based on the relative size of the spaces, this should be a win because
920 if the object is in the dynamic space and not the 'from' generation
921 we don't want to test immobile_space_p() at all.
922 Additionally, pinned_p() is both more expensive and less likely than
923 forwarding_pointer_p(), so we want to reverse those conditions, which
924 would not be possible with pinned_p() buried inside from_space_p(). */
925 page_index_t page_index = find_page_index((void*)obj);
926 if (page_index >= 0)
927 return page_table[page_index].gen != from_space ||
928 forwarding_pointer_p(native_pointer(obj)) ||
929 pinned_p(obj, page_index);
930 #ifdef LISP_FEATURE_IMMOBILE_SPACE
931 if (immobile_space_p(obj))
932 return immobile_obj_gen_bits(native_pointer(obj)) != from_space;
933 #endif
934 return 1;
935 #endif
938 #ifdef EMPTY_HT_SLOT /* only if it's a static symbol */
939 // "ish" because EMPTY_HT_SLOT is of course a pointer.
940 # define ht_cell_nonpointerish(x) (!is_lisp_pointer(x) || x==EMPTY_HT_SLOT)
941 #else
942 # define ht_cell_nonpointerish(x) !is_lisp_pointer(x)
943 #endif
945 static int survived_gc_yet_KEY(lispobj key, lispobj value) {
946 return ht_cell_nonpointerish(key) || pointer_survived_gc_yet(key);
948 static int survived_gc_yet_VALUE(lispobj key, lispobj value) {
949 return ht_cell_nonpointerish(value) || pointer_survived_gc_yet(value);
951 static int survived_gc_yet_AND(lispobj key, lispobj value) {
952 int key_nonpointer = ht_cell_nonpointerish(key);
953 int val_nonpointer = ht_cell_nonpointerish(value);
954 if (key_nonpointer && val_nonpointer) return 1;
955 return (key_nonpointer || pointer_survived_gc_yet(key))
956 && (val_nonpointer || pointer_survived_gc_yet(value));
958 static int survived_gc_yet_OR(lispobj key, lispobj value) {
959 int key_nonpointer = ht_cell_nonpointerish(key);
960 int val_nonpointer = ht_cell_nonpointerish(value);
961 if (key_nonpointer || val_nonpointer) return 1;
962 // Both MUST be pointers
963 return pointer_survived_gc_yet(key) || pointer_survived_gc_yet(value);
966 static int (*weak_hash_entry_alivep_fun(lispobj weakness))(lispobj,lispobj)
968 switch (weakness) {
969 case KEY: return survived_gc_yet_KEY;
970 case VALUE: return survived_gc_yet_VALUE;
971 case KEY_OR_VALUE: return survived_gc_yet_OR;
972 case KEY_AND_VALUE: return survived_gc_yet_AND;
973 case NIL: return NULL;
974 default: lose("Bad hash table weakness");
978 /* Return the beginning of data in ARRAY (skipping the header and the
979 * length) or NULL if it isn't an array of the specified widetag after
980 * all. */
981 static inline lispobj *
982 get_array_data (lispobj array, int widetag, uword_t *length)
984 if (is_lisp_pointer(array) && widetag_of(*native_pointer(array)) == widetag) {
985 if (length != NULL)
986 *length = fixnum_value(native_pointer(array)[1]);
987 return native_pointer(array) + 2;
988 } else {
989 return NULL;
993 /* Only need to worry about scavenging the _real_ entries in the
994 * table. Phantom entries such as the hash table itself at index 0 and
995 * the empty marker at index 1 were scavenged by scav_vector that
996 * either called this function directly or arranged for it to be
997 * called later by pushing the hash table onto weak_hash_tables. */
998 static void
999 scav_hash_table_entries (struct hash_table *hash_table)
1001 lispobj *kv_vector;
1002 uword_t kv_length;
1003 lispobj *index_vector;
1004 uword_t length;
1005 lispobj *next_vector;
1006 uword_t next_vector_length;
1007 lispobj *hash_vector;
1008 uword_t hash_vector_length;
1009 lispobj empty_symbol;
1010 lispobj weakness = hash_table->weakness;
1011 uword_t i;
1013 kv_vector = get_array_data(hash_table->table,
1014 SIMPLE_VECTOR_WIDETAG, &kv_length);
1015 if (kv_vector == NULL)
1016 lose("invalid kv_vector %x\n", hash_table->table);
1018 index_vector = get_array_data(hash_table->index_vector,
1019 SIMPLE_ARRAY_WORD_WIDETAG, &length);
1020 if (index_vector == NULL)
1021 lose("invalid index_vector %x\n", hash_table->index_vector);
1023 next_vector = get_array_data(hash_table->next_vector,
1024 SIMPLE_ARRAY_WORD_WIDETAG,
1025 &next_vector_length);
1026 if (next_vector == NULL)
1027 lose("invalid next_vector %x\n", hash_table->next_vector);
1029 hash_vector = get_array_data(hash_table->hash_vector,
1030 SIMPLE_ARRAY_WORD_WIDETAG,
1031 &hash_vector_length);
1032 if (hash_vector != NULL)
1033 gc_assert(hash_vector_length == next_vector_length);
1035 /* These lengths could be different as the index_vector can be a
1036 * different length from the others, a larger index_vector could
1037 * help reduce collisions. */
1038 gc_assert(next_vector_length*2 == kv_length);
1040 empty_symbol = kv_vector[1];
1041 /* fprintf(stderr,"* empty_symbol = %x\n", empty_symbol);*/
1042 if (widetag_of(*native_pointer(empty_symbol)) != SYMBOL_WIDETAG) {
1043 lose("not a symbol where empty-hash-table-slot symbol expected: %x\n",
1044 *native_pointer(empty_symbol));
1047 /* Work through the KV vector. */
1048 int (*alivep_test)(lispobj,lispobj) = weak_hash_entry_alivep_fun(weakness);
1049 #define SCAV_ENTRIES(aliveness_predicate) \
1050 for (i = 1; i < next_vector_length; i++) { \
1051 lispobj old_key = kv_vector[2*i]; \
1052 lispobj __attribute__((unused)) value = kv_vector[2*i+1]; \
1053 if (aliveness_predicate) { \
1054 /* Scavenge the key and value. */ \
1055 scavenge(&kv_vector[2*i], 2); \
1056 /* If an EQ-based key has moved, mark the hash-table for rehash */ \
1057 if (!hash_vector || hash_vector[i] == MAGIC_HASH_VECTOR_VALUE) { \
1058 lispobj new_key = kv_vector[2*i]; \
1059 if (old_key != new_key && new_key != empty_symbol) \
1060 hash_table->needs_rehash_p = T; \
1062 if (alivep_test)
1063 SCAV_ENTRIES(alivep_test(old_key, value))
1064 else
1065 SCAV_ENTRIES(1)
1068 sword_t
1069 scav_vector (lispobj *where, lispobj object)
1071 sword_t kv_length = fixnum_value(where[1]);
1072 struct hash_table *hash_table;
1074 /* SB-VM:VECTOR-VALID-HASHING-SUBTYPE is set for EQ-based and weak
1075 * hash tables in the Lisp HASH-TABLE code to indicate need for
1076 * special GC support. */
1077 if ((HeaderValue(object) & 0xFF) == subtype_VectorNormal) {
1078 normal:
1079 scavenge(where + 2, kv_length);
1080 return CEILING(kv_length + 2, 2);
1083 /* Scavenge element 0, which may be a hash-table structure. */
1084 scavenge(where+2, 1);
1085 if (!is_lisp_pointer(where[2])) {
1086 /* This'll happen when REHASH clears the header of old-kv-vector
1087 * and fills it with zero, but some other thread simulatenously
1088 * sets the header in %%PUTHASH.
1090 fprintf(stderr,
1091 "Warning: no pointer at %p in hash table: this indicates "
1092 "non-fatal corruption caused by concurrent access to a "
1093 "hash-table from multiple threads. Any accesses to "
1094 "hash-tables shared between threads should be protected "
1095 "by locks.\n", (void*)&where[2]);
1096 goto normal;
1098 hash_table = (struct hash_table *)native_pointer(where[2]);
1099 /*FSHOW((stderr,"/hash_table = %x\n", hash_table));*/
1100 if (widetag_of(hash_table->header) != INSTANCE_WIDETAG) {
1101 lose("hash table not instance (%x at %x)\n",
1102 hash_table->header,
1103 hash_table);
1106 /* Scavenge element 1, which should be some internal symbol that
1107 * the hash table code reserves for marking empty slots. */
1108 scavenge(where+3, 1);
1109 if (!is_lisp_pointer(where[3])) {
1110 lose("not empty-hash-table-slot symbol pointer: %x\n", where[3]);
1113 /* Scavenge hash table, which will fix the positions of the other
1114 * needed objects. */
1115 scav_instance((lispobj *)hash_table, hash_table->header);
1117 /* Cross-check the kv_vector. */
1118 if (where != native_pointer(hash_table->table)) {
1119 lose("hash_table table!=this table %x\n", hash_table->table);
1122 if (hash_table->weakness == NIL) {
1123 scav_hash_table_entries(hash_table);
1124 } else {
1125 /* Delay scavenging of this table by pushing it onto
1126 * weak_hash_tables (if it's not there already) for the weak
1127 * object phase. */
1128 if (hash_table->next_weak_hash_table == NIL) {
1129 hash_table->next_weak_hash_table = (lispobj)weak_hash_tables;
1130 weak_hash_tables = hash_table;
1134 return (CEILING(kv_length + 2, 2));
1137 void
1138 scav_weak_hash_tables (void)
1140 struct hash_table *table;
1142 /* Scavenge entries whose triggers are known to survive. */
1143 for (table = weak_hash_tables; table != NULL;
1144 table = (struct hash_table *)table->next_weak_hash_table) {
1145 scav_hash_table_entries(table);
1149 /* Walk through the chain whose first element is *FIRST and remove
1150 * dead weak entries. */
1151 static inline void
1152 scan_weak_hash_table_chain (struct hash_table *hash_table, lispobj *prev,
1153 lispobj *kv_vector, lispobj *index_vector,
1154 lispobj *next_vector, lispobj *hash_vector,
1155 lispobj empty_symbol, int (*alivep_test)(lispobj,lispobj))
1157 unsigned index = *prev;
1158 while (index) {
1159 unsigned next = next_vector[index];
1160 lispobj key = kv_vector[2 * index];
1161 lispobj value = kv_vector[2 * index + 1];
1162 gc_assert(key != empty_symbol);
1163 gc_assert(value != empty_symbol);
1164 if (!alivep_test(key, value)) {
1165 unsigned count = fixnum_value(hash_table->number_entries);
1166 gc_assert(count > 0);
1167 *prev = next;
1168 hash_table->number_entries = make_fixnum(count - 1);
1169 next_vector[index] = fixnum_value(hash_table->next_free_kv);
1170 hash_table->next_free_kv = make_fixnum(index);
1171 kv_vector[2 * index] = empty_symbol;
1172 kv_vector[2 * index + 1] = empty_symbol;
1173 if (hash_vector)
1174 hash_vector[index] = MAGIC_HASH_VECTOR_VALUE;
1175 } else {
1176 prev = &next_vector[index];
1178 index = next;
1182 static void
1183 scan_weak_hash_table (struct hash_table *hash_table)
1185 lispobj *kv_vector;
1186 lispobj *index_vector;
1187 uword_t length = 0; /* prevent warning */
1188 lispobj *next_vector;
1189 uword_t next_vector_length = 0; /* prevent warning */
1190 lispobj *hash_vector;
1191 lispobj empty_symbol;
1192 lispobj weakness = hash_table->weakness;
1193 uword_t i;
1195 kv_vector = get_array_data(hash_table->table,
1196 SIMPLE_VECTOR_WIDETAG, NULL);
1197 index_vector = get_array_data(hash_table->index_vector,
1198 SIMPLE_ARRAY_WORD_WIDETAG, &length);
1199 next_vector = get_array_data(hash_table->next_vector,
1200 SIMPLE_ARRAY_WORD_WIDETAG,
1201 &next_vector_length);
1202 hash_vector = get_array_data(hash_table->hash_vector,
1203 SIMPLE_ARRAY_WORD_WIDETAG, NULL);
1204 empty_symbol = kv_vector[1];
1206 for (i = 0; i < length; i++) {
1207 scan_weak_hash_table_chain(hash_table, &index_vector[i],
1208 kv_vector, index_vector, next_vector,
1209 hash_vector, empty_symbol,
1210 weak_hash_entry_alivep_fun(weakness));
1214 /* Remove dead entries from weak hash tables. */
1215 void
1216 scan_weak_hash_tables (void)
1218 struct hash_table *table, *next;
1220 for (table = weak_hash_tables; table != NULL; table = next) {
1221 next = (struct hash_table *)table->next_weak_hash_table;
1222 table->next_weak_hash_table = NIL;
1223 scan_weak_hash_table(table);
1226 weak_hash_tables = NULL;
1231 * initialization
1234 static sword_t
1235 scav_lose(lispobj *where, lispobj object)
1237 lose("no scavenge function for object %p (widetag 0x%x)\n",
1238 (uword_t)object,
1239 widetag_of(*where));
1241 return 0; /* bogus return value to satisfy static type checking */
1244 static lispobj
1245 trans_lose(lispobj object)
1247 lose("no transport function for object %p (widetag 0x%x)\n",
1248 (void*)object,
1249 widetag_of(*native_pointer(object)));
1250 return NIL; /* bogus return value to satisfy static type checking */
1253 static sword_t
1254 size_lose(lispobj *where)
1256 lose("no size function for object at %p (widetag 0x%x)\n",
1257 (void*)where,
1258 widetag_of(*where));
1259 return 1; /* bogus return value to satisfy static type checking */
1264 * initialization
1267 #include "genesis/gc-tables.h"
1270 static lispobj *search_spaces(void *pointer)
1272 lispobj *start;
1273 if (((start = search_dynamic_space(pointer)) != NULL) ||
1274 #ifdef LISP_FEATURE_IMMOBILE_SPACE
1275 ((start = search_immobile_space(pointer)) != NULL) ||
1276 #endif
1277 ((start = search_static_space(pointer)) != NULL) ||
1278 ((start = search_read_only_space(pointer)) != NULL))
1279 return start;
1280 return NULL;
1283 /* Find the code object for the given pc, or return NULL on
1284 failure. */
1285 lispobj *
1286 component_ptr_from_pc(lispobj *pc)
1288 lispobj *object = search_spaces(pc);
1290 if (object != NULL && widetag_of(*object) == CODE_HEADER_WIDETAG)
1291 return object;
1293 return NULL;
1296 /* Scan an area looking for an object which encloses the given pointer.
1297 * Return the object start on success, or NULL on failure. */
1298 lispobj *
1299 gc_search_space3(void *pointer, lispobj *start, void *limit)
1301 if (pointer < (void*)start || pointer >= limit) return NULL;
1303 size_t count;
1304 #if 0
1305 /* CAUTION: this code is _significantly_ slower than the production version
1306 due to the extra checks for forwarding. Only use it if debugging */
1307 for ( ; (void*)start < limit ; start += count) {
1308 lispobj *forwarded_start;
1309 if (forwarding_pointer_p(start))
1310 forwarded_start = native_pointer(forwarding_pointer_value(start));
1311 else
1312 forwarded_start = start;
1313 lispobj thing = *forwarded_start;
1314 count = is_cons_half(thing) ? 2 : sizetab[widetag_of(thing)](forwarded_start);
1315 /* Check whether the pointer is within this object. */
1316 if (pointer < (void*)(start+count)) return start;
1318 #else
1319 for ( ; (void*)start < limit ; start += count) {
1320 lispobj thing = *start;
1321 count = is_cons_half(thing) ? 2 : sizetab[widetag_of(thing)](start);
1322 /* Check whether the pointer is within this object. */
1323 if (pointer < (void*)(start+count)) return start;
1325 #endif
1326 return NULL;
1329 /* Helper for valid_lisp_pointer_p (below) and
1330 * conservative_root_p (gencgc).
1332 * pointer is the pointer to check validity of,
1333 * and start_addr is the address of the enclosing object.
1335 * This is actually quite simple to check: because the heap state is assumed
1336 * consistent, and 'start_addr' is known good, having come from
1337 * gc_search_space(), only the 'pointer' argument is dubious.
1338 * So make 'start_addr' into a tagged pointer and see if that matches 'pointer'.
1339 * If it does, then 'pointer' is valid.
1342 properly_tagged_p_internal(lispobj pointer, lispobj *start_addr)
1344 // If a headerless object, confirm that 'pointer' is a list pointer.
1345 // Given the precondition that the heap is in a valid state,
1346 // it may be assumed that one check of is_cons_half() suffices;
1347 // we don't need to check the other half.
1348 lispobj header = *start_addr;
1349 if (is_cons_half(header))
1350 return make_lispobj(start_addr, LIST_POINTER_LOWTAG) == pointer;
1352 // Because this heap object was not deemed to be a cons,
1353 // it must be an object header. Don't need a check except when paranoid.
1354 gc_dcheck(other_immediate_lowtag_p(header));
1356 // The space of potential widetags has 64 elements, not 256,
1357 // because of the constant low 2 bits.
1358 int widetag = widetag_of(header);
1359 int lowtag = lowtag_for_widetag[widetag>>2];
1360 if (lowtag && make_lispobj(start_addr, lowtag) == pointer)
1361 return 1; // instant win
1363 if (widetag == CODE_HEADER_WIDETAG) {
1364 // Check for RETURN_PC_HEADER first since it's quicker.
1365 // Then consider the embedded simple-funs.
1366 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
1367 /* The all-architecture test below is good as far as it goes,
1368 * but an LRA object is similar to a FUN-POINTER: It is
1369 * embedded within a CODE-OBJECT pointed to by start_addr, and
1370 * cannot be found by simply walking the heap, therefore we
1371 * need to check for it. -- AB, 2010-Jun-04 */
1372 if (lowtag_of(pointer) == OTHER_POINTER_LOWTAG) {
1373 lispobj *potential_lra = native_pointer(pointer);
1374 if ((widetag_of(potential_lra[0]) == RETURN_PC_WIDETAG) &&
1375 ((potential_lra - HeaderValue(potential_lra[0])) == start_addr)) {
1376 return 1; /* It's as good as we can verify. */
1379 #endif
1380 if (lowtag_of(pointer) == FUN_POINTER_LOWTAG) {
1381 struct simple_fun *pfun =
1382 (struct simple_fun*)(pointer-FUN_POINTER_LOWTAG);
1383 for_each_simple_fun(i, function, (struct code*)start_addr, 0, {
1384 if (pfun == function) return 1;
1388 return 0; // no good
1391 /* META: Note the ambiguous word "validate" in the comment below.
1392 * This means "Decide whether <x> is valid".
1393 * But when you see os_validate() elsewhere, that doesn't mean to ask
1394 * whether something is valid, it says to *make* it valid.
1395 * I think it would be nice if we could avoid using the word in the
1396 * sense in which os_validate() uses it, which would entail renaming
1397 * a bunch of stuff, which is harder than just explaining why
1398 * the comments can be deceptive */
1400 /* Used by the debugger to validate possibly bogus pointers before
1401 * calling MAKE-LISP-OBJ on them.
1403 * FIXME: We would like to make this perfect, because if the debugger
1404 * constructs a reference to a bugs lisp object, and it ends up in a
1405 * location scavenged by the GC all hell breaks loose.
1407 * Whereas conservative_root_p has to be conservative
1408 * and return true for all valid pointers, this could actually be eager
1409 * and lie about a few pointers without bad results... but that should
1410 * be reflected in the name.
1413 valid_lisp_pointer_p(lispobj pointer)
1415 lispobj *start = search_spaces((void*)pointer);
1416 if (start != NULL)
1417 return properly_tagged_descriptor_p((void*)pointer, start);
1418 return 0;
1421 boolean
1422 maybe_gc(os_context_t *context)
1424 lispobj gc_happened;
1425 struct thread *thread = arch_os_get_current_thread();
1426 boolean were_in_lisp = !foreign_function_call_active_p(thread);
1428 if (were_in_lisp) {
1429 fake_foreign_function_call(context);
1432 /* SUB-GC may return without GCing if *GC-INHIBIT* is set, in
1433 * which case we will be running with no gc trigger barrier
1434 * thing for a while. But it shouldn't be long until the end
1435 * of WITHOUT-GCING.
1437 * FIXME: It would be good to protect the end of dynamic space for
1438 * CheneyGC and signal a storage condition from there.
1441 /* Restore the signal mask from the interrupted context before
1442 * calling into Lisp if interrupts are enabled. Why not always?
1444 * Suppose there is a WITHOUT-INTERRUPTS block far, far out. If an
1445 * interrupt hits while in SUB-GC, it is deferred and the
1446 * os_context_sigmask of that interrupt is set to block further
1447 * deferrable interrupts (until the first one is
1448 * handled). Unfortunately, that context refers to this place and
1449 * when we return from here the signals will not be blocked.
1451 * A kludgy alternative is to propagate the sigmask change to the
1452 * outer context.
1454 #if !(defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_SAFEPOINT))
1455 check_gc_signals_unblocked_or_lose(os_context_sigmask_addr(context));
1456 unblock_gc_signals(0, 0);
1457 #endif
1458 FSHOW((stderr, "/maybe_gc: calling SUB_GC\n"));
1459 /* FIXME: Nothing must go wrong during GC else we end up running
1460 * the debugger, error handlers, and user code in general in a
1461 * potentially unsafe place. Running out of the control stack or
1462 * the heap in SUB-GC are ways to lose. Of course, deferrables
1463 * cannot be unblocked because there may be a pending handler, or
1464 * we may even be in a WITHOUT-INTERRUPTS. */
1465 gc_happened = funcall0(StaticSymbolFunction(SUB_GC));
1466 FSHOW((stderr, "/maybe_gc: gc_happened=%s\n",
1467 (gc_happened == NIL)
1468 ? "NIL"
1469 : ((gc_happened == T)
1470 ? "T"
1471 : "0")));
1472 /* gc_happened can take three values: T, NIL, 0.
1474 * T means that the thread managed to trigger a GC, and post-gc
1475 * must be called.
1477 * NIL means that the thread is within without-gcing, and no GC
1478 * has occurred.
1480 * Finally, 0 means that *a* GC has occurred, but it wasn't
1481 * triggered by this thread; success, but post-gc doesn't have
1482 * to be called.
1484 if ((gc_happened == T) &&
1485 /* See if interrupts are enabled or it's possible to enable
1486 * them. POST-GC has a similar check, but we don't want to
1487 * unlock deferrables in that case and get a pending interrupt
1488 * here. */
1489 ((SymbolValue(INTERRUPTS_ENABLED,thread) != NIL) ||
1490 (SymbolValue(ALLOW_WITH_INTERRUPTS,thread) != NIL))) {
1491 #ifndef LISP_FEATURE_WIN32
1492 sigset_t *context_sigmask = os_context_sigmask_addr(context);
1493 if (!deferrables_blocked_p(context_sigmask)) {
1494 thread_sigmask(SIG_SETMASK, context_sigmask, 0);
1495 #ifndef LISP_FEATURE_SB_SAFEPOINT
1496 check_gc_signals_unblocked_or_lose(0);
1497 #endif
1498 #endif
1499 FSHOW((stderr, "/maybe_gc: calling POST_GC\n"));
1500 funcall0(StaticSymbolFunction(POST_GC));
1501 #ifndef LISP_FEATURE_WIN32
1502 } else {
1503 FSHOW((stderr, "/maybe_gc: punting on POST_GC due to blockage\n"));
1505 #endif
1508 if (were_in_lisp) {
1509 undo_fake_foreign_function_call(context);
1510 } else {
1511 /* Otherwise done by undo_fake_foreign_function_call. And
1512 something later wants them to be blocked. What a nice
1513 interface.*/
1514 block_blockable_signals(0);
1517 FSHOW((stderr, "/maybe_gc: returning\n"));
1518 return (gc_happened != NIL);
1521 #define BYTES_ZERO_BEFORE_END (1<<12)
1523 /* There used to be a similar function called SCRUB-CONTROL-STACK in
1524 * Lisp and another called zero_stack() in cheneygc.c, but since it's
1525 * shorter to express in, and more often called from C, I keep only
1526 * the C one after fixing it. -- MG 2009-03-25 */
1528 /* Zero the unused portion of the control stack so that old objects
1529 * are not kept alive because of uninitialized stack variables.
1531 * "To summarize the problem, since not all allocated stack frame
1532 * slots are guaranteed to be written by the time you call an another
1533 * function or GC, there may be garbage pointers retained in your dead
1534 * stack locations. The stack scrubbing only affects the part of the
1535 * stack from the SP to the end of the allocated stack." - ram, on
1536 * cmucl-imp, Tue, 25 Sep 2001
1538 * So, as an (admittedly lame) workaround, from time to time we call
1539 * scrub-control-stack to zero out all the unused portion. This is
1540 * supposed to happen when the stack is mostly empty, so that we have
1541 * a chance of clearing more of it: callers are currently (2002.07.18)
1542 * REPL, SUB-GC and sig_stop_for_gc_handler. */
1544 /* Take care not to tread on the guard page and the hard guard page as
1545 * it would be unkind to sig_stop_for_gc_handler. Touching the return
1546 * guard page is not dangerous. For this to work the guard page must
1547 * be zeroed when protected. */
1549 /* FIXME: I think there is no guarantee that once
1550 * BYTES_ZERO_BEFORE_END bytes are zero the rest are also zero. This
1551 * may be what the "lame" adjective in the above comment is for. In
1552 * this case, exact gc may lose badly. */
1553 void
1554 scrub_control_stack()
1556 scrub_thread_control_stack(arch_os_get_current_thread());
1559 void
1560 scrub_thread_control_stack(struct thread *th)
1562 os_vm_address_t guard_page_address = CONTROL_STACK_GUARD_PAGE(th);
1563 os_vm_address_t hard_guard_page_address = CONTROL_STACK_HARD_GUARD_PAGE(th);
1564 #ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
1565 /* On these targets scrubbing from C is a bad idea, so we punt to
1566 * a routine in $ARCH-assem.S. */
1567 extern void arch_scrub_control_stack(struct thread *, os_vm_address_t, os_vm_address_t);
1568 arch_scrub_control_stack(th, guard_page_address, hard_guard_page_address);
1569 #else
1570 lispobj *sp = access_control_stack_pointer(th);
1571 scrub:
1572 if ((((os_vm_address_t)sp < (hard_guard_page_address + os_vm_page_size)) &&
1573 ((os_vm_address_t)sp >= hard_guard_page_address)) ||
1574 (((os_vm_address_t)sp < (guard_page_address + os_vm_page_size)) &&
1575 ((os_vm_address_t)sp >= guard_page_address) &&
1576 (th->control_stack_guard_page_protected != NIL)))
1577 return;
1578 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
1579 do {
1580 *sp = 0;
1581 } while (((uword_t)sp--) & (BYTES_ZERO_BEFORE_END - 1));
1582 if ((os_vm_address_t)sp < (hard_guard_page_address + os_vm_page_size))
1583 return;
1584 do {
1585 if (*sp)
1586 goto scrub;
1587 } while (((uword_t)sp--) & (BYTES_ZERO_BEFORE_END - 1));
1588 #else
1589 do {
1590 *sp = 0;
1591 } while (((uword_t)++sp) & (BYTES_ZERO_BEFORE_END - 1));
1592 if ((os_vm_address_t)sp >= hard_guard_page_address)
1593 return;
1594 do {
1595 if (*sp)
1596 goto scrub;
1597 } while (((uword_t)++sp) & (BYTES_ZERO_BEFORE_END - 1));
1598 #endif
1599 #endif /* LISP_FEATURE_C_STACK_IS_CONTROL_STACK */
1602 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
1604 void
1605 scavenge_control_stack(struct thread *th)
1607 lispobj *object_ptr;
1609 /* In order to properly support dynamic-extent allocation of
1610 * non-CONS objects, the control stack requires special handling.
1611 * Rather than calling scavenge() directly, grovel over it fixing
1612 * broken hearts, scavenging pointers to oldspace, and pitching a
1613 * fit when encountering unboxed data. This prevents stray object
1614 * headers from causing the scavenger to blow past the end of the
1615 * stack (an error case checked in scavenge()). We don't worry
1616 * about treating unboxed words as boxed or vice versa, because
1617 * the compiler isn't allowed to store unboxed objects on the
1618 * control stack. -- AB, 2011-Dec-02 */
1620 for (object_ptr = th->control_stack_start;
1621 object_ptr < access_control_stack_pointer(th);
1622 object_ptr++) {
1624 lispobj object = *object_ptr;
1625 #ifdef LISP_FEATURE_GENCGC
1626 if (forwarding_pointer_p(object_ptr))
1627 lose("unexpected forwarding pointer in scavenge_control_stack: %p, start=%p, end=%p\n",
1628 object_ptr, th->control_stack_start, access_control_stack_pointer(th));
1629 #endif
1630 if (is_lisp_pointer(object) && from_space_p(object)) {
1631 /* It currently points to old space. Check for a
1632 * forwarding pointer. */
1633 lispobj *ptr = native_pointer(object);
1634 if (forwarding_pointer_p(ptr)) {
1635 /* Yes, there's a forwarding pointer. */
1636 *object_ptr = LOW_WORD(forwarding_pointer_value(ptr));
1637 } else {
1638 /* Scavenge that pointer. */
1639 long n_words_scavenged =
1640 (scavtab[widetag_of(object)])(object_ptr, object);
1641 gc_assert(n_words_scavenged == 1);
1643 } else if (scavtab[widetag_of(object)] == scav_lose) {
1644 lose("unboxed object in scavenge_control_stack: %p->%x, start=%p, end=%p\n",
1645 object_ptr, object, th->control_stack_start, access_control_stack_pointer(th));
1650 /* Scavenging Interrupt Contexts */
1652 static int boxed_registers[] = BOXED_REGISTERS;
1654 /* The GC has a notion of an "interior pointer" register, an unboxed
1655 * register that typically contains a pointer to inside an object
1656 * referenced by another pointer. The most obvious of these is the
1657 * program counter, although many compiler backends define a "Lisp
1658 * Interior Pointer" register known to the runtime as reg_LIP, and
1659 * various CPU architectures have other registers that also partake of
1660 * the interior-pointer nature. As the code for pairing an interior
1661 * pointer value up with its "base" register, and fixing it up after
1662 * scavenging is complete is horribly repetitive, a few macros paper
1663 * over the monotony. --AB, 2010-Jul-14 */
1665 /* These macros are only ever used over a lexical environment which
1666 * defines a pointer to an os_context_t called context, thus we don't
1667 * bother to pass that context in as a parameter. */
1669 /* Define how to access a given interior pointer. */
1670 #define ACCESS_INTERIOR_POINTER_pc \
1671 *os_context_pc_addr(context)
1672 #define ACCESS_INTERIOR_POINTER_lip \
1673 *os_context_register_addr(context, reg_LIP)
1674 #define ACCESS_INTERIOR_POINTER_lr \
1675 *os_context_lr_addr(context)
1676 #define ACCESS_INTERIOR_POINTER_npc \
1677 *os_context_npc_addr(context)
1678 #define ACCESS_INTERIOR_POINTER_ctr \
1679 *os_context_ctr_addr(context)
1681 #define INTERIOR_POINTER_VARS(name) \
1682 uword_t name##_offset; \
1683 int name##_register_pair
1685 #define PAIR_INTERIOR_POINTER(name) \
1686 pair_interior_pointer(context, \
1687 ACCESS_INTERIOR_POINTER_##name, \
1688 &name##_offset, \
1689 &name##_register_pair)
1691 /* One complexity here is that if a paired register is not found for
1692 * an interior pointer, then that pointer does not get updated.
1693 * Originally, there was some commentary about using an index of -1
1694 * when calling os_context_register_addr() on SPARC referring to the
1695 * program counter, but the real reason is to allow an interior
1696 * pointer register to point to the runtime, read-only space, or
1697 * static space without problems. */
1698 #define FIXUP_INTERIOR_POINTER(name) \
1699 do { \
1700 if (name##_register_pair >= 0) { \
1701 ACCESS_INTERIOR_POINTER_##name = \
1702 (*os_context_register_addr(context, \
1703 name##_register_pair) \
1704 & ~LOWTAG_MASK) \
1705 + name##_offset; \
1707 } while (0)
1710 static void
1711 pair_interior_pointer(os_context_t *context, uword_t pointer,
1712 uword_t *saved_offset, int *register_pair)
1714 unsigned int i;
1717 * I (RLT) think this is trying to find the boxed register that is
1718 * closest to the LIP address, without going past it. Usually, it's
1719 * reg_CODE or reg_LRA. But sometimes, nothing can be found.
1721 /* 0x7FFFFFFF on 32-bit platforms;
1722 0x7FFFFFFFFFFFFFFF on 64-bit platforms */
1723 *saved_offset = (((uword_t)1) << (N_WORD_BITS - 1)) - 1;
1724 *register_pair = -1;
1725 for (i = 0; i < (sizeof(boxed_registers) / sizeof(int)); i++) {
1726 uword_t reg;
1727 uword_t offset;
1728 int index;
1730 index = boxed_registers[i];
1731 reg = *os_context_register_addr(context, index);
1733 /* An interior pointer is never relative to a non-pointer
1734 * register (an oversight in the original implementation).
1735 * The simplest argument for why this is true is to consider
1736 * the fixnum that happens by coincide to be the word-index in
1737 * memory of the header for some object plus two. This is
1738 * happenstance would cause the register containing the fixnum
1739 * to be selected as the register_pair if the interior pointer
1740 * is to anywhere after the first two words of the object.
1741 * The fixnum won't be changed during GC, but the object might
1742 * move, thus destroying the interior pointer. --AB,
1743 * 2010-Jul-14 */
1745 if (is_lisp_pointer(reg) &&
1746 ((reg & ~LOWTAG_MASK) <= pointer)) {
1747 offset = pointer - (reg & ~LOWTAG_MASK);
1748 if (offset < *saved_offset) {
1749 *saved_offset = offset;
1750 *register_pair = index;
1756 static void
1757 scavenge_interrupt_context(os_context_t * context)
1759 unsigned int i;
1761 /* FIXME: The various #ifdef noise here is precisely that: noise.
1762 * Is it possible to fold it into the macrology so that we have
1763 * one set of #ifdefs and then INTERIOR_POINTER_VARS /et alia/
1764 * compile out for the registers that don't exist on a given
1765 * platform? */
1767 INTERIOR_POINTER_VARS(pc);
1768 #ifdef reg_LIP
1769 INTERIOR_POINTER_VARS(lip);
1770 #endif
1771 #ifdef ARCH_HAS_LINK_REGISTER
1772 INTERIOR_POINTER_VARS(lr);
1773 #endif
1774 #ifdef ARCH_HAS_NPC_REGISTER
1775 INTERIOR_POINTER_VARS(npc);
1776 #endif
1777 #ifdef LISP_FEATURE_PPC
1778 INTERIOR_POINTER_VARS(ctr);
1779 #endif
1781 PAIR_INTERIOR_POINTER(pc);
1782 #ifdef reg_LIP
1783 PAIR_INTERIOR_POINTER(lip);
1784 #endif
1785 #ifdef ARCH_HAS_LINK_REGISTER
1786 PAIR_INTERIOR_POINTER(lr);
1787 #endif
1788 #ifdef ARCH_HAS_NPC_REGISTER
1789 PAIR_INTERIOR_POINTER(npc);
1790 #endif
1791 #ifdef LISP_FEATURE_PPC
1792 PAIR_INTERIOR_POINTER(ctr);
1793 #endif
1795 /* Scavenge all boxed registers in the context. */
1796 for (i = 0; i < (sizeof(boxed_registers) / sizeof(int)); i++) {
1797 os_context_register_t *boxed_reg;
1798 lispobj datum;
1800 /* We can't "just" cast os_context_register_addr() to a
1801 * pointer to lispobj and pass it to scavenge, because some
1802 * systems can have a wider register width than we use for
1803 * lisp objects, and on big-endian systems casting a pointer
1804 * to a narrower target type doesn't work properly.
1805 * Therefore, we copy the value out to a temporary lispobj
1806 * variable, scavenge there, and copy the value back in.
1808 * FIXME: lispobj is unsigned, os_context_register_t may be
1809 * signed or unsigned, are we truncating or sign-extending
1810 * values here that shouldn't be modified? Possibly affects
1811 * any architecture that has 32-bit and 64-bit variants where
1812 * we run in 32-bit mode on 64-bit hardware when the OS is set
1813 * up for 64-bit from the start. Or an environment with
1814 * 32-bit addresses and 64-bit registers. */
1816 boxed_reg = os_context_register_addr(context, boxed_registers[i]);
1817 datum = *boxed_reg;
1818 scavenge(&datum, 1);
1819 *boxed_reg = datum;
1822 /* Now that the scavenging is done, repair the various interior
1823 * pointers. */
1824 FIXUP_INTERIOR_POINTER(pc);
1825 #ifdef reg_LIP
1826 FIXUP_INTERIOR_POINTER(lip);
1827 #endif
1828 #ifdef ARCH_HAS_LINK_REGISTER
1829 FIXUP_INTERIOR_POINTER(lr);
1830 #endif
1831 #ifdef ARCH_HAS_NPC_REGISTER
1832 FIXUP_INTERIOR_POINTER(npc);
1833 #endif
1834 #ifdef LISP_FEATURE_PPC
1835 FIXUP_INTERIOR_POINTER(ctr);
1836 #endif
1839 void
1840 scavenge_interrupt_contexts(struct thread *th)
1842 int i, index;
1843 os_context_t *context;
1845 index = fixnum_value(SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,th));
1847 #if defined(DEBUG_PRINT_CONTEXT_INDEX)
1848 printf("Number of active contexts: %d\n", index);
1849 #endif
1851 for (i = 0; i < index; i++) {
1852 context = th->interrupt_contexts[i];
1853 scavenge_interrupt_context(context);
1856 #endif /* x86oid targets */
1858 void varint_unpacker_init(struct varint_unpacker* unpacker, lispobj integer)
1860 if (fixnump(integer)) {
1861 unpacker->word = fixnum_value(integer);
1862 unpacker->limit = N_WORD_BYTES;
1863 unpacker->data = (char*)&unpacker->word;
1864 } else {
1865 struct bignum* bignum = (struct bignum*)(integer - OTHER_POINTER_LOWTAG);
1866 unpacker->word = 0;
1867 unpacker->limit = HeaderValue(bignum->header) * N_WORD_BYTES;
1868 unpacker->data = (char*)bignum->digits;
1870 unpacker->index = 0;
1873 // Fetch the next varint from 'unpacker' into 'result'.
1874 // Because there is no length prefix on the number of varints encoded,
1875 // spurious trailing zeros might be observed. The data consumer can
1876 // circumvent that by storing a count as the first value in the series.
1877 // Return 1 for success, 0 for EOF.
1878 int varint_unpack(struct varint_unpacker* unpacker, int* result)
1880 if (unpacker->index >= unpacker->limit) return 0;
1881 int accumulator = 0;
1882 int shift = 0;
1883 while (1) {
1884 #ifdef LISP_FEATURE_LITTLE_ENDIAN
1885 int byte = unpacker->data[unpacker->index];
1886 #else
1887 // bignums are little-endian in word order,
1888 // but machine-native within each word.
1889 // We could pack bytes MSB-to-LSB in the bigdigits,
1890 // but that seems less intuitive on the Lisp side.
1891 int word_index = unpacker->index / N_WORD_BYTES;
1892 int byte_index = unpacker->index % N_WORD_BYTES;
1893 int byte = (((unsigned int*)unpacker->data)[word_index]
1894 >> (byte_index * 8)) & 0xFF;
1895 #endif
1896 ++unpacker->index;
1897 accumulator |= (byte & 0x7F) << shift;
1898 if (!(byte & 0x80)) break;
1899 gc_assert(unpacker->index < unpacker->limit);
1900 shift += 7;
1902 *result = accumulator;
1903 return 1;