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

View as plain text