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

View as plain text