Source file src/runtime/mbitmap.go

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

View as plain text