Debian Codegraph @

src/runtime/mbitmap.go

raw
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Garbage collector: type and heap bitmaps.
6 //
7 // Stack, data, and bss bitmaps
8 //
9 // Stack frames and global variables in the data and bss sections are
10 // described by bitmaps with 1 bit per pointer-sized word. A "1" bit
11 // means the word is a live pointer to be visited by the GC (referred to
12 // as "pointer"). A "0" bit means the word should be ignored by GC
13 // (referred to as "scalar", though it could be a dead pointer value).
14 //
15 // Heap bitmaps
16 //
17 // The heap bitmap comprises 1 bit for each pointer-sized word in the heap,
18 // recording whether a pointer is stored in that word or not. This bitmap
19 // is stored at the end of a span for small objects and is unrolled at
20 // runtime from type metadata for all larger objects. Objects without
21 // pointers have neither a bitmap nor associated type metadata.
22 //
23 // Bits in all cases correspond to words in little-endian order.
24 //
25 // For small objects, if s is the mspan for the span starting at "start",
26 // then s.heapBits() returns a slice containing the bitmap for the whole span.
27 // That is, s.heapBits()[0] holds the goarch.PtrSize*8 bits for the first
28 // goarch.PtrSize*8 words from "start" through "start+63*ptrSize" in the span.
29 // On a related note, small objects are always small enough that their bitmap
30 // fits in goarch.PtrSize*8 bits, so writing out bitmap data takes two bitmap
31 // writes at most (because object boundaries don't generally lie on
32 // s.heapBits()[i] boundaries).
33 //
34 // For larger objects, if t is the type for the object starting at "start",
35 // within some span whose mspan is s, then the bitmap at t.GCData is "tiled"
36 // from "start" through "start+s.elemsize".
37 // Specifically, the first bit of t.GCData corresponds to the word at "start",
38 // the second to the word after "start", and so on up to t.PtrBytes. At t.PtrBytes,
39 // we skip to "start+t.Size_" and begin again from there. This process is
40 // repeated until we hit "start+s.elemsize".
41 // This tiling algorithm supports array data, since the type always refers to
42 // the element type of the array. Single objects are considered the same as
43 // single-element arrays.
44 // The tiling algorithm may scan data past the end of the compiler-recognized
45 // object, but any unused data within the allocation slot (i.e. within s.elemsize)
46 // is zeroed, so the GC just observes nil pointers.
47 // Note that this "tiled" bitmap isn't stored anywhere; it is generated on-the-fly.
48 //
49 // For objects without their own span, the type metadata is stored in the first
50 // word before the object at the beginning of the allocation slot. For objects
51 // with their own span, the type metadata is stored in the mspan.
52 //
53 // The bitmap for small unallocated objects in scannable spans is not maintained
54 // (can be junk).
55
56 package runtime
57
58 import (
59 "internal/abi"
60 "internal/goarch"
61 "internal/goexperiment"
62 "internal/runtime/atomic"
63 "internal/runtime/gc"
64 "internal/runtime/sys"
65 "unsafe"
66 )
67
68 // heapBitsInSpan returns true if the size of an object implies its ptr/scalar
69 // data is stored at the end of the span, and is accessible via span.heapBits.
70 //
71 // Note: this works for both rounded-up sizes (span.elemsize) and unrounded
72 // type sizes because gc.MinSizeForMallocHeader is guaranteed to be at a size
73 // class boundary.
74 //
75 //go:nosplit
76 func heapBitsInSpan(userSize uintptr) bool {
77 // N.B. gc.MinSizeForMallocHeader is an exclusive minimum so that this function is
78 // invariant under size-class rounding on its input.
79 return userSize <= gc.MinSizeForMallocHeader
80 }
81
82 // typePointers is an iterator over the pointers in a heap object.
83 //
84 // Iteration through this type implements the tiling algorithm described at the
85 // top of this file.
86 type typePointers struct {
87 // elem is the address of the current array element of type typ being iterated over.
88 // Objects that are not arrays are treated as single-element arrays, in which case
89 // this value does not change.
90 elem uintptr
91
92 // addr is the address the iterator is currently working from and describes
93 // the address of the first word referenced by mask.
94 addr uintptr
95
96 // mask is a bitmask where each bit corresponds to pointer-words after addr.
97 // Bit 0 is the pointer-word at addr, Bit 1 is the next word, and so on.
98 // If a bit is 1, then there is a pointer at that word.
99 // nextFast and next mask out bits in this mask as their pointers are processed.
100 mask uintptr
101
102 // typ is a pointer to the type information for the heap object's type.
103 // This may be nil if the object is in a span where heapBitsInSpan(span.elemsize) is true.
104 typ *_type
105 }
106
107 // typePointersOf returns an iterator over all heap pointers in the range [addr, addr+size).
108 //
109 // addr and addr+size must be in the range [span.base(), span.limit).
110 //
111 // Note: addr+size must be passed as the limit argument to the iterator's next method on
112 // each iteration. This slightly awkward API is to allow typePointers to be destructured
113 // by the compiler.
114 //
115 // nosplit because it is used during write barriers and must not be preempted.
116 //
117 //go:nosplit
118 func (span *mspan) typePointersOf(addr, size uintptr) typePointers {
119 base := span.objBase(addr)
120 tp := span.typePointersOfUnchecked(base)
121 if base == addr && size == span.elemsize {
122 return tp
123 }
124 return tp.fastForward(addr-tp.addr, addr+size)
125 }
126
127 // typePointersOfUnchecked is like typePointersOf, but assumes addr is the base
128 // of an allocation slot in a span (the start of the object if no header, the
129 // header otherwise). It returns an iterator that generates all pointers
130 // in the range [addr, addr+span.elemsize).
131 //
132 // nosplit because it is used during write barriers and must not be preempted.
133 //
134 //go:nosplit
135 func (span *mspan) typePointersOfUnchecked(addr uintptr) typePointers {
136 const doubleCheck = false
137 if doubleCheck && span.objBase(addr) != addr {
138 print("runtime: addr=", addr, " base=", span.objBase(addr), "\n")
139 throw("typePointersOfUnchecked consisting of non-base-address for object")
140 }
141
142 spc := span.spanclass
143 if spc.noscan() {
144 return typePointers{}
145 }
146 if heapBitsInSpan(span.elemsize) {
147 // Handle header-less objects.
148 return typePointers{elem: addr, addr: addr, mask: span.heapBitsSmallForAddr(addr)}
149 }
150
151 // All of these objects have a header.
152 var typ *_type
153 if spc.sizeclass() != 0 {
154 // Pull the allocation header from the first word of the object.
155 typ = *(**_type)(unsafe.Pointer(addr))
156 addr += gc.MallocHeaderSize
157 } else {
158 // Synchronize with allocator, in case this came from the conservative scanner.
159 // See heapSetTypeLarge for more details.
160 typ = (*_type)(atomic.Loadp(unsafe.Pointer(&span.largeType)))
161 if typ == nil {
162 // Allow a nil type here for delayed zeroing. See mallocgc.
163 return typePointers{}
164 }
165 }
166 gcmask := getGCMask(typ)
167 return typePointers{elem: addr, addr: addr, mask: readUintptr(gcmask), typ: typ}
168 }
169
170 // typePointersOfType is like typePointersOf, but assumes addr points to one or more
171 // contiguous instances of the provided type. The provided type must not be nil.
172 //
173 // It returns an iterator that tiles typ's gcmask starting from addr. It's the caller's
174 // responsibility to limit iteration.
175 //
176 // nosplit because its callers are nosplit and require all their callees to be nosplit.
177 //
178 //go:nosplit
179 func (span *mspan) typePointersOfType(typ *abi.Type, addr uintptr) typePointers {
180 const doubleCheck = false
181 if doubleCheck && typ == nil {
182 throw("bad type passed to typePointersOfType")
183 }
184 if span.spanclass.noscan() {
185 return typePointers{}
186 }
187 // Since we have the type, pretend we have a header.
188 gcmask := getGCMask(typ)
189 return typePointers{elem: addr, addr: addr, mask: readUintptr(gcmask), typ: typ}
190 }
191
192 // nextFast is the fast path of next. nextFast is written to be inlineable and,
193 // as the name implies, fast.
194 //
195 // Callers that are performance-critical should iterate using the following
196 // pattern:
197 //
198 // for {
199 // var addr uintptr
200 // if tp, addr = tp.nextFast(); addr == 0 {
201 // if tp, addr = tp.next(limit); addr == 0 {
202 // break
203 // }
204 // }
205 // // Use addr.
206 // ...
207 // }
208 //
209 // nosplit because it is used during write barriers and must not be preempted.
210 //
211 //go:nosplit
212 func (tp typePointers) nextFast() (typePointers, uintptr) {
213 // TESTQ/JEQ
214 if tp.mask == 0 {
215 return tp, 0
216 }
217 // BSFQ
218 var i int
219 if goarch.PtrSize == 8 {
220 i = sys.TrailingZeros64(uint64(tp.mask))
221 } else {
222 i = sys.TrailingZeros32(uint32(tp.mask))
223 }
224 if GOARCH == "amd64" {
225 // BTCQ
226 tp.mask ^= uintptr(1) << (i & (ptrBits - 1))
227 } else {
228 // SUB, AND
229 tp.mask &= tp.mask - 1
230 }
231 // LEAQ (XX)(XX*8)
232 return tp, tp.addr + uintptr(i)*goarch.PtrSize
233 }
234
235 // next advances the pointers iterator, returning the updated iterator and
236 // the address of the next pointer.
237 //
238 // limit must be the same each time it is passed to next.
239 //
240 // nosplit because it is used during write barriers and must not be preempted.
241 //
242 //go:nosplit
243 func (tp typePointers) next(limit uintptr) (typePointers, uintptr) {
244 for {
245 if tp.mask != 0 {
246 return tp.nextFast()
247 }
248
249 // Stop if we don't actually have type information.
250 if tp.typ == nil {
251 return typePointers{}, 0
252 }
253
254 // Advance to the next element if necessary.
255 if tp.addr+goarch.PtrSize*ptrBits >= tp.elem+tp.typ.PtrBytes {
256 tp.elem += tp.typ.Size_
257 tp.addr = tp.elem
258 } else {
259 tp.addr += ptrBits * goarch.PtrSize
260 }
261
262 // Check if we've exceeded the limit with the last update.
263 if tp.addr >= limit {
264 return typePointers{}, 0
265 }
266
267 // Grab more bits and try again.
268 tp.mask = readUintptr(addb(getGCMask(tp.typ), (tp.addr-tp.elem)/goarch.PtrSize/8))
269 if tp.addr+goarch.PtrSize*ptrBits > limit {
270 bits := (tp.addr + goarch.PtrSize*ptrBits - limit) / goarch.PtrSize
271 tp.mask &^= ((1 << (bits)) - 1) << (ptrBits - bits)
272 }
273 }
274 }
275
276 // fastForward moves the iterator forward by n bytes. n must be a multiple
277 // of goarch.PtrSize. limit must be the same limit passed to next for this
278 // iterator.
279 //
280 // nosplit because it is used during write barriers and must not be preempted.
281 //
282 //go:nosplit
283 func (tp typePointers) fastForward(n, limit uintptr) typePointers {
284 // Basic bounds check.
285 target := tp.addr + n
286 if target >= limit {
287 return typePointers{}
288 }
289 if tp.typ == nil {
290 // Handle small objects.
291 // Clear any bits before the target address.
292 tp.mask &^= (1 << ((target - tp.addr) / goarch.PtrSize)) - 1
293 // Clear any bits past the limit.
294 if tp.addr+goarch.PtrSize*ptrBits > limit {
295 bits := (tp.addr + goarch.PtrSize*ptrBits - limit) / goarch.PtrSize
296 tp.mask &^= ((1 << (bits)) - 1) << (ptrBits - bits)
297 }
298 return tp
299 }
300
301 // Move up elem and addr.
302 // Offsets within an element are always at a ptrBits*goarch.PtrSize boundary.
303 if n >= tp.typ.Size_ {
304 // elem needs to be moved to the element containing
305 // tp.addr + n.
306 oldelem := tp.elem
307 tp.elem += (tp.addr - tp.elem + n) / tp.typ.Size_ * tp.typ.Size_
308 tp.addr = tp.elem + alignDown(n-(tp.elem-oldelem), ptrBits*goarch.PtrSize)
309 } else {
310 tp.addr += alignDown(n, ptrBits*goarch.PtrSize)
311 }
312
313 if tp.addr-tp.elem >= tp.typ.PtrBytes {
314 // We're starting in the non-pointer area of an array.
315 // Move up to the next element.
316 tp.elem += tp.typ.Size_
317 tp.addr = tp.elem
318 tp.mask = readUintptr(getGCMask(tp.typ))
319
320 // We may have exceeded the limit after this. Bail just like next does.
321 if tp.addr >= limit {
322 return typePointers{}
323 }
324 } else {
325 // Grab the mask, but then clear any bits before the target address and any
326 // bits over the limit.
327 tp.mask = readUintptr(addb(getGCMask(tp.typ), (tp.addr-tp.elem)/goarch.PtrSize/8))
328 tp.mask &^= (1 << ((target - tp.addr) / goarch.PtrSize)) - 1
329 }
330 if tp.addr+goarch.PtrSize*ptrBits > limit {
331 bits := (tp.addr + goarch.PtrSize*ptrBits - limit) / goarch.PtrSize
332 tp.mask &^= ((1 << (bits)) - 1) << (ptrBits - bits)
333 }
334 return tp
335 }
336
337 // objBase returns the base pointer for the object containing addr in span.
338 //
339 // Assumes that addr points into a valid part of span (span.base() <= addr < span.limit).
340 //
341 //go:nosplit
342 func (span *mspan) objBase(addr uintptr) uintptr {
343 return span.base() + span.objIndex(addr)*span.elemsize
344 }
345
346 // bulkBarrierPreWrite executes a write barrier
347 // for every pointer slot in the memory range [src, src+size),
348 // using pointer/scalar information from [dst, dst+size).
349 // This executes the write barriers necessary before a memmove.
350 // src, dst, and size must be pointer-aligned.
351 // The range [dst, dst+size) must lie within a single object.
352 // It does not perform the actual writes.
353 //
354 // As a special case, src == 0 indicates that this is being used for a
355 // memclr. bulkBarrierPreWrite will pass 0 for the src of each write
356 // barrier.
357 //
358 // Callers should call bulkBarrierPreWrite immediately before
359 // calling memmove(dst, src, size). This function is marked nosplit
360 // to avoid being preempted; the GC must not stop the goroutine
361 // between the memmove and the execution of the barriers.
362 // The caller is also responsible for cgo pointer checks if this
363 // may be writing Go pointers into non-Go memory.
364 //
365 // Pointer data is not maintained for allocations containing
366 // no pointers at all; any caller of bulkBarrierPreWrite must first
367 // make sure the underlying allocation contains pointers, usually
368 // by checking typ.PtrBytes.
369 //
370 // The typ argument is the type of the space at src and dst (and the
371 // element type if src and dst refer to arrays) and it is optional.
372 // If typ is nil, the barrier will still behave as expected and typ
373 // is used purely as an optimization. However, it must be used with
374 // care.
375 //
376 // If typ is not nil, then src and dst must point to one or more values
377 // of type typ. The caller must ensure that the ranges [src, src+size)
378 // and [dst, dst+size) refer to one or more whole values of type src and
379 // dst (leaving off the pointerless tail of the space is OK). If this
380 // precondition is not followed, this function will fail to scan the
381 // right pointers.
382 //
383 // When in doubt, pass nil for typ. That is safe and will always work.
384 //
385 // Callers must perform cgo checks if goexperiment.CgoCheck2.
386 //
387 //go:nosplit
388 func bulkBarrierPreWrite(dst, src, size uintptr, typ *abi.Type) {
389 if (dst|src|size)&(goarch.PtrSize-1) != 0 {
390 throw("bulkBarrierPreWrite: unaligned arguments")
391 }
392 if !writeBarrier.enabled {
393 return
394 }
395 s := spanOf(dst)
396 if s == nil {
397 // If dst is a global, use the data or BSS bitmaps to
398 // execute write barriers.
399 for _, datap := range activeModules() {
400 if datap.data <= dst && dst < datap.edata {
401 bulkBarrierBitmap(dst, src, size, dst-datap.data, datap.gcdatamask.bytedata)
402 return
403 }
404 }
405 for _, datap := range activeModules() {
406 if datap.bss <= dst && dst < datap.ebss {
407 bulkBarrierBitmap(dst, src, size, dst-datap.bss, datap.gcbssmask.bytedata)
408 return
409 }
410 }
411 return
412 } else if s.state.get() != mSpanInUse || dst < s.base() || s.limit <= dst {
413 // dst was heap memory at some point, but isn't now.
414 // It can't be a global. It must be either our stack,
415 // or in the case of direct channel sends, it could be
416 // another stack. Either way, no need for barriers.
417 // This will also catch if dst is in a freed span,
418 // though that should never have.
419 return
420 }
421 buf := &getg().m.p.ptr().wbBuf
422
423 // Double-check that the bitmaps generated in the two possible paths match.
424 const doubleCheck = false
425 if doubleCheck {
426 doubleCheckTypePointersOfType(s, typ, dst, size)
427 }
428
429 var tp typePointers
430 if typ != nil {
431 tp = s.typePointersOfType(typ, dst)
432 } else {
433 tp = s.typePointersOf(dst, size)
434 }
435 if src == 0 {
436 for {
437 var addr uintptr
438 if tp, addr = tp.next(dst + size); addr == 0 {
439 break
440 }
441 dstx := (*uintptr)(unsafe.Pointer(addr))
442 p := buf.get1()
443 p[0] = *dstx
444 }
445 } else {
446 for {
447 var addr uintptr
448 if tp, addr = tp.next(dst + size); addr == 0 {
449 break
450 }
451 dstx := (*uintptr)(unsafe.Pointer(addr))
452 srcx := (*uintptr)(unsafe.Pointer(src + (addr - dst)))
453 p := buf.get2()
454 p[0] = *dstx
455 p[1] = *srcx
456 }
457 }
458 }
459
460 // bulkBarrierPreWriteSrcOnly is like bulkBarrierPreWrite but
461 // does not execute write barriers for [dst, dst+size).
462 //
463 // In addition to the requirements of bulkBarrierPreWrite
464 // callers need to ensure [dst, dst+size) is zeroed.
465 //
466 // This is used for special cases where e.g. dst was just
467 // created and zeroed with malloc.
468 //
469 // The type of the space can be provided purely as an optimization.
470 // See bulkBarrierPreWrite's comment for more details -- use this
471 // optimization with great care.
472 //
473 //go:nosplit
474 func bulkBarrierPreWriteSrcOnly(dst, src, size uintptr, typ *abi.Type) {
475 if (dst|src|size)&(goarch.PtrSize-1) != 0 {
476 throw("bulkBarrierPreWrite: unaligned arguments")
477 }
478 if !writeBarrier.enabled {
479 return
480 }
481 buf := &getg().m.p.ptr().wbBuf
482 s := spanOf(dst)
483
484 // Double-check that the bitmaps generated in the two possible paths match.
485 const doubleCheck = false
486 if doubleCheck {
487 doubleCheckTypePointersOfType(s, typ, dst, size)
488 }
489
490 var tp typePointers
491 if typ != nil {
492 tp = s.typePointersOfType(typ, dst)
493 } else {
494 tp = s.typePointersOf(dst, size)
495 }
496 for {
497 var addr uintptr
498 if tp, addr = tp.next(dst + size); addr == 0 {
499 break
500 }
501 srcx := (*uintptr)(unsafe.Pointer(addr - dst + src))
502 p := buf.get1()
503 p[0] = *srcx
504 }
505 }
506
507 // initHeapBits initializes the heap bitmap for a span.
508 func (s *mspan) initHeapBits() {
509 if goarch.PtrSize == 8 && !s.spanclass.noscan() && s.spanclass.sizeclass() == 1 {
510 b := s.heapBits()
511 for i := range b {
512 b[i] = ^uintptr(0)
513 }
514 } else if (!s.spanclass.noscan() && heapBitsInSpan(s.elemsize)) || s.isUserArenaChunk {
515 b := s.heapBits()
516 clear(b)
517 }
518 if goexperiment.GreenTeaGC && gcUsesSpanInlineMarkBits(s.elemsize) {
519 s.initInlineMarkBits()
520 }
521 }
522
523 // heapBits returns the heap ptr/scalar bits stored at the end of the span for
524 // small object spans and heap arena spans.
525 //
526 // Note that the uintptr of each element means something different for small object
527 // spans and for heap arena spans. Small object spans are easy: they're never interpreted
528 // as anything but uintptr, so they're immune to differences in endianness. However, the
529 // heapBits for user arena spans is exposed through a dummy type descriptor, so the byte
530 // ordering needs to match the same byte ordering the compiler would emit. The compiler always
531 // emits the bitmap data in little endian byte ordering, so on big endian platforms these
532 // uintptrs will have their byte orders swapped from what they normally would be.
533 //
534 // heapBitsInSpan(span.elemsize) or span.isUserArenaChunk must be true.
535 //
536 //go:nosplit
537 func (span *mspan) heapBits() []uintptr {
538 const doubleCheck = false
539
540 if doubleCheck && !span.isUserArenaChunk {
541 if span.spanclass.noscan() {
542 throw("heapBits called for noscan")
543 }
544 if span.elemsize > gc.MinSizeForMallocHeader {
545 throw("heapBits called for span class that should have a malloc header")
546 }
547 }
548 // Find the bitmap at the end of the span.
549 //
550 // Nearly every span with heap bits is exactly one page in size. Arenas are the only exception.
551 if span.npages == 1 {
552 // This will be inlined and constant-folded down.
553 return heapBitsSlice(span.base(), pageSize, span.elemsize)
554 }
555 return heapBitsSlice(span.base(), span.npages*pageSize, span.elemsize)
556 }
557
558 // Helper for constructing a slice for the span's heap bits.
559 //
560 //go:nosplit
561 func heapBitsSlice(spanBase, spanSize, elemsize uintptr) []uintptr {
562 base, bitmapSize := spanHeapBitsRange(spanBase, spanSize, elemsize)
563 elems := int(bitmapSize / goarch.PtrSize)
564 var sl notInHeapSlice
565 sl = notInHeapSlice{(*notInHeap)(unsafe.Pointer(base)), elems, elems}
566 return *(*[]uintptr)(unsafe.Pointer(&sl))
567 }
568
569 //go:nosplit
570 func spanHeapBitsRange(spanBase, spanSize, elemsize uintptr) (base, size uintptr) {
571 size = spanSize / goarch.PtrSize / 8
572 base = spanBase + spanSize - size
573 if goexperiment.GreenTeaGC && gcUsesSpanInlineMarkBits(elemsize) {
574 base -= unsafe.Sizeof(spanInlineMarkBits{})
575 }
576 return
577 }
578
579 // heapBitsSmallForAddr loads the heap bits for the object stored at addr from span.heapBits.
580 //
581 // addr must be the base pointer of an object in the span. heapBitsInSpan(span.elemsize)
582 // must be true.
583 //
584 //go:nosplit
585 func (span *mspan) heapBitsSmallForAddr(addr uintptr) uintptr {
586 hbitsBase, _ := spanHeapBitsRange(span.base(), span.npages*pageSize, span.elemsize)
587 hbits := (*byte)(unsafe.Pointer(hbitsBase))
588
589 // These objects are always small enough that their bitmaps
590 // fit in a single word, so just load the word or two we need.
591 //
592 // Mirrors mspan.writeHeapBitsSmall.
593 //
594 // We should be using heapBits(), but unfortunately it introduces
595 // both bounds checks panics and throw which causes us to exceed
596 // the nosplit limit in quite a few cases.
597 i := (addr - span.base()) / goarch.PtrSize / ptrBits
598 j := (addr - span.base()) / goarch.PtrSize % ptrBits
599 bits := span.elemsize / goarch.PtrSize
600 word0 := (*uintptr)(unsafe.Pointer(addb(hbits, goarch.PtrSize*(i+0))))
601 word1 := (*uintptr)(unsafe.Pointer(addb(hbits, goarch.PtrSize*(i+1))))
602
603 var read uintptr
604 if j+bits > ptrBits {
605 // Two reads.
606 bits0 := ptrBits - j
607 bits1 := bits - bits0
608 read = *word0 >> j
609 read |= (*word1 & ((1 << bits1) - 1)) << bits0
610 } else {
611 // One read.
612 read = (*word0 >> j) & ((1 << bits) - 1)
613 }
614 return read
615 }
616
617 // writeHeapBitsSmall writes the heap bits for small objects whose ptr/scalar data is
618 // stored as a bitmap at the end of the span.
619 //
620 // Assumes dataSize is <= ptrBits*goarch.PtrSize. x must be a pointer into the span.
621 // heapBitsInSpan(dataSize) must be true. dataSize must be >= typ.Size_.
622 //
623 //go:nosplit
624 func (span *mspan) writeHeapBitsSmall(x, dataSize uintptr, typ *_type) (scanSize uintptr) {
625 // The objects here are always really small, so a single load is sufficient.
626 src0 := readUintptr(getGCMask(typ))
627
628 // Create repetitions of the bitmap if we have a small slice backing store.
629 scanSize = typ.PtrBytes
630 src := src0
631 if typ.Size_ == goarch.PtrSize {
632 src = (1 << (dataSize / goarch.PtrSize)) - 1
633 } else {
634 // N.B. We rely on dataSize being an exact multiple of the type size.
635 // The alternative is to be defensive and mask out src to the length
636 // of dataSize. The purpose is to save on one additional masking operation.
637 if doubleCheckHeapSetType && !asanenabled && dataSize%typ.Size_ != 0 {
638 throw("runtime: (*mspan).writeHeapBitsSmall: dataSize is not a multiple of typ.Size_")
639 }
640 for i := typ.Size_; i < dataSize; i += typ.Size_ {
641 src |= src0 << (i / goarch.PtrSize)
642 scanSize += typ.Size_
643 }
644 if asanenabled {
645 // Mask src down to dataSize. dataSize is going to be a strange size because of
646 // the redzone required for allocations when asan is enabled.
647 src &= (1 << (dataSize / goarch.PtrSize)) - 1
648 }
649 }
650
651 // Since we're never writing more than one uintptr's worth of bits, we're either going
652 // to do one or two writes.
653 dstBase, _ := spanHeapBitsRange(span.base(), pageSize, span.elemsize)
654 dst := unsafe.Pointer(dstBase)
655 o := (x - span.base()) / goarch.PtrSize
656 i := o / ptrBits
657 j := o % ptrBits
658 bits := span.elemsize / goarch.PtrSize
659 if j+bits > ptrBits {
660 // Two writes.
661 bits0 := ptrBits - j
662 bits1 := bits - bits0
663 dst0 := (*uintptr)(add(dst, (i+0)*goarch.PtrSize))
664 dst1 := (*uintptr)(add(dst, (i+1)*goarch.PtrSize))
665 *dst0 = (*dst0)&(^uintptr(0)>>bits0) | (src << j)
666 *dst1 = (*dst1)&^((1<<bits1)-1) | (src >> bits0)
667 } else {
668 // One write.
669 dst := (*uintptr)(add(dst, i*goarch.PtrSize))
670 *dst = (*dst)&^(((1<<bits)-1)<<j) | (src << j)
671 }
672
673 const doubleCheck = false
674 if doubleCheck {
675 srcRead := span.heapBitsSmallForAddr(x)
676 if srcRead != src {
677 print("runtime: x=", hex(x), " i=", i, " j=", j, " bits=", bits, "\n")
678 print("runtime: dataSize=", dataSize, " typ.Size_=", typ.Size_, " typ.PtrBytes=", typ.PtrBytes, "\n")
679 print("runtime: src0=", hex(src0), " src=", hex(src), " srcRead=", hex(srcRead), "\n")
680 throw("bad pointer bits written for small object")
681 }
682 }
683 return
684 }
685
686 // heapSetType* functions record that the new allocation [x, x+size)
687 // holds in [x, x+dataSize) one or more values of type typ.
688 // (The number of values is given by dataSize / typ.Size.)
689 // If dataSize < size, the fragment [x+dataSize, x+size) is
690 // recorded as non-pointer data.
691 // It is known that the type has pointers somewhere;
692 // malloc does not call heapSetType* when there are no pointers.
693 //
694 // There can be read-write races between heapSetType* and things
695 // that read the heap metadata like scanObject. However, since
696 // heapSetType* is only used for objects that have not yet been
697 // made reachable, readers will ignore bits being modified by this
698 // function. This does mean this function cannot transiently modify
699 // shared memory that belongs to neighboring objects. Also, on weakly-ordered
700 // machines, callers must execute a store/store (publication) barrier
701 // between calling this function and making the object reachable.
702
703 const doubleCheckHeapSetType = doubleCheckMalloc
704
705 func heapSetTypeNoHeader(x, dataSize uintptr, typ *_type, span *mspan) uintptr {
706 if doubleCheckHeapSetType && (!heapBitsInSpan(dataSize) || !heapBitsInSpan(span.elemsize)) {
707 throw("tried to write heap bits, but no heap bits in span")
708 }
709 scanSize := span.writeHeapBitsSmall(x, dataSize, typ)
710 if doubleCheckHeapSetType {
711 doubleCheckHeapType(x, dataSize, typ, nil, span)
712 }
713 return scanSize
714 }
715
716 func heapSetTypeSmallHeader(x, dataSize uintptr, typ *_type, header **_type, span *mspan) uintptr {
717 if header == nil {
718 // This nil check and throw is almost pointless. Normally we would
719 // expect header to never be nil. However, this is called on potentially
720 // freshly-allocated virtual memory. As of 2025, the compiler-inserted
721 // nil check is not a branch but a memory read that we expect to fault
722 // if the pointer really is nil.
723 //
724 // However, this causes a read of the page, and operating systems may
725 // take it as a hint to back the accessed memory with a read-only zero
726 // page. However, we immediately write to this memory, which can then
727 // force operating systems to have to update the page table and flush
728 // the TLB.
729 //
730 // This nil check is thus an explicit branch instead of what the compiler
731 // would insert circa 2025, which is a memory read instruction.
732 //
733 // See go.dev/issue/74375 for details of a similar issue in
734 // spanInlineMarkBits.
735 throw("runtime: pointer to heap type header nil?")
736 }
737 *header = typ
738 if doubleCheckHeapSetType {
739 doubleCheckHeapType(x, dataSize, typ, header, span)
740 }
741 return span.elemsize
742 }
743
744 func heapSetTypeLarge(x, dataSize uintptr, typ *_type, span *mspan) uintptr {
745 gctyp := typ
746 // Write out the header atomically to synchronize with the garbage collector.
747 //
748 // This atomic store is paired with an atomic load in typePointersOfUnchecked.
749 // This store ensures that initializing x's memory cannot be reordered after
750 // this store. Meanwhile the load in typePointersOfUnchecked ensures that
751 // reading x's memory cannot be reordered before largeType is loaded. Together,
752 // these two operations guarantee that the garbage collector can only see
753 // initialized memory if largeType is non-nil.
754 //
755 // Gory details below...
756 //
757 // Ignoring conservative scanning for a moment, this store need not be atomic
758 // if we have a publication barrier on our side. This is because the garbage
759 // collector cannot observe x unless:
760 // 1. It stops this goroutine and scans its stack, or
761 // 2. We return from mallocgc and publish the pointer somewhere.
762 // Either case requires a write on our side, followed by some synchronization
763 // followed by a read by the garbage collector.
764 //
765 // In case (1), the garbage collector can only observe a nil largeType, since it
766 // had to stop our goroutine when it was preemptible during zeroing. For the
767 // duration of the zeroing, largeType is nil and the object has nothing interesting
768 // for the garbage collector to look at, so the garbage collector will not access
769 // the object at all.
770 //
771 // In case (2), the garbage collector can also observe a nil largeType. This
772 // might happen if the object was newly allocated, and a new GC cycle didn't start
773 // (that would require a global barrier, STW). In this case, the garbage collector
774 // will once again ignore the object, and that's safe because objects are
775 // allocate-black.
776 //
777 // However, the garbage collector can also observe a non-nil largeType in case (2).
778 // This is still okay, since to access the object's memory, it must have first
779 // loaded the object's pointer from somewhere. This makes the access of the object's
780 // memory a data-dependent load, and our publication barrier in the allocator
781 // guarantees that a data-dependent load must observe a version of the object's
782 // data from after the publication barrier executed.
783 //
784 // Unfortunately conservative scanning is a problem. There's no guarantee of a
785 // data dependency as in case (2) because conservative scanning can produce pointers
786 // 'out of thin air' in that it need not have been written somewhere by the allocating
787 // thread first. It might not even be a pointer, or it could be a pointer written to
788 // some stack location long ago. This is the fundamental reason why we need
789 // explicit synchronization somewhere in this whole mess. We choose to put that
790 // synchronization on largeType.
791 //
792 // As described at the very top, the treating largeType as an atomic variable, on
793 // both the reader and writer side, is sufficient to ensure that only initialized
794 // memory at x will be observed if largeType is non-nil.
795 atomic.StorepNoWB(unsafe.Pointer(&span.largeType), unsafe.Pointer(gctyp))
796 if doubleCheckHeapSetType {
797 doubleCheckHeapType(x, dataSize, typ, &span.largeType, span)
798 }
799 return span.elemsize
800 }
801
802 func doubleCheckHeapType(x, dataSize uintptr, gctyp *_type, header **_type, span *mspan) {
803 doubleCheckHeapPointers(x, dataSize, gctyp, header, span)
804
805 // To exercise the less common path more often, generate
806 // a random interior pointer and make sure iterating from
807 // that point works correctly too.
808 maxIterBytes := span.elemsize
809 if header == nil {
810 maxIterBytes = dataSize
811 }
812 off := alignUp(uintptr(cheaprand())%dataSize, goarch.PtrSize)
813 size := dataSize - off
814 if size == 0 {
815 off -= goarch.PtrSize
816 size += goarch.PtrSize
817 }
818 interior := x + off
819 size -= alignDown(uintptr(cheaprand())%size, goarch.PtrSize)
820 if size == 0 {
821 size = goarch.PtrSize
822 }
823 // Round up the type to the size of the type.
824 size = (size + gctyp.Size_ - 1) / gctyp.Size_ * gctyp.Size_
825 if interior+size > x+maxIterBytes {
826 size = x + maxIterBytes - interior
827 }
828 doubleCheckHeapPointersInterior(x, interior, size, dataSize, gctyp, header, span)
829 }
830
831 func doubleCheckHeapPointers(x, dataSize uintptr, typ *_type, header **_type, span *mspan) {
832 // Check that scanning the full object works.
833 tp := span.typePointersOfUnchecked(span.objBase(x))
834 maxIterBytes := span.elemsize
835 if header == nil {
836 maxIterBytes = dataSize
837 }
838 bad := false
839 for i := uintptr(0); i < maxIterBytes; i += goarch.PtrSize {
840 // Compute the pointer bit we want at offset i.
841 want := false
842 if i < span.elemsize {
843 off := i % typ.Size_
844 if off < typ.PtrBytes {
845 j := off / goarch.PtrSize
846 want = *addb(getGCMask(typ), j/8)>>(j%8)&1 != 0
847 }
848 }
849 if want {
850 var addr uintptr
851 tp, addr = tp.next(x + span.elemsize)
852 if addr == 0 {
853 println("runtime: found bad iterator")
854 }
855 if addr != x+i {
856 print("runtime: addr=", hex(addr), " x+i=", hex(x+i), "\n")
857 bad = true
858 }
859 }
860 }
861 if !bad {
862 var addr uintptr
863 tp, addr = tp.next(x + span.elemsize)
864 if addr == 0 {
865 return
866 }
867 println("runtime: extra pointer:", hex(addr))
868 }
869 print("runtime: hasHeader=", header != nil, " typ.Size_=", typ.Size_, " TFlagGCMaskOnDemaind=", typ.TFlag&abi.TFlagGCMaskOnDemand != 0, "\n")
870 print("runtime: x=", hex(x), " dataSize=", dataSize, " elemsize=", span.elemsize, "\n")
871 print("runtime: typ=", unsafe.Pointer(typ), " typ.PtrBytes=", typ.PtrBytes, "\n")
872 print("runtime: limit=", hex(x+span.elemsize), "\n")
873 tp = span.typePointersOfUnchecked(x)
874 dumpTypePointers(tp)
875 for {
876 var addr uintptr
877 if tp, addr = tp.next(x + span.elemsize); addr == 0 {
878 println("runtime: would've stopped here")
879 dumpTypePointers(tp)
880 break
881 }
882 print("runtime: addr=", hex(addr), "\n")
883 dumpTypePointers(tp)
884 }
885 throw("heapSetType: pointer entry not correct")
886 }
887
888 func doubleCheckHeapPointersInterior(x, interior, size, dataSize uintptr, typ *_type, header **_type, span *mspan) {
889 bad := false
890 if interior < x {
891 print("runtime: interior=", hex(interior), " x=", hex(x), "\n")
892 throw("found bad interior pointer")
893 }
894 off := interior - x
895 tp := span.typePointersOf(interior, size)
896 for i := off; i < off+size; i += goarch.PtrSize {
897 // Compute the pointer bit we want at offset i.
898 want := false
899 if i < span.elemsize {
900 off := i % typ.Size_
901 if off < typ.PtrBytes {
902 j := off / goarch.PtrSize
903 want = *addb(getGCMask(typ), j/8)>>(j%8)&1 != 0
904 }
905 }
906 if want {
907 var addr uintptr
908 tp, addr = tp.next(interior + size)
909 if addr == 0 {
910 println("runtime: found bad iterator")
911 bad = true
912 }
913 if addr != x+i {
914 print("runtime: addr=", hex(addr), " x+i=", hex(x+i), "\n")
915 bad = true
916 }
917 }
918 }
919 if !bad {
920 var addr uintptr
921 tp, addr = tp.next(interior + size)
922 if addr == 0 {
923 return
924 }
925 println("runtime: extra pointer:", hex(addr))
926 }
927 print("runtime: hasHeader=", header != nil, " typ.Size_=", typ.Size_, "\n")
928 print("runtime: x=", hex(x), " dataSize=", dataSize, " elemsize=", span.elemsize, " interior=", hex(interior), " size=", size, "\n")
929 print("runtime: limit=", hex(interior+size), "\n")
930 tp = span.typePointersOf(interior, size)
931 dumpTypePointers(tp)
932 for {
933 var addr uintptr
934 if tp, addr = tp.next(interior + size); addr == 0 {
935 println("runtime: would've stopped here")
936 dumpTypePointers(tp)
937 break
938 }
939 print("runtime: addr=", hex(addr), "\n")
940 dumpTypePointers(tp)
941 }
942
943 print("runtime: want: ")
944 for i := off; i < off+size; i += goarch.PtrSize {
945 // Compute the pointer bit we want at offset i.
946 want := false
947 if i < dataSize {
948 off := i % typ.Size_
949 if off < typ.PtrBytes {
950 j := off / goarch.PtrSize
951 want = *addb(getGCMask(typ), j/8)>>(j%8)&1 != 0
952 }
953 }
954 if want {
955 print("1")
956 } else {
957 print("0")
958 }
959 }
960 println()
961
962 throw("heapSetType: pointer entry not correct")
963 }
964
965 //go:nosplit
966 func doubleCheckTypePointersOfType(s *mspan, typ *_type, addr, size uintptr) {
967 if typ == nil {
968 return
969 }
970 if typ.Kind() == abi.Interface {
971 // Interfaces are unfortunately inconsistently handled
972 // when it comes to the type pointer, so it's easy to
973 // produce a lot of false positives here.
974 return
975 }
976 tp0 := s.typePointersOfType(typ, addr)
977 tp1 := s.typePointersOf(addr, size)
978 failed := false
979 for {
980 var addr0, addr1 uintptr
981 tp0, addr0 = tp0.next(addr + size)
982 tp1, addr1 = tp1.next(addr + size)
983 if addr0 != addr1 {
984 failed = true
985 break
986 }
987 if addr0 == 0 {
988 break
989 }
990 }
991 if failed {
992 tp0 := s.typePointersOfType(typ, addr)
993 tp1 := s.typePointersOf(addr, size)
994 print("runtime: addr=", hex(addr), " size=", size, "\n")
995 print("runtime: type=", toRType(typ).string(), "\n")
996 dumpTypePointers(tp0)
997 dumpTypePointers(tp1)
998 for {
999 var addr0, addr1 uintptr
1000 tp0, addr0 = tp0.next(addr + size)
1001 tp1, addr1 = tp1.next(addr + size)
1002 print("runtime: ", hex(addr0), " ", hex(addr1), "\n")
1003 if addr0 == 0 && addr1 == 0 {
1004 break
1005 }
1006 }
1007 throw("mismatch between typePointersOfType and typePointersOf")
1008 }
1009 }
1010
1011 func dumpTypePointers(tp typePointers) {
1012 print("runtime: tp.elem=", hex(tp.elem), " tp.typ=", unsafe.Pointer(tp.typ), "\n")
1013 print("runtime: tp.addr=", hex(tp.addr), " tp.mask=")
1014 for i := uintptr(0); i < ptrBits; i++ {
1015 if tp.mask&(uintptr(1)<<i) != 0 {
1016 print("1")
1017 } else {
1018 print("0")
1019 }
1020 }
1021 println()
1022 }
1023
1024 // addb returns the byte pointer p+n.
1025 //
1026 //go:nowritebarrier
1027 //go:nosplit
1028 func addb(p *byte, n uintptr) *byte {
1029 // Note: wrote out full expression instead of calling add(p, n)
1030 // to reduce the number of temporaries generated by the
1031 // compiler for this trivial expression during inlining.
1032 return (*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + n))
1033 }
1034
1035 // subtractb returns the byte pointer p-n.
1036 //
1037 //go:nowritebarrier
1038 //go:nosplit
1039 func subtractb(p *byte, n uintptr) *byte {
1040 // Note: wrote out full expression instead of calling add(p, -n)
1041 // to reduce the number of temporaries generated by the
1042 // compiler for this trivial expression during inlining.
1043 return (*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) - n))
1044 }
1045
1046 // add1 returns the byte pointer p+1.
1047 //
1048 //go:nowritebarrier
1049 //go:nosplit
1050 func add1(p *byte) *byte {
1051 // Note: wrote out full expression instead of calling addb(p, 1)
1052 // to reduce the number of temporaries generated by the
1053 // compiler for this trivial expression during inlining.
1054 return (*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + 1))
1055 }
1056
1057 // subtract1 returns the byte pointer p-1.
1058 //
1059 // nosplit because it is used during write barriers and must not be preempted.
1060 //
1061 //go:nowritebarrier
1062 //go:nosplit
1063 func subtract1(p *byte) *byte {
1064 // Note: wrote out full expression instead of calling subtractb(p, 1)
1065 // to reduce the number of temporaries generated by the
1066 // compiler for this trivial expression during inlining.
1067 return (*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) - 1))
1068 }
1069
1070 // markBits provides access to the mark bit for an object in the heap.
1071 // bytep points to the byte holding the mark bit.
1072 // mask is a byte with a single bit set that can be &ed with *bytep
1073 // to see if the bit has been set.
1074 // *m.byte&m.mask != 0 indicates the mark bit is set.
1075 // index can be used along with span information to generate
1076 // the address of the object in the heap.
1077 // We maintain one set of mark bits for allocation and one for
1078 // marking purposes.
1079 type markBits struct {
1080 bytep *uint8
1081 mask uint8
1082 index uintptr
1083 }
1084
1085 //go:nosplit
1086 func (s *mspan) allocBitsForIndex(allocBitIndex uintptr) markBits {
1087 bytep, mask := s.allocBits.bitp(allocBitIndex)
1088 return markBits{bytep, mask, allocBitIndex}
1089 }
1090
1091 // refillAllocCache takes 8 bytes s.allocBits starting at whichByte
1092 // and negates them so that ctz (count trailing zeros) instructions
1093 // can be used. It then places these 8 bytes into the cached 64 bit
1094 // s.allocCache.
1095 func (s *mspan) refillAllocCache(whichByte uint16) {
1096 bytes := (*[8]uint8)(unsafe.Pointer(s.allocBits.bytep(uintptr(whichByte))))
1097 aCache := uint64(0)
1098 aCache |= uint64(bytes[0])
1099 aCache |= uint64(bytes[1]) << (1 * 8)
1100 aCache |= uint64(bytes[2]) << (2 * 8)
1101 aCache |= uint64(bytes[3]) << (3 * 8)
1102 aCache |= uint64(bytes[4]) << (4 * 8)
1103 aCache |= uint64(bytes[5]) << (5 * 8)
1104 aCache |= uint64(bytes[6]) << (6 * 8)
1105 aCache |= uint64(bytes[7]) << (7 * 8)
1106 s.allocCache = ^aCache
1107 }
1108
1109 // nextFreeIndex returns the index of the next free object in s at
1110 // or after s.freeindex.
1111 // There are hardware instructions that can be used to make this
1112 // faster if profiling warrants it.
1113 func (s *mspan) nextFreeIndex() uint16 {
1114 sfreeindex := s.freeindex
1115 snelems := s.nelems
1116 if sfreeindex == snelems {
1117 return sfreeindex
1118 }
1119 if sfreeindex > snelems {
1120 throw("s.freeindex > s.nelems")
1121 }
1122
1123 aCache := s.allocCache
1124
1125 bitIndex := sys.TrailingZeros64(aCache)
1126 for bitIndex == 64 {
1127 // Move index to start of next cached bits.
1128 sfreeindex = (sfreeindex + 64) &^ (64 - 1)
1129 if sfreeindex >= snelems {
1130 s.freeindex = snelems
1131 return snelems
1132 }
1133 whichByte := sfreeindex / 8
1134 // Refill s.allocCache with the next 64 alloc bits.
1135 s.refillAllocCache(whichByte)
1136 aCache = s.allocCache
1137 bitIndex = sys.TrailingZeros64(aCache)
1138 // nothing available in cached bits
1139 // grab the next 8 bytes and try again.
1140 }
1141 result := sfreeindex + uint16(bitIndex)
1142 if result >= snelems {
1143 s.freeindex = snelems
1144 return snelems
1145 }
1146
1147 s.allocCache >>= uint(bitIndex + 1)
1148 sfreeindex = result + 1
1149
1150 if sfreeindex%64 == 0 && sfreeindex != snelems {
1151 // We just incremented s.freeindex so it isn't 0.
1152 // As each 1 in s.allocCache was encountered and used for allocation
1153 // it was shifted away. At this point s.allocCache contains all 0s.
1154 // Refill s.allocCache so that it corresponds
1155 // to the bits at s.allocBits starting at s.freeindex.
1156 whichByte := sfreeindex / 8
1157 s.refillAllocCache(whichByte)
1158 }
1159 s.freeindex = sfreeindex
1160 return result
1161 }
1162
1163 // isFree reports whether the index'th object in s is unallocated.
1164 //
1165 // The caller must ensure s.state is mSpanInUse, and there must have
1166 // been no preemption points since ensuring this (which could allow a
1167 // GC transition, which would allow the state to change).
1168 //
1169 // Callers must ensure that the index passed here must not have been
1170 // produced from a pointer that came from 'thin air', as might happen
1171 // with conservative scanning.
1172 func (s *mspan) isFree(index uintptr) bool {
1173 if index < uintptr(s.freeindex) {
1174 return false
1175 }
1176 bytep, mask := s.allocBits.bitp(index)
1177 return *bytep&mask == 0
1178 }
1179
1180 // isFreeOrNewlyAllocated reports whether the index'th object in s is
1181 // either unallocated or has been allocated since the beginning of the
1182 // last mark phase.
1183 //
1184 // The caller must ensure s.state is mSpanInUse, and there must have
1185 // been no preemption points since ensuring this (which could allow a
1186 // GC transition, which would allow the state to change).
1187 //
1188 // Callers must ensure that the index passed here must not have been
1189 // produced from a pointer that came from 'thin air', as might happen
1190 // with conservative scanning, unless the GC is currently in the mark
1191 // phase. If the GC is currently in the mark phase, this function is
1192 // safe to call for out-of-thin-air pointers.
1193 func (s *mspan) isFreeOrNewlyAllocated(index uintptr) bool {
1194 if index < uintptr(s.freeIndexForScan) {
1195 return false
1196 }
1197 bytep, mask := s.allocBits.bitp(index)
1198 return *bytep&mask == 0
1199 }
1200
1201 // divideByElemSize returns n/s.elemsize.
1202 // n must be within [0, s.npages*_PageSize),
1203 // or may be exactly s.npages*_PageSize
1204 // if s.elemsize is from sizeclasses.go.
1205 //
1206 // nosplit, because it is called by objIndex, which is nosplit
1207 //
1208 //go:nosplit
1209 func (s *mspan) divideByElemSize(n uintptr) uintptr {
1210 const doubleCheck = false
1211
1212 // See explanation in mksizeclasses.go's computeDivMagic.
1213 q := uintptr((uint64(n) * uint64(s.divMul)) >> 32)
1214
1215 if doubleCheck && q != n/s.elemsize {
1216 println(n, "/", s.elemsize, "should be", n/s.elemsize, "but got", q)
1217 throw("bad magic division")
1218 }
1219 return q
1220 }
1221
1222 // nosplit, because it is called by other nosplit code like findObject
1223 //
1224 //go:nosplit
1225 func (s *mspan) objIndex(p uintptr) uintptr {
1226 return s.divideByElemSize(p - s.base())
1227 }
1228
1229 func markBitsForAddr(p uintptr) markBits {
1230 s := spanOf(p)
1231 objIndex := s.objIndex(p)
1232 return s.markBitsForIndex(objIndex)
1233 }
1234
1235 // isMarked reports whether mark bit m is set.
1236 func (m markBits) isMarked() bool {
1237 return *m.bytep&m.mask != 0
1238 }
1239
1240 // setMarked sets the marked bit in the markbits, atomically.
1241 func (m markBits) setMarked() {
1242 // Might be racing with other updates, so use atomic update always.
1243 // We used to be clever here and use a non-atomic update in certain
1244 // cases, but it's not worth the risk.
1245 atomic.Or8(m.bytep, m.mask)
1246 }
1247
1248 // setMarkedNonAtomic sets the marked bit in the markbits, non-atomically.
1249 func (m markBits) setMarkedNonAtomic() {
1250 *m.bytep |= m.mask
1251 }
1252
1253 // clearMarked clears the marked bit in the markbits, atomically.
1254 func (m markBits) clearMarked() {
1255 // Might be racing with other updates, so use atomic update always.
1256 // We used to be clever here and use a non-atomic update in certain
1257 // cases, but it's not worth the risk.
1258 atomic.And8(m.bytep, ^m.mask)
1259 }
1260
1261 // markBitsForSpan returns the markBits for the span base address base.
1262 func markBitsForSpan(base uintptr) (mbits markBits) {
1263 mbits = markBitsForAddr(base)
1264 if mbits.mask != 1 {
1265 throw("markBitsForSpan: unaligned start")
1266 }
1267 return mbits
1268 }
1269
1270 // isMarkedOrNotInHeap returns true if a pointer is in the heap and marked,
1271 // or if the pointer is not in the heap. Used by goroutine leak detection
1272 // to determine if concurrency resources are reachable in memory.
1273 func isMarkedOrNotInHeap(p unsafe.Pointer) bool {
1274 obj, span, objIndex := findObject(uintptr(p), 0, 0)
1275 if obj != 0 {
1276 mbits := span.markBitsForIndex(objIndex)
1277 return mbits.isMarked()
1278 }
1279
1280 // If we fall through to get here, the object is not in the heap.
1281 // In this case, it is either a pointer to a stack object or a global resource.
1282 // Treat it as reachable in memory by default, to be safe.
1283 //
1284 // TODO(vsaioc): we could be more precise by checking against the stacks
1285 // of runnable goroutines. I don't think this is necessary, based on what we've seen, but
1286 // let's keep the option open in case the runtime evolves.
1287 // This will (naively) lead to quadratic blow-up for goroutine leak detection,
1288 // but if it is only run on demand, maybe the extra cost is not a show-stopper.
1289 return true
1290 }
1291
1292 // advance advances the markBits to the next object in the span.
1293 func (m *markBits) advance() {
1294 if m.mask == 1<<7 {
1295 m.bytep = (*uint8)(unsafe.Pointer(uintptr(unsafe.Pointer(m.bytep)) + 1))
1296 m.mask = 1
1297 } else {
1298 m.mask = m.mask << 1
1299 }
1300 m.index++
1301 }
1302
1303 // clobberdeadPtr is a special value that is used by the compiler to
1304 // clobber dead stack slots, when -clobberdead flag is set.
1305 const clobberdeadPtr = uintptr(0xdeaddead | 0xdeaddead<<((^uintptr(0)>>63)*32))
1306
1307 // badPointer throws bad pointer in heap panic.
1308 func badPointer(s *mspan, p, refBase, refOff uintptr) {
1309 // Typically this indicates an incorrect use
1310 // of unsafe or cgo to store a bad pointer in
1311 // the Go heap. It may also indicate a runtime
1312 // bug.
1313 //
1314 // TODO(austin): We could be more aggressive
1315 // and detect pointers to unallocated objects
1316 // in allocated spans.
1317 printlock()
1318 print("runtime: pointer ", hex(p))
1319 if s != nil {
1320 state := s.state.get()
1321 if state != mSpanInUse {
1322 print(" to unallocated span")
1323 } else {
1324 print(" to unused region of span")
1325 }
1326 print(" span.base()=", hex(s.base()), " span.limit=", hex(s.limit), " span.state=", state)
1327 }
1328 print("\n")
1329 if refBase != 0 {
1330 print("runtime: found in object at *(", hex(refBase), "+", hex(refOff), ")\n")
1331 gcDumpObject("object", refBase, refOff)
1332 }
1333 getg().m.traceback = 2
1334 throw("found bad pointer in Go heap (incorrect use of unsafe or cgo?)")
1335 }
1336
1337 // findObject returns the base address for the heap object containing
1338 // the address p, the object's span, and the index of the object in s.
1339 // If p does not point into a heap object, it returns base == 0.
1340 //
1341 // If p points is an invalid heap pointer and debug.invalidptr != 0,
1342 // findObject panics.
1343 //
1344 // refBase and refOff optionally give the base address of the object
1345 // in which the pointer p was found and the byte offset at which it
1346 // was found. These are used for error reporting.
1347 //
1348 // It is nosplit so it is safe for p to be a pointer to the current goroutine's stack.
1349 // Since p is a uintptr, it would not be adjusted if the stack were to move.
1350 //
1351 // findObject should be an internal detail,
1352 // but widely used packages access it using linkname.
1353 // Notable members of the hall of shame include:
1354 // - github.com/bytedance/sonic
1355 //
1356 // Do not remove or change the type signature.
1357 // See go.dev/issue/67401.
1358 //
1359 //go:linkname findObject
1360 //go:nosplit
1361 func findObject(p, refBase, refOff uintptr) (base uintptr, s *mspan, objIndex uintptr) {
1362 s = spanOf(p)
1363 // If s is nil, the virtual address has never been part of the heap.
1364 // This pointer may be to some mmap'd region, so we allow it.
1365 if s == nil {
1366 if (GOARCH == "amd64" || GOARCH == "arm64") && p == clobberdeadPtr && debug.invalidptr != 0 {
1367 // Crash if clobberdeadPtr is seen. Only on AMD64 and ARM64 for now,
1368 // as they are the only platform where compiler's clobberdead mode is
1369 // implemented. On these platforms clobberdeadPtr cannot be a valid address.
1370 badPointer(s, p, refBase, refOff)
1371 }
1372 return
1373 }
1374 // If p is a bad pointer, it may not be in s's bounds.
1375 //
1376 // Check s.state to synchronize with span initialization
1377 // before checking other fields. See also spanOfHeap.
1378 if state := s.state.get(); state != mSpanInUse || p < s.base() || p >= s.limit {
1379 // Pointers into stacks are also ok, the runtime manages these explicitly.
1380 if state == mSpanManual {
1381 return
1382 }
1383 // The following ensures that we are rigorous about what data
1384 // structures hold valid pointers.
1385 if debug.invalidptr != 0 {
1386 badPointer(s, p, refBase, refOff)
1387 }
1388 return
1389 }
1390
1391 objIndex = s.objIndex(p)
1392 base = s.base() + objIndex*s.elemsize
1393 return
1394 }
1395
1396 // reflect_verifyNotInHeapPtr reports whether converting the not-in-heap pointer into a unsafe.Pointer is ok.
1397 //
1398 //go:linkname reflect_verifyNotInHeapPtr reflect.verifyNotInHeapPtr
1399 func reflect_verifyNotInHeapPtr(p uintptr) bool {
1400 // Conversion to a pointer is ok as long as findObject above does not call badPointer.
1401 // Since we're already promised that p doesn't point into the heap, just disallow heap
1402 // pointers and the special clobbered pointer.
1403 return spanOf(p) == nil && p != clobberdeadPtr
1404 }
1405
1406 const ptrBits = 8 * goarch.PtrSize
1407
1408 // bulkBarrierBitmap executes write barriers for copying from [src,
1409 // src+size) to [dst, dst+size) using a 1-bit pointer bitmap. src is
1410 // assumed to start maskOffset bytes into the data covered by the
1411 // bitmap in bits (which may not be a multiple of 8).
1412 //
1413 // This is used by bulkBarrierPreWrite for writes to data and BSS.
1414 //
1415 //go:nosplit
1416 func bulkBarrierBitmap(dst, src, size, maskOffset uintptr, bits *uint8) {
1417 word := maskOffset / goarch.PtrSize
1418 bits = addb(bits, word/8)
1419 mask := uint8(1) << (word % 8)
1420
1421 buf := &getg().m.p.ptr().wbBuf
1422 for i := uintptr(0); i < size; i += goarch.PtrSize {
1423 if mask == 0 {
1424 bits = addb(bits, 1)
1425 if *bits == 0 {
1426 // Skip 8 words.
1427 i += 7 * goarch.PtrSize
1428 continue
1429 }
1430 mask = 1
1431 }
1432 if *bits&mask != 0 {
1433 dstx := (*uintptr)(unsafe.Pointer(dst + i))
1434 if src == 0 {
1435 p := buf.get1()
1436 p[0] = *dstx
1437 } else {
1438 srcx := (*uintptr)(unsafe.Pointer(src + i))
1439 p := buf.get2()
1440 p[0] = *dstx
1441 p[1] = *srcx
1442 }
1443 }
1444 mask <<= 1
1445 }
1446 }
1447
1448 // typeBitsBulkBarrier executes a write barrier for every
1449 // pointer that would be copied from [src, src+size) to [dst,
1450 // dst+size) by a memmove using the type bitmap to locate those
1451 // pointer slots.
1452 //
1453 // The type typ must correspond exactly to [src, src+size) and [dst, dst+size).
1454 // dst, src, and size must be pointer-aligned.
1455 //
1456 // Must not be preempted because it typically runs right before memmove,
1457 // and the GC must observe them as an atomic action.
1458 //
1459 // Callers must perform cgo checks if goexperiment.CgoCheck2.
1460 //
1461 //go:nosplit
1462 func typeBitsBulkBarrier(typ *_type, dst, src, size uintptr) {
1463 if typ == nil {
1464 throw("runtime: typeBitsBulkBarrier without type")
1465 }
1466 if typ.Size_ != size {
1467 println("runtime: typeBitsBulkBarrier with type ", toRType(typ).string(), " of size ", typ.Size_, " but memory size", size)
1468 throw("runtime: invalid typeBitsBulkBarrier")
1469 }
1470 if !writeBarrier.enabled {
1471 return
1472 }
1473 ptrmask := getGCMask(typ)
1474 buf := &getg().m.p.ptr().wbBuf
1475 var bits uint32
1476 for i := uintptr(0); i < typ.PtrBytes; i += goarch.PtrSize {
1477 if i&(goarch.PtrSize*8-1) == 0 {
1478 bits = uint32(*ptrmask)
1479 ptrmask = addb(ptrmask, 1)
1480 } else {
1481 bits = bits >> 1
1482 }
1483 if bits&1 != 0 {
1484 dstx := (*uintptr)(unsafe.Pointer(dst + i))
1485 srcx := (*uintptr)(unsafe.Pointer(src + i))
1486 p := buf.get2()
1487 p[0] = *dstx
1488 p[1] = *srcx
1489 }
1490 }
1491 }
1492
1493 // countAlloc returns the number of objects allocated in span s by
1494 // scanning the mark bitmap.
1495 func (s *mspan) countAlloc() int {
1496 count := 0
1497 bytes := divRoundUp(uintptr(s.nelems), 8)
1498 // Iterate over each 8-byte chunk and count allocations
1499 // with an intrinsic. Note that newMarkBits guarantees that
1500 // gcmarkBits will be 8-byte aligned, so we don't have to
1501 // worry about edge cases, irrelevant bits will simply be zero.
1502 for i := uintptr(0); i < bytes; i += 8 {
1503 // Extract 64 bits from the byte pointer and get a OnesCount.
1504 // Note that the unsafe cast here doesn't preserve endianness,
1505 // but that's OK. We only care about how many bits are 1, not
1506 // about the order we discover them in.
1507 mrkBits := *(*uint64)(unsafe.Pointer(s.gcmarkBits.bytep(i)))
1508 count += sys.OnesCount64(mrkBits)
1509 }
1510 return count
1511 }
1512
1513 // Read the bytes starting at the aligned pointer p into a uintptr.
1514 // Read is little-endian.
1515 func readUintptr(p *byte) uintptr {
1516 x := *(*uintptr)(unsafe.Pointer(p))
1517 if goarch.BigEndian {
1518 if goarch.PtrSize == 8 {
1519 return uintptr(sys.Bswap64(uint64(x)))
1520 }
1521 return uintptr(sys.Bswap32(uint32(x)))
1522 }
1523 return x
1524 }
1525
1526 var debugPtrmask struct {
1527 lock mutex
1528 data *byte
1529 }
1530
1531 // progToPointerMask returns the 1-bit pointer mask output by the GC program prog.
1532 // size the size of the region described by prog, in bytes.
1533 // The resulting bitvector will have no more than size/goarch.PtrSize bits.
1534 func progToPointerMask(prog *byte, size uintptr) bitvector {
1535 n := (size/goarch.PtrSize + 7) / 8
1536 x := (*[1 << 30]byte)(persistentalloc(n+1, 1, &memstats.buckhash_sys))[:n+1]
1537 x[len(x)-1] = 0xa1 // overflow check sentinel
1538 n = runGCProg(prog, &x[0])
1539 if x[len(x)-1] != 0xa1 {
1540 throw("progToPointerMask: overflow")
1541 }
1542 return bitvector{int32(n), &x[0]}
1543 }
1544
1545 // Packed GC pointer bitmaps, aka GC programs.
1546 //
1547 // For large types containing arrays, the type information has a
1548 // natural repetition that can be encoded to save space in the
1549 // binary and in the memory representation of the type information.
1550 //
1551 // The encoding is a simple Lempel-Ziv style bytecode machine
1552 // with the following instructions:
1553 //
1554 // 00000000: stop
1555 // 0nnnnnnn: emit n bits copied from the next (n+7)/8 bytes
1556 // 10000000 n c: repeat the previous n bits c times; n, c are varints
1557 // 1nnnnnnn c: repeat the previous n bits c times; c is a varint
1558 //
1559 // Currently, gc programs are only used for describing data and bss
1560 // sections of the binary.
1561
1562 // runGCProg returns the number of 1-bit entries written to memory.
1563 func runGCProg(prog, dst *byte) uintptr {
1564 dstStart := dst
1565
1566 // Bits waiting to be written to memory.
1567 var bits uintptr
1568 var nbits uintptr
1569
1570 p := prog
1571 Run:
1572 for {
1573 // Flush accumulated full bytes.
1574 // The rest of the loop assumes that nbits <= 7.
1575 for ; nbits >= 8; nbits -= 8 {
1576 *dst = uint8(bits)
1577 dst = add1(dst)
1578 bits >>= 8
1579 }
1580
1581 // Process one instruction.
1582 inst := uintptr(*p)
1583 p = add1(p)
1584 n := inst & 0x7F
1585 if inst&0x80 == 0 {
1586 // Literal bits; n == 0 means end of program.
1587 if n == 0 {
1588 // Program is over.
1589 break Run
1590 }
1591 nbyte := n / 8
1592 for i := uintptr(0); i < nbyte; i++ {
1593 bits |= uintptr(*p) << nbits
1594 p = add1(p)
1595 *dst = uint8(bits)
1596 dst = add1(dst)
1597 bits >>= 8
1598 }
1599 if n %= 8; n > 0 {
1600 bits |= uintptr(*p) << nbits
1601 p = add1(p)
1602 nbits += n
1603 }
1604 continue Run
1605 }
1606
1607 // Repeat. If n == 0, it is encoded in a varint in the next bytes.
1608 if n == 0 {
1609 for off := uint(0); ; off += 7 {
1610 x := uintptr(*p)
1611 p = add1(p)
1612 n |= (x & 0x7F) << off
1613 if x&0x80 == 0 {
1614 break
1615 }
1616 }
1617 }
1618
1619 // Count is encoded in a varint in the next bytes.
1620 c := uintptr(0)
1621 for off := uint(0); ; off += 7 {
1622 x := uintptr(*p)
1623 p = add1(p)
1624 c |= (x & 0x7F) << off
1625 if x&0x80 == 0 {
1626 break
1627 }
1628 }
1629 c *= n // now total number of bits to copy
1630
1631 // If the number of bits being repeated is small, load them
1632 // into a register and use that register for the entire loop
1633 // instead of repeatedly reading from memory.
1634 // Handling fewer than 8 bits here makes the general loop simpler.
1635 // The cutoff is goarch.PtrSize*8 - 7 to guarantee that when we add
1636 // the pattern to a bit buffer holding at most 7 bits (a partial byte)
1637 // it will not overflow.
1638 src := dst
1639 const maxBits = goarch.PtrSize*8 - 7
1640 if n <= maxBits {
1641 // Start with bits in output buffer.
1642 pattern := bits
1643 npattern := nbits
1644
1645 // If we need more bits, fetch them from memory.
1646 src = subtract1(src)
1647 for npattern < n {
1648 pattern <<= 8
1649 pattern |= uintptr(*src)
1650 src = subtract1(src)
1651 npattern += 8
1652 }
1653
1654 // We started with the whole bit output buffer,
1655 // and then we loaded bits from whole bytes.
1656 // Either way, we might now have too many instead of too few.
1657 // Discard the extra.
1658 if npattern > n {
1659 pattern >>= npattern - n
1660 npattern = n
1661 }
1662
1663 // Replicate pattern to at most maxBits.
1664 if npattern == 1 {
1665 // One bit being repeated.
1666 // If the bit is 1, make the pattern all 1s.
1667 // If the bit is 0, the pattern is already all 0s,
1668 // but we can claim that the number of bits
1669 // in the word is equal to the number we need (c),
1670 // because right shift of bits will zero fill.
1671 if pattern == 1 {
1672 pattern = 1<<maxBits - 1
1673 npattern = maxBits
1674 } else {
1675 npattern = c
1676 }
1677 } else {
1678 b := pattern
1679 nb := npattern
1680 if nb+nb <= maxBits {
1681 // Double pattern until the whole uintptr is filled.
1682 for nb <= goarch.PtrSize*8 {
1683 b |= b << nb
1684 nb += nb
1685 }
1686 // Trim away incomplete copy of original pattern in high bits.
1687 // TODO(rsc): Replace with table lookup or loop on systems without divide?
1688 nb = maxBits / npattern * npattern
1689 b &= 1<<nb - 1
1690 pattern = b
1691 npattern = nb
1692 }
1693 }
1694
1695 // Add pattern to bit buffer and flush bit buffer, c/npattern times.
1696 // Since pattern contains >8 bits, there will be full bytes to flush
1697 // on each iteration.
1698 for ; c >= npattern; c -= npattern {
1699 bits |= pattern << nbits
1700 nbits += npattern
1701 for nbits >= 8 {
1702 *dst = uint8(bits)
1703 dst = add1(dst)
1704 bits >>= 8
1705 nbits -= 8
1706 }
1707 }
1708
1709 // Add final fragment to bit buffer.
1710 if c > 0 {
1711 pattern &= 1<<c - 1
1712 bits |= pattern << nbits
1713 nbits += c
1714 }
1715 continue Run
1716 }
1717
1718 // Repeat; n too large to fit in a register.
1719 // Since nbits <= 7, we know the first few bytes of repeated data
1720 // are already written to memory.
1721 off := n - nbits // n > nbits because n > maxBits and nbits <= 7
1722 // Leading src fragment.
1723 src = subtractb(src, (off+7)/8)
1724 if frag := off & 7; frag != 0 {
1725 bits |= uintptr(*src) >> (8 - frag) << nbits
1726 src = add1(src)
1727 nbits += frag
1728 c -= frag
1729 }
1730 // Main loop: load one byte, write another.
1731 // The bits are rotating through the bit buffer.
1732 for i := c / 8; i > 0; i-- {
1733 bits |= uintptr(*src) << nbits
1734 src = add1(src)
1735 *dst = uint8(bits)
1736 dst = add1(dst)
1737 bits >>= 8
1738 }
1739 // Final src fragment.
1740 if c %= 8; c > 0 {
1741 bits |= (uintptr(*src) & (1<<c - 1)) << nbits
1742 nbits += c
1743 }
1744 }
1745
1746 // Write any final bits out, using full-byte writes, even for the final byte.
1747 totalBits := (uintptr(unsafe.Pointer(dst))-uintptr(unsafe.Pointer(dstStart)))*8 + nbits
1748 nbits += -nbits & 7
1749 for ; nbits > 0; nbits -= 8 {
1750 *dst = uint8(bits)
1751 dst = add1(dst)
1752 bits >>= 8
1753 }
1754 return totalBits
1755 }
1756
1757 func dumpGCProg(p *byte) {
1758 nptr := 0
1759 for {
1760 x := *p
1761 p = add1(p)
1762 if x == 0 {
1763 print("\t", nptr, " end\n")
1764 break
1765 }
1766 if x&0x80 == 0 {
1767 print("\t", nptr, " lit ", x, ":")
1768 n := int(x+7) / 8
1769 for i := 0; i < n; i++ {
1770 print(" ", hex(*p))
1771 p = add1(p)
1772 }
1773 print("\n")
1774 nptr += int(x)
1775 } else {
1776 nbit := int(x &^ 0x80)
1777 if nbit == 0 {
1778 for nb := uint(0); ; nb += 7 {
1779 x := *p
1780 p = add1(p)
1781 nbit |= int(x&0x7f) << nb
1782 if x&0x80 == 0 {
1783 break
1784 }
1785 }
1786 }
1787 count := 0
1788 for nb := uint(0); ; nb += 7 {
1789 x := *p
1790 p = add1(p)
1791 count |= int(x&0x7f) << nb
1792 if x&0x80 == 0 {
1793 break
1794 }
1795 }
1796 print("\t", nptr, " repeat ", nbit, " × ", count, "\n")
1797 nptr += nbit * count
1798 }
1799 }
1800 }
1801
1802 // Testing.
1803
1804 // reflect_gcbits returns the GC type info for x, for testing.
1805 // The result is the bitmap entries (0 or 1), one entry per byte.
1806 //
1807 //go:linkname reflect_gcbits reflect.gcbits
1808 func reflect_gcbits(x any) []byte {
1809 return pointerMask(x)
1810 }
1811
1812 // Returns GC type info for the pointer stored in ep for testing.
1813 // If ep points to the stack, only static live information will be returned
1814 // (i.e. not for objects which are only dynamically live stack objects).
1815 func pointerMask(ep any) (mask []byte) {
1816 e := *efaceOf(&ep)
1817 p := e.data
1818 t := e._type
1819
1820 var et *_type
1821 if t.Kind() != abi.Pointer {
1822 throw("bad argument to getgcmask: expected type to be a pointer to the value type whose mask is being queried")
1823 }
1824 et = (*ptrtype)(unsafe.Pointer(t)).Elem
1825
1826 // data or bss
1827 for _, datap := range activeModules() {
1828 // data
1829 if datap.data <= uintptr(p) && uintptr(p) < datap.edata {
1830 bitmap := datap.gcdatamask.bytedata
1831 n := et.Size_
1832 mask = make([]byte, n/goarch.PtrSize)
1833 for i := uintptr(0); i < n; i += goarch.PtrSize {
1834 off := (uintptr(p) + i - datap.data) / goarch.PtrSize
1835 mask[i/goarch.PtrSize] = (*addb(bitmap, off/8) >> (off % 8)) & 1
1836 }
1837 return
1838 }
1839
1840 // bss
1841 if datap.bss <= uintptr(p) && uintptr(p) < datap.ebss {
1842 bitmap := datap.gcbssmask.bytedata
1843 n := et.Size_
1844 mask = make([]byte, n/goarch.PtrSize)
1845 for i := uintptr(0); i < n; i += goarch.PtrSize {
1846 off := (uintptr(p) + i - datap.bss) / goarch.PtrSize
1847 mask[i/goarch.PtrSize] = (*addb(bitmap, off/8) >> (off % 8)) & 1
1848 }
1849 return
1850 }
1851 }
1852
1853 // heap
1854 if base, s, _ := findObject(uintptr(p), 0, 0); base != 0 {
1855 if s.spanclass.noscan() {
1856 return nil
1857 }
1858 limit := base + s.elemsize
1859
1860 // Move the base up to the iterator's start, because
1861 // we want to hide evidence of a malloc header from the
1862 // caller.
1863 tp := s.typePointersOfUnchecked(base)
1864 base = tp.addr
1865
1866 // Unroll the full bitmap the GC would actually observe.
1867 maskFromHeap := make([]byte, (limit-base)/goarch.PtrSize)
1868 for {
1869 var addr uintptr
1870 if tp, addr = tp.next(limit); addr == 0 {
1871 break
1872 }
1873 maskFromHeap[(addr-base)/goarch.PtrSize] = 1
1874 }
1875
1876 // Double-check that every part of the ptr/scalar we're not
1877 // showing the caller is zeroed. This keeps us honest that
1878 // that information is actually irrelevant.
1879 for i := limit; i < s.elemsize; i++ {
1880 if *(*byte)(unsafe.Pointer(i)) != 0 {
1881 throw("found non-zeroed tail of allocation")
1882 }
1883 }
1884
1885 // Callers (and a check we're about to run) expects this mask
1886 // to end at the last pointer.
1887 for len(maskFromHeap) > 0 && maskFromHeap[len(maskFromHeap)-1] == 0 {
1888 maskFromHeap = maskFromHeap[:len(maskFromHeap)-1]
1889 }
1890
1891 // Unroll again, but this time from the type information.
1892 maskFromType := make([]byte, (limit-base)/goarch.PtrSize)
1893 tp = s.typePointersOfType(et, base)
1894 for {
1895 var addr uintptr
1896 if tp, addr = tp.next(limit); addr == 0 {
1897 break
1898 }
1899 maskFromType[(addr-base)/goarch.PtrSize] = 1
1900 }
1901
1902 // Validate that the prefix of maskFromType is equal to
1903 // maskFromHeap. maskFromType may contain more pointers than
1904 // maskFromHeap produces because maskFromHeap may be able to
1905 // get exact type information for certain classes of objects.
1906 // With maskFromType, we're always just tiling the type bitmap
1907 // through to the elemsize.
1908 //
1909 // It's OK if maskFromType has pointers in elemsize that extend
1910 // past the actual populated space; we checked above that all
1911 // that space is zeroed, so just the GC will just see nil pointers.
1912 differs := false
1913 for i := range maskFromHeap {
1914 if maskFromHeap[i] != maskFromType[i] {
1915 differs = true
1916 break
1917 }
1918 }
1919
1920 if differs {
1921 print("runtime: heap mask=")
1922 for _, b := range maskFromHeap {
1923 print(b)
1924 }
1925 println()
1926 print("runtime: type mask=")
1927 for _, b := range maskFromType {
1928 print(b)
1929 }
1930 println()
1931 print("runtime: type=", toRType(et).string(), "\n")
1932 throw("found two different masks from two different methods")
1933 }
1934
1935 // Select the heap mask to return. We may not have a type mask.
1936 mask = maskFromHeap
1937
1938 // Make sure we keep ep alive. We may have stopped referencing
1939 // ep's data pointer sometime before this point and it's possible
1940 // for that memory to get freed.
1941 KeepAlive(ep)
1942 return
1943 }
1944
1945 // stack
1946 if gp := getg(); gp.m.curg.stack.lo <= uintptr(p) && uintptr(p) < gp.m.curg.stack.hi {
1947 found := false
1948 var u unwinder
1949 for u.initAt(gp.m.curg.sched.pc, gp.m.curg.sched.sp, 0, gp.m.curg, 0); u.valid(); u.next() {
1950 if u.frame.sp <= uintptr(p) && uintptr(p) < u.frame.varp {
1951 found = true
1952 break
1953 }
1954 }
1955 if found {
1956 locals, _, _ := u.frame.getStackMap(false)
1957 if locals.n == 0 {
1958 return
1959 }
1960 size := uintptr(locals.n) * goarch.PtrSize
1961 n := (*ptrtype)(unsafe.Pointer(t)).Elem.Size_
1962 mask = make([]byte, n/goarch.PtrSize)
1963 for i := uintptr(0); i < n; i += goarch.PtrSize {
1964 off := (uintptr(p) + i - u.frame.varp + size) / goarch.PtrSize
1965 mask[i/goarch.PtrSize] = locals.ptrbit(off)
1966 }
1967 }
1968 return
1969 }
1970
1971 // otherwise, not something the GC knows about.
1972 // possibly read-only data, like malloc(0).
1973 // must not have pointers
1974 return
1975 }