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

View as plain text