Source file src/runtime/export_test.go

     1  // Copyright 2010 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  // Export guts for testing.
     6  
     7  package runtime
     8  
     9  import (
    10  	"internal/abi"
    11  	"internal/goarch"
    12  	"internal/goos"
    13  	"internal/runtime/atomic"
    14  	"internal/runtime/gc"
    15  	"internal/runtime/maps"
    16  	"internal/runtime/sys"
    17  	"unsafe"
    18  )
    19  
    20  var Fadd64 = fadd64
    21  var Fsub64 = fsub64
    22  var Fmul64 = fmul64
    23  var Fdiv64 = fdiv64
    24  var F64to32 = f64to32
    25  var F32to64 = f32to64
    26  var Fcmp64 = fcmp64
    27  var Fintto64 = fintto64
    28  var F64toint = f64toint
    29  
    30  var Entersyscall = entersyscall
    31  var Exitsyscall = exitsyscall
    32  var LockedOSThread = lockedOSThread
    33  var Xadduintptr = atomic.Xadduintptr
    34  
    35  var ReadRandomFailed = &readRandomFailed
    36  
    37  var Fastlog2 = fastlog2
    38  
    39  var ParseByteCount = parseByteCount
    40  
    41  var Nanotime = nanotime
    42  var Cputicks = cputicks
    43  var CyclesPerSecond = pprof_cyclesPerSecond
    44  var NetpollBreak = netpollBreak
    45  var Usleep = usleep
    46  
    47  var PhysPageSize = physPageSize
    48  var PhysHugePageSize = physHugePageSize
    49  
    50  var NetpollGenericInit = netpollGenericInit
    51  
    52  var Memmove = memmove
    53  var MemclrNoHeapPointers = memclrNoHeapPointers
    54  
    55  var CgoCheckPointer = cgoCheckPointer
    56  
    57  const CrashStackImplemented = crashStackImplemented
    58  
    59  const TracebackInnerFrames = tracebackInnerFrames
    60  const TracebackOuterFrames = tracebackOuterFrames
    61  
    62  var LockPartialOrder = lockPartialOrder
    63  
    64  type TimeTimer = timeTimer
    65  
    66  type LockRank lockRank
    67  
    68  func (l LockRank) String() string {
    69  	return lockRank(l).String()
    70  }
    71  
    72  const PreemptMSupported = preemptMSupported
    73  
    74  type LFNode struct {
    75  	Next    uint64
    76  	Pushcnt uintptr
    77  }
    78  
    79  func LFStackPush(head *uint64, node *LFNode) {
    80  	(*lfstack)(head).push((*lfnode)(unsafe.Pointer(node)))
    81  }
    82  
    83  func LFStackPop(head *uint64) *LFNode {
    84  	return (*LFNode)((*lfstack)(head).pop())
    85  }
    86  func LFNodeValidate(node *LFNode) {
    87  	lfnodeValidate((*lfnode)(unsafe.Pointer(node)))
    88  }
    89  
    90  func Netpoll(delta int64) {
    91  	systemstack(func() {
    92  		netpoll(delta)
    93  	})
    94  }
    95  
    96  func PointerMask(x any) (ret []byte) {
    97  	systemstack(func() {
    98  		ret = pointerMask(x)
    99  	})
   100  	return
   101  }
   102  
   103  func RunSchedLocalQueueTest() {
   104  	pp := new(p)
   105  	gs := make([]g, len(pp.runq))
   106  	Escape(gs) // Ensure gs doesn't move, since we use guintptrs
   107  	for i := 0; i < len(pp.runq); i++ {
   108  		if g, _ := runqget(pp); g != nil {
   109  			throw("runq is not empty initially")
   110  		}
   111  		for j := 0; j < i; j++ {
   112  			runqput(pp, &gs[i], false)
   113  		}
   114  		for j := 0; j < i; j++ {
   115  			if g, _ := runqget(pp); g != &gs[i] {
   116  				print("bad element at iter ", i, "/", j, "\n")
   117  				throw("bad element")
   118  			}
   119  		}
   120  		if g, _ := runqget(pp); g != nil {
   121  			throw("runq is not empty afterwards")
   122  		}
   123  	}
   124  }
   125  
   126  func RunSchedLocalQueueStealTest() {
   127  	p1 := new(p)
   128  	p2 := new(p)
   129  	gs := make([]g, len(p1.runq))
   130  	Escape(gs) // Ensure gs doesn't move, since we use guintptrs
   131  	for i := 0; i < len(p1.runq); i++ {
   132  		for j := 0; j < i; j++ {
   133  			gs[j].sig = 0
   134  			runqput(p1, &gs[j], false)
   135  		}
   136  		gp := runqsteal(p2, p1, true)
   137  		s := 0
   138  		if gp != nil {
   139  			s++
   140  			gp.sig++
   141  		}
   142  		for {
   143  			gp, _ = runqget(p2)
   144  			if gp == nil {
   145  				break
   146  			}
   147  			s++
   148  			gp.sig++
   149  		}
   150  		for {
   151  			gp, _ = runqget(p1)
   152  			if gp == nil {
   153  				break
   154  			}
   155  			gp.sig++
   156  		}
   157  		for j := 0; j < i; j++ {
   158  			if gs[j].sig != 1 {
   159  				print("bad element ", j, "(", gs[j].sig, ") at iter ", i, "\n")
   160  				throw("bad element")
   161  			}
   162  		}
   163  		if s != i/2 && s != i/2+1 {
   164  			print("bad steal ", s, ", want ", i/2, " or ", i/2+1, ", iter ", i, "\n")
   165  			throw("bad steal")
   166  		}
   167  	}
   168  }
   169  
   170  func RunSchedLocalQueueEmptyTest(iters int) {
   171  	// Test that runq is not spuriously reported as empty.
   172  	// Runq emptiness affects scheduling decisions and spurious emptiness
   173  	// can lead to underutilization (both runnable Gs and idle Ps coexist
   174  	// for arbitrary long time).
   175  	done := make(chan bool, 1)
   176  	p := new(p)
   177  	gs := make([]g, 2)
   178  	Escape(gs) // Ensure gs doesn't move, since we use guintptrs
   179  	ready := new(uint32)
   180  	for i := 0; i < iters; i++ {
   181  		*ready = 0
   182  		next0 := (i & 1) == 0
   183  		next1 := (i & 2) == 0
   184  		runqput(p, &gs[0], next0)
   185  		go func() {
   186  			for atomic.Xadd(ready, 1); atomic.Load(ready) != 2; {
   187  			}
   188  			if runqempty(p) {
   189  				println("next:", next0, next1)
   190  				throw("queue is empty")
   191  			}
   192  			done <- true
   193  		}()
   194  		for atomic.Xadd(ready, 1); atomic.Load(ready) != 2; {
   195  		}
   196  		runqput(p, &gs[1], next1)
   197  		runqget(p)
   198  		<-done
   199  		runqget(p)
   200  	}
   201  }
   202  
   203  var (
   204  	StringHash = stringHash
   205  	BytesHash  = bytesHash
   206  	Int32Hash  = int32Hash
   207  	Int64Hash  = int64Hash
   208  	MemHash    = memhash
   209  	MemHash32  = memhash32
   210  	MemHash64  = memhash64
   211  	EfaceHash  = efaceHash
   212  	IfaceHash  = ifaceHash
   213  )
   214  
   215  var MinAeshashSize = &maps.MinAeshashSize
   216  
   217  var AeshashEnabled = maps.AeshashEnabled
   218  
   219  func MemclrBytes(b []byte) {
   220  	s := (*slice)(unsafe.Pointer(&b))
   221  	memclrNoHeapPointers(s.array, uintptr(s.len))
   222  }
   223  
   224  const HashLoad = hashLoad
   225  
   226  // entry point for testing
   227  func GostringW(w []uint16) (s string) {
   228  	systemstack(func() {
   229  		s = gostringw(&w[0])
   230  	})
   231  	return
   232  }
   233  
   234  var Open = open
   235  var Close = closefd
   236  var Read = read
   237  var Write = write
   238  
   239  func Envs() []string     { return envs }
   240  func SetEnvs(e []string) { envs = e }
   241  
   242  const PtrSize = goarch.PtrSize
   243  
   244  const ClobberdeadPtr = clobberdeadPtr
   245  
   246  func Clobberfree() bool {
   247  	return debug.clobberfree != 0
   248  }
   249  
   250  var ForceGCPeriod = &forcegcperiod
   251  
   252  // SetTracebackEnv is like runtime/debug.SetTraceback, but it raises
   253  // the "environment" traceback level, so later calls to
   254  // debug.SetTraceback (e.g., from testing timeouts) can't lower it.
   255  func SetTracebackEnv(level string) {
   256  	setTraceback(level)
   257  	traceback_env = traceback_cache
   258  }
   259  
   260  var ReadUnaligned64 = readUnaligned64
   261  
   262  func CountPagesInUse() (pagesInUse, counted uintptr) {
   263  	stw := stopTheWorld(stwForTestCountPagesInUse)
   264  
   265  	pagesInUse = mheap_.pagesInUse.Load()
   266  
   267  	for _, s := range mheap_.allspans {
   268  		if s.state.get() == mSpanInUse {
   269  			counted += s.npages
   270  		}
   271  	}
   272  
   273  	startTheWorld(stw)
   274  
   275  	return
   276  }
   277  
   278  func Blocksampled(cycles, rate int64) bool { return blocksampled(cycles, rate) }
   279  
   280  func Cheaprand() uint32         { return cheaprand() }
   281  func Cheaprand64() int64        { return cheaprand64() }
   282  func Fastrand() uint32          { return uint32(rand()) }
   283  func Fastrand64() uint64        { return rand() }
   284  func Fastrandn(n uint32) uint32 { return randn(n) }
   285  
   286  type ProfBuf profBuf
   287  
   288  func NewProfBuf(hdrsize, bufwords, tags int) *ProfBuf {
   289  	return (*ProfBuf)(newProfBuf(hdrsize, bufwords, tags))
   290  }
   291  
   292  func (p *ProfBuf) Write(tag *unsafe.Pointer, now int64, hdr []uint64, stk []uintptr) {
   293  	(*profBuf)(p).write(tag, now, hdr, stk)
   294  }
   295  
   296  const (
   297  	ProfBufBlocking    = profBufBlocking
   298  	ProfBufNonBlocking = profBufNonBlocking
   299  )
   300  
   301  func (p *ProfBuf) Read(mode profBufReadMode) ([]uint64, []unsafe.Pointer, bool) {
   302  	return (*profBuf)(p).read(mode)
   303  }
   304  
   305  func (p *ProfBuf) Close() {
   306  	(*profBuf)(p).close()
   307  }
   308  
   309  type CPUStats = cpuStats
   310  
   311  func ReadCPUStats() CPUStats {
   312  	return work.cpuStats
   313  }
   314  
   315  func ReadMetricsSlow(memStats *MemStats, samplesp unsafe.Pointer, len, cap int) {
   316  	stw := stopTheWorld(stwForTestReadMetricsSlow)
   317  
   318  	// Initialize the metrics beforehand because this could
   319  	// allocate and skew the stats.
   320  	metricsLock()
   321  	initMetrics()
   322  
   323  	systemstack(func() {
   324  		// Donate the racectx to g0. readMetricsLocked calls into the race detector
   325  		// via map access.
   326  		getg().racectx = getg().m.curg.racectx
   327  
   328  		// Read the metrics once before in case it allocates and skews the metrics.
   329  		// readMetricsLocked is designed to only allocate the first time it is called
   330  		// with a given slice of samples. In effect, this extra read tests that this
   331  		// remains true, since otherwise the second readMetricsLocked below could
   332  		// allocate before it returns.
   333  		readMetricsLocked(samplesp, len, cap)
   334  
   335  		// Read memstats first. It's going to flush
   336  		// the mcaches which readMetrics does not do, so
   337  		// going the other way around may result in
   338  		// inconsistent statistics.
   339  		readmemstats_m(memStats)
   340  
   341  		// Read metrics again. We need to be sure we're on the
   342  		// system stack with readmemstats_m so that we don't call into
   343  		// the stack allocator and adjust metrics between there and here.
   344  		readMetricsLocked(samplesp, len, cap)
   345  
   346  		// Undo the donation.
   347  		getg().racectx = 0
   348  	})
   349  	metricsUnlock()
   350  
   351  	startTheWorld(stw)
   352  }
   353  
   354  var DoubleCheckReadMemStats = &doubleCheckReadMemStats
   355  
   356  // ReadMemStatsSlow returns both the runtime-computed MemStats and
   357  // MemStats accumulated by scanning the heap.
   358  func ReadMemStatsSlow() (base, slow MemStats) {
   359  	stw := stopTheWorld(stwForTestReadMemStatsSlow)
   360  
   361  	// Run on the system stack to avoid stack growth allocation.
   362  	systemstack(func() {
   363  		// Make sure stats don't change.
   364  		getg().m.mallocing++
   365  
   366  		readmemstats_m(&base)
   367  
   368  		// Initialize slow from base and zero the fields we're
   369  		// recomputing.
   370  		slow = base
   371  		slow.Alloc = 0
   372  		slow.TotalAlloc = 0
   373  		slow.Mallocs = 0
   374  		slow.Frees = 0
   375  		slow.HeapReleased = 0
   376  		var bySize [gc.NumSizeClasses]struct {
   377  			Mallocs, Frees uint64
   378  		}
   379  
   380  		// Add up current allocations in spans.
   381  		for _, s := range mheap_.allspans {
   382  			if s.state.get() != mSpanInUse {
   383  				continue
   384  			}
   385  			if s.isUnusedUserArenaChunk() {
   386  				continue
   387  			}
   388  			if sizeclass := s.spanclass.sizeclass(); sizeclass == 0 {
   389  				slow.Mallocs++
   390  				slow.Alloc += uint64(s.elemsize)
   391  			} else {
   392  				slow.Mallocs += uint64(s.allocCount)
   393  				slow.Alloc += uint64(s.allocCount) * uint64(s.elemsize)
   394  				bySize[sizeclass].Mallocs += uint64(s.allocCount)
   395  			}
   396  		}
   397  
   398  		// Add in frees by just reading the stats for those directly.
   399  		var m heapStatsDelta
   400  		memstats.heapStats.unsafeRead(&m)
   401  
   402  		// Collect per-sizeclass free stats.
   403  		var smallFree uint64
   404  		for i := 0; i < gc.NumSizeClasses; i++ {
   405  			slow.Frees += m.smallFreeCount[i]
   406  			bySize[i].Frees += m.smallFreeCount[i]
   407  			bySize[i].Mallocs += m.smallFreeCount[i]
   408  			smallFree += m.smallFreeCount[i] * uint64(gc.SizeClassToSize[i])
   409  		}
   410  		slow.Frees += m.tinyAllocCount + m.largeFreeCount
   411  		slow.Mallocs += slow.Frees
   412  
   413  		slow.TotalAlloc = slow.Alloc + m.largeFree + smallFree
   414  
   415  		for i := range slow.BySize {
   416  			slow.BySize[i].Mallocs = bySize[i].Mallocs
   417  			slow.BySize[i].Frees = bySize[i].Frees
   418  		}
   419  
   420  		for i := mheap_.pages.start; i < mheap_.pages.end; i++ {
   421  			chunk := mheap_.pages.tryChunkOf(i)
   422  			if chunk == nil {
   423  				continue
   424  			}
   425  			pg := chunk.scavenged.popcntRange(0, pallocChunkPages)
   426  			slow.HeapReleased += uint64(pg) * pageSize
   427  		}
   428  		for _, p := range allp {
   429  			// Only count scav bits for pages in the cache
   430  			pg := sys.OnesCount64(p.pcache.cache & p.pcache.scav)
   431  			slow.HeapReleased += uint64(pg) * pageSize
   432  		}
   433  
   434  		getg().m.mallocing--
   435  	})
   436  
   437  	startTheWorld(stw)
   438  	return
   439  }
   440  
   441  // ShrinkStackAndVerifyFramePointers attempts to shrink the stack of the current goroutine
   442  // and verifies that unwinding the new stack doesn't crash, even if the old
   443  // stack has been freed or reused (simulated via poisoning).
   444  func ShrinkStackAndVerifyFramePointers() {
   445  	before := stackPoisonCopy
   446  	defer func() { stackPoisonCopy = before }()
   447  	stackPoisonCopy = 1
   448  
   449  	gp := getg()
   450  	systemstack(func() {
   451  		shrinkstack(gp)
   452  	})
   453  	// If our new stack contains frame pointers into the old stack, this will
   454  	// crash because the old stack has been poisoned.
   455  	FPCallers(make([]uintptr, 1024))
   456  }
   457  
   458  type StackPoisonCopyRestore int
   459  
   460  func (s StackPoisonCopyRestore) Restore() { stackPoisonCopy = int(s) }
   461  
   462  func StackPoisonCopy() StackPoisonCopyRestore {
   463  	before := stackPoisonCopy
   464  	stackPoisonCopy = 1
   465  	return StackPoisonCopyRestore(before)
   466  }
   467  
   468  // BlockOnSystemStack switches to the system stack, prints "x\n" to
   469  // stderr, and blocks in a stack containing
   470  // "runtime.blockOnSystemStackInternal".
   471  func BlockOnSystemStack() {
   472  	systemstack(blockOnSystemStackInternal)
   473  }
   474  
   475  func blockOnSystemStackInternal() {
   476  	print("x\n")
   477  	lock(&deadlock)
   478  	lock(&deadlock)
   479  }
   480  
   481  type RWMutex struct {
   482  	rw rwmutex
   483  }
   484  
   485  func (rw *RWMutex) Init() {
   486  	rw.rw.init(lockRankTestR, lockRankTestRInternal, lockRankTestW)
   487  }
   488  
   489  func (rw *RWMutex) RLock() {
   490  	rw.rw.rlock()
   491  }
   492  
   493  func (rw *RWMutex) RUnlock() {
   494  	rw.rw.runlock()
   495  }
   496  
   497  func (rw *RWMutex) Lock() {
   498  	rw.rw.lock()
   499  }
   500  
   501  func (rw *RWMutex) Unlock() {
   502  	rw.rw.unlock()
   503  }
   504  
   505  func LockOSCounts() (external, internal uint32) {
   506  	gp := getg()
   507  	if gp.m.lockedExt+gp.m.lockedInt == 0 {
   508  		if gp.lockedm != 0 {
   509  			panic("lockedm on non-locked goroutine")
   510  		}
   511  	} else {
   512  		if gp.lockedm == 0 {
   513  			panic("nil lockedm on locked goroutine")
   514  		}
   515  	}
   516  	return gp.m.lockedExt, gp.m.lockedInt
   517  }
   518  
   519  //go:noinline
   520  func TracebackSystemstack(stk []uintptr, i int) int {
   521  	if i == 0 {
   522  		pc, sp := sys.GetCallerPC(), sys.GetCallerSP()
   523  		var u unwinder
   524  		u.initAt(pc, sp, 0, getg(), unwindJumpStack) // Don't ignore errors, for testing
   525  		return tracebackPCs(&u, 0, stk)
   526  	}
   527  	n := 0
   528  	systemstack(func() {
   529  		n = TracebackSystemstack(stk, i-1)
   530  	})
   531  	return n
   532  }
   533  
   534  func KeepNArenaHints(n int) {
   535  	hint := mheap_.arenaHints
   536  	for i := 1; i < n; i++ {
   537  		hint = hint.next
   538  		if hint == nil {
   539  			return
   540  		}
   541  	}
   542  	hint.next = nil
   543  }
   544  
   545  // MapNextArenaHint reserves a page at the next arena growth hint,
   546  // preventing the arena from growing there, and returns the range of
   547  // addresses that are no longer viable.
   548  //
   549  // This may fail to reserve memory. If it fails, it still returns the
   550  // address range it attempted to reserve.
   551  func MapNextArenaHint() (start, end uintptr, ok bool) {
   552  	hint := mheap_.arenaHints
   553  	addr := hint.addr
   554  	if hint.down {
   555  		start, end = addr-heapArenaBytes, addr
   556  		addr -= physPageSize
   557  	} else {
   558  		start, end = addr, addr+heapArenaBytes
   559  	}
   560  	got := sysReserve(unsafe.Pointer(addr), physPageSize, "")
   561  	ok = (addr == uintptr(got))
   562  	if !ok {
   563  		// We were unable to get the requested reservation.
   564  		// Release what we did get and fail.
   565  		sysUnreserve(got, physPageSize)
   566  	}
   567  	return
   568  }
   569  
   570  func NextArenaHint() (uintptr, bool) {
   571  	if mheap_.arenaHints == nil {
   572  		return 0, false
   573  	}
   574  	return mheap_.arenaHints.addr, true
   575  }
   576  
   577  type G = g
   578  
   579  type Sudog = sudog
   580  
   581  type XRegPerG = xRegPerG
   582  
   583  func Getg() *G {
   584  	return getg()
   585  }
   586  
   587  func Goid() uint64 {
   588  	return getg().goid
   589  }
   590  
   591  func GIsWaitingOnMutex(gp *G) bool {
   592  	return readgstatus(gp) == _Gwaiting && gp.waitreason.isMutexWait()
   593  }
   594  
   595  var CasGStatusAlwaysTrack = &casgstatusAlwaysTrack
   596  
   597  //go:noinline
   598  func PanicForTesting(b []byte, i int) byte {
   599  	return unexportedPanicForTesting(b, i)
   600  }
   601  
   602  //go:noinline
   603  func unexportedPanicForTesting(b []byte, i int) byte {
   604  	return b[i]
   605  }
   606  
   607  func G0StackOverflow() {
   608  	systemstack(func() {
   609  		g0 := getg()
   610  		sp := sys.GetCallerSP()
   611  		// The stack bounds for g0 stack is not always precise.
   612  		// Use an artificially small stack, to trigger a stack overflow
   613  		// without actually run out of the system stack (which may seg fault).
   614  		g0.stack.lo = sp - 4096 - stackSystem
   615  		g0.stackguard0 = g0.stack.lo + stackGuard
   616  		g0.stackguard1 = g0.stackguard0
   617  
   618  		stackOverflow(nil)
   619  	})
   620  }
   621  
   622  func stackOverflow(x *byte) {
   623  	var buf [256]byte
   624  	stackOverflow(&buf[0])
   625  }
   626  
   627  func RunGetgThreadSwitchTest() {
   628  	// Test that getg works correctly with thread switch.
   629  	// With gccgo, if we generate getg inlined, the backend
   630  	// may cache the address of the TLS variable, which
   631  	// will become invalid after a thread switch. This test
   632  	// checks that the bad caching doesn't happen.
   633  
   634  	ch := make(chan int)
   635  	go func(ch chan int) {
   636  		ch <- 5
   637  		LockOSThread()
   638  	}(ch)
   639  
   640  	g1 := getg()
   641  
   642  	// Block on a receive. This is likely to get us a thread
   643  	// switch. If we yield to the sender goroutine, it will
   644  	// lock the thread, forcing us to resume on a different
   645  	// thread.
   646  	<-ch
   647  
   648  	g2 := getg()
   649  	if g1 != g2 {
   650  		panic("g1 != g2")
   651  	}
   652  
   653  	// Also test getg after some control flow, as the
   654  	// backend is sensitive to control flow.
   655  	g3 := getg()
   656  	if g1 != g3 {
   657  		panic("g1 != g3")
   658  	}
   659  }
   660  
   661  // Expose freegc for testing.
   662  func Freegc(p unsafe.Pointer, size uintptr, noscan bool) {
   663  	freegc(p, size, noscan)
   664  }
   665  
   666  // Expose gcAssistBytes for the current g for testing.
   667  func AssistCredit() int64 {
   668  	assistG := getg()
   669  	if assistG.m.curg != nil {
   670  		assistG = assistG.m.curg
   671  	}
   672  	return assistG.gcAssistBytes
   673  }
   674  
   675  // Expose gcBlackenEnabled for testing.
   676  func GcBlackenEnable() bool {
   677  	// Note we do a non-atomic load here.
   678  	// Some checks against gcBlackenEnabled (e.g., in mallocgc)
   679  	// are currently done via non-atomic load for performance reasons,
   680  	// but other checks are done via atomic load (e.g., in mgcmark.go),
   681  	// so interpreting this value in a test may be subtle.
   682  	return gcBlackenEnabled != 0
   683  }
   684  
   685  const SizeSpecializedMallocEnabled = sizeSpecializedMallocEnabled
   686  
   687  const RuntimeFreegcEnabled = runtimeFreegcEnabled
   688  
   689  const (
   690  	PageSize         = pageSize
   691  	PallocChunkPages = pallocChunkPages
   692  	PageAlloc64Bit   = pageAlloc64Bit
   693  	PallocSumBytes   = pallocSumBytes
   694  )
   695  
   696  // Expose pallocSum for testing.
   697  type PallocSum pallocSum
   698  
   699  func PackPallocSum(start, max, end uint) PallocSum { return PallocSum(packPallocSum(start, max, end)) }
   700  func (m PallocSum) Start() uint                    { return pallocSum(m).start() }
   701  func (m PallocSum) Max() uint                      { return pallocSum(m).max() }
   702  func (m PallocSum) End() uint                      { return pallocSum(m).end() }
   703  
   704  // Expose pallocBits for testing.
   705  type PallocBits pallocBits
   706  
   707  func (b *PallocBits) Find(npages uintptr, searchIdx uint) (uint, uint) {
   708  	return (*pallocBits)(b).find(npages, searchIdx)
   709  }
   710  func (b *PallocBits) AllocRange(i, n uint)       { (*pallocBits)(b).allocRange(i, n) }
   711  func (b *PallocBits) Free(i, n uint)             { (*pallocBits)(b).free(i, n) }
   712  func (b *PallocBits) Summarize() PallocSum       { return PallocSum((*pallocBits)(b).summarize()) }
   713  func (b *PallocBits) PopcntRange(i, n uint) uint { return (*pageBits)(b).popcntRange(i, n) }
   714  
   715  // SummarizeSlow is a slow but more obviously correct implementation
   716  // of (*pallocBits).summarize. Used for testing.
   717  func SummarizeSlow(b *PallocBits) PallocSum {
   718  	var start, most, end uint
   719  
   720  	const N = uint(len(b)) * 64
   721  	for start < N && (*pageBits)(b).get(start) == 0 {
   722  		start++
   723  	}
   724  	for end < N && (*pageBits)(b).get(N-end-1) == 0 {
   725  		end++
   726  	}
   727  	run := uint(0)
   728  	for i := uint(0); i < N; i++ {
   729  		if (*pageBits)(b).get(i) == 0 {
   730  			run++
   731  		} else {
   732  			run = 0
   733  		}
   734  		most = max(most, run)
   735  	}
   736  	return PackPallocSum(start, most, end)
   737  }
   738  
   739  // Expose non-trivial helpers for testing.
   740  func FindBitRange64(c uint64, n uint) uint { return findBitRange64(c, n) }
   741  
   742  // Given two PallocBits, returns a set of bit ranges where
   743  // they differ.
   744  func DiffPallocBits(a, b *PallocBits) []BitRange {
   745  	ba := (*pageBits)(a)
   746  	bb := (*pageBits)(b)
   747  
   748  	var d []BitRange
   749  	base, size := uint(0), uint(0)
   750  	for i := uint(0); i < uint(len(ba))*64; i++ {
   751  		if ba.get(i) != bb.get(i) {
   752  			if size == 0 {
   753  				base = i
   754  			}
   755  			size++
   756  		} else {
   757  			if size != 0 {
   758  				d = append(d, BitRange{base, size})
   759  			}
   760  			size = 0
   761  		}
   762  	}
   763  	if size != 0 {
   764  		d = append(d, BitRange{base, size})
   765  	}
   766  	return d
   767  }
   768  
   769  // StringifyPallocBits gets the bits in the bit range r from b,
   770  // and returns a string containing the bits as ASCII 0 and 1
   771  // characters.
   772  func StringifyPallocBits(b *PallocBits, r BitRange) string {
   773  	str := ""
   774  	for j := r.I; j < r.I+r.N; j++ {
   775  		if (*pageBits)(b).get(j) != 0 {
   776  			str += "1"
   777  		} else {
   778  			str += "0"
   779  		}
   780  	}
   781  	return str
   782  }
   783  
   784  // Expose pallocData for testing.
   785  type PallocData pallocData
   786  
   787  func (d *PallocData) FindScavengeCandidate(searchIdx uint, min, max uintptr) (uint, uint) {
   788  	return (*pallocData)(d).findScavengeCandidate(searchIdx, min, max)
   789  }
   790  func (d *PallocData) AllocRange(i, n uint) { (*pallocData)(d).allocRange(i, n) }
   791  func (d *PallocData) ScavengedSetRange(i, n uint) {
   792  	(*pallocData)(d).scavenged.setRange(i, n)
   793  }
   794  func (d *PallocData) PallocBits() *PallocBits {
   795  	return (*PallocBits)(&(*pallocData)(d).pallocBits)
   796  }
   797  func (d *PallocData) Scavenged() *PallocBits {
   798  	return (*PallocBits)(&(*pallocData)(d).scavenged)
   799  }
   800  
   801  // Expose fillAligned for testing.
   802  func FillAligned(x uint64, m uint) uint64 { return fillAligned(x, m) }
   803  
   804  // Expose pageCache for testing.
   805  type PageCache pageCache
   806  
   807  const PageCachePages = pageCachePages
   808  
   809  func NewPageCache(base uintptr, cache, scav uint64) PageCache {
   810  	return PageCache(pageCache{base: base, cache: cache, scav: scav})
   811  }
   812  func (c *PageCache) Empty() bool   { return (*pageCache)(c).empty() }
   813  func (c *PageCache) Base() uintptr { return (*pageCache)(c).base }
   814  func (c *PageCache) Cache() uint64 { return (*pageCache)(c).cache }
   815  func (c *PageCache) Scav() uint64  { return (*pageCache)(c).scav }
   816  func (c *PageCache) Alloc(npages uintptr) (uintptr, uintptr) {
   817  	return (*pageCache)(c).alloc(npages)
   818  }
   819  func (c *PageCache) Flush(s *PageAlloc) {
   820  	cp := (*pageCache)(c)
   821  	sp := (*pageAlloc)(s)
   822  
   823  	systemstack(func() {
   824  		// None of the tests need any higher-level locking, so we just
   825  		// take the lock internally.
   826  		lock(sp.mheapLock)
   827  		cp.flush(sp)
   828  		unlock(sp.mheapLock)
   829  	})
   830  }
   831  
   832  // Expose chunk index type.
   833  type ChunkIdx chunkIdx
   834  
   835  // Expose pageAlloc for testing. Note that because pageAlloc is
   836  // not in the heap, so is PageAlloc.
   837  type PageAlloc pageAlloc
   838  
   839  func (p *PageAlloc) Alloc(npages uintptr) (uintptr, uintptr) {
   840  	pp := (*pageAlloc)(p)
   841  
   842  	var addr, scav uintptr
   843  	systemstack(func() {
   844  		// None of the tests need any higher-level locking, so we just
   845  		// take the lock internally.
   846  		lock(pp.mheapLock)
   847  		addr, scav = pp.alloc(npages)
   848  		unlock(pp.mheapLock)
   849  	})
   850  	return addr, scav
   851  }
   852  func (p *PageAlloc) AllocToCache() PageCache {
   853  	pp := (*pageAlloc)(p)
   854  
   855  	var c PageCache
   856  	systemstack(func() {
   857  		// None of the tests need any higher-level locking, so we just
   858  		// take the lock internally.
   859  		lock(pp.mheapLock)
   860  		c = PageCache(pp.allocToCache())
   861  		unlock(pp.mheapLock)
   862  	})
   863  	return c
   864  }
   865  func (p *PageAlloc) Free(base, npages uintptr) {
   866  	pp := (*pageAlloc)(p)
   867  
   868  	systemstack(func() {
   869  		// None of the tests need any higher-level locking, so we just
   870  		// take the lock internally.
   871  		lock(pp.mheapLock)
   872  		pp.free(base, npages)
   873  		unlock(pp.mheapLock)
   874  	})
   875  }
   876  func (p *PageAlloc) Bounds() (ChunkIdx, ChunkIdx) {
   877  	return ChunkIdx((*pageAlloc)(p).start), ChunkIdx((*pageAlloc)(p).end)
   878  }
   879  func (p *PageAlloc) Scavenge(nbytes uintptr) (r uintptr) {
   880  	pp := (*pageAlloc)(p)
   881  	systemstack(func() {
   882  		r = pp.scavenge(nbytes, nil, true)
   883  	})
   884  	return
   885  }
   886  func (p *PageAlloc) InUse() []AddrRange {
   887  	ranges := make([]AddrRange, 0, len(p.inUse.ranges))
   888  	for _, r := range p.inUse.ranges {
   889  		ranges = append(ranges, AddrRange{r})
   890  	}
   891  	return ranges
   892  }
   893  
   894  // Returns nil if the PallocData's L2 is missing.
   895  func (p *PageAlloc) PallocData(i ChunkIdx) *PallocData {
   896  	ci := chunkIdx(i)
   897  	return (*PallocData)((*pageAlloc)(p).tryChunkOf(ci))
   898  }
   899  
   900  // AddrRange is a wrapper around addrRange for testing.
   901  type AddrRange struct {
   902  	addrRange
   903  }
   904  
   905  // MakeAddrRange creates a new address range.
   906  func MakeAddrRange(base, limit uintptr) AddrRange {
   907  	return AddrRange{makeAddrRange(base, limit)}
   908  }
   909  
   910  // Base returns the virtual base address of the address range.
   911  func (a AddrRange) Base() uintptr {
   912  	return a.addrRange.base.addr()
   913  }
   914  
   915  // Base returns the virtual address of the limit of the address range.
   916  func (a AddrRange) Limit() uintptr {
   917  	return a.addrRange.limit.addr()
   918  }
   919  
   920  // Equals returns true if the two address ranges are exactly equal.
   921  func (a AddrRange) Equals(b AddrRange) bool {
   922  	return a == b
   923  }
   924  
   925  // Size returns the size in bytes of the address range.
   926  func (a AddrRange) Size() uintptr {
   927  	return a.addrRange.size()
   928  }
   929  
   930  // testSysStat is the sysStat passed to test versions of various
   931  // runtime structures. We do actually have to keep track of this
   932  // because otherwise memstats.mappedReady won't actually line up
   933  // with other stats in the runtime during tests.
   934  var testSysStat = &memstats.other_sys
   935  
   936  // AddrRanges is a wrapper around addrRanges for testing.
   937  type AddrRanges struct {
   938  	addrRanges
   939  	mutable bool
   940  }
   941  
   942  // NewAddrRanges creates a new empty addrRanges.
   943  //
   944  // Note that this initializes addrRanges just like in the
   945  // runtime, so its memory is persistentalloc'd. Call this
   946  // function sparingly since the memory it allocates is
   947  // leaked.
   948  //
   949  // This AddrRanges is mutable, so we can test methods like
   950  // Add.
   951  func NewAddrRanges() AddrRanges {
   952  	r := addrRanges{}
   953  	r.init(testSysStat)
   954  	return AddrRanges{r, true}
   955  }
   956  
   957  // MakeAddrRanges creates a new addrRanges populated with
   958  // the ranges in a.
   959  //
   960  // The returned AddrRanges is immutable, so methods like
   961  // Add will fail.
   962  func MakeAddrRanges(a ...AddrRange) AddrRanges {
   963  	// Methods that manipulate the backing store of addrRanges.ranges should
   964  	// not be used on the result from this function (e.g. add) since they may
   965  	// trigger reallocation. That would normally be fine, except the new
   966  	// backing store won't come from the heap, but from persistentalloc, so
   967  	// we'll leak some memory implicitly.
   968  	ranges := make([]addrRange, 0, len(a))
   969  	total := uintptr(0)
   970  	for _, r := range a {
   971  		ranges = append(ranges, r.addrRange)
   972  		total += r.Size()
   973  	}
   974  	return AddrRanges{addrRanges{
   975  		ranges:     ranges,
   976  		totalBytes: total,
   977  		sysStat:    testSysStat,
   978  	}, false}
   979  }
   980  
   981  // Ranges returns a copy of the ranges described by the
   982  // addrRanges.
   983  func (a *AddrRanges) Ranges() []AddrRange {
   984  	result := make([]AddrRange, 0, len(a.addrRanges.ranges))
   985  	for _, r := range a.addrRanges.ranges {
   986  		result = append(result, AddrRange{r})
   987  	}
   988  	return result
   989  }
   990  
   991  // FindSucc returns the successor to base. See addrRanges.findSucc
   992  // for more details.
   993  func (a *AddrRanges) FindSucc(base uintptr) int {
   994  	return a.findSucc(base)
   995  }
   996  
   997  // Add adds a new AddrRange to the AddrRanges.
   998  //
   999  // The AddrRange must be mutable (i.e. created by NewAddrRanges),
  1000  // otherwise this method will throw.
  1001  func (a *AddrRanges) Add(r AddrRange) {
  1002  	if !a.mutable {
  1003  		throw("attempt to mutate immutable AddrRanges")
  1004  	}
  1005  	a.add(r.addrRange)
  1006  }
  1007  
  1008  // TotalBytes returns the totalBytes field of the addrRanges.
  1009  func (a *AddrRanges) TotalBytes() uintptr {
  1010  	return a.addrRanges.totalBytes
  1011  }
  1012  
  1013  // BitRange represents a range over a bitmap.
  1014  type BitRange struct {
  1015  	I, N uint // bit index and length in bits
  1016  }
  1017  
  1018  // NewPageAlloc creates a new page allocator for testing and
  1019  // initializes it with the scav and chunks maps. Each key in these maps
  1020  // represents a chunk index and each value is a series of bit ranges to
  1021  // set within each bitmap's chunk.
  1022  //
  1023  // The initialization of the pageAlloc preserves the invariant that if a
  1024  // scavenged bit is set the alloc bit is necessarily unset, so some
  1025  // of the bits described by scav may be cleared in the final bitmap if
  1026  // ranges in chunks overlap with them.
  1027  //
  1028  // scav is optional, and if nil, the scavenged bitmap will be cleared
  1029  // (as opposed to all 1s, which it usually is). Furthermore, every
  1030  // chunk index in scav must appear in chunks; ones that do not are
  1031  // ignored.
  1032  func NewPageAlloc(chunks, scav map[ChunkIdx][]BitRange) *PageAlloc {
  1033  	p := new(pageAlloc)
  1034  
  1035  	// We've got an entry, so initialize the pageAlloc.
  1036  	p.init(new(mutex), testSysStat, true)
  1037  	lockInit(p.mheapLock, lockRankMheap)
  1038  	for i, init := range chunks {
  1039  		addr := chunkBase(chunkIdx(i))
  1040  
  1041  		// Mark the chunk's existence in the pageAlloc.
  1042  		systemstack(func() {
  1043  			lock(p.mheapLock)
  1044  			p.grow(addr, pallocChunkBytes)
  1045  			unlock(p.mheapLock)
  1046  		})
  1047  
  1048  		// Initialize the bitmap and update pageAlloc metadata.
  1049  		ci := chunkIndex(addr)
  1050  		chunk := p.chunkOf(ci)
  1051  
  1052  		// Clear all the scavenged bits which grow set.
  1053  		chunk.scavenged.clearRange(0, pallocChunkPages)
  1054  
  1055  		// Simulate the allocation and subsequent free of all pages in
  1056  		// the chunk for the scavenge index. This sets the state equivalent
  1057  		// with all pages within the index being free.
  1058  		p.scav.index.alloc(ci, pallocChunkPages)
  1059  		p.scav.index.free(ci, 0, pallocChunkPages)
  1060  
  1061  		// Apply scavenge state if applicable.
  1062  		if scav != nil {
  1063  			if scvg, ok := scav[i]; ok {
  1064  				for _, s := range scvg {
  1065  					// Ignore the case of s.N == 0. setRange doesn't handle
  1066  					// it and it's a no-op anyway.
  1067  					if s.N != 0 {
  1068  						chunk.scavenged.setRange(s.I, s.N)
  1069  					}
  1070  				}
  1071  			}
  1072  		}
  1073  
  1074  		// Apply alloc state.
  1075  		for _, s := range init {
  1076  			// Ignore the case of s.N == 0. allocRange doesn't handle
  1077  			// it and it's a no-op anyway.
  1078  			if s.N != 0 {
  1079  				chunk.allocRange(s.I, s.N)
  1080  
  1081  				// Make sure the scavenge index is updated.
  1082  				p.scav.index.alloc(ci, s.N)
  1083  			}
  1084  		}
  1085  
  1086  		// Update heap metadata for the allocRange calls above.
  1087  		systemstack(func() {
  1088  			lock(p.mheapLock)
  1089  			p.update(addr, pallocChunkPages, false, false)
  1090  			unlock(p.mheapLock)
  1091  		})
  1092  	}
  1093  
  1094  	return (*PageAlloc)(p)
  1095  }
  1096  
  1097  // FreePageAlloc releases hard OS resources owned by the pageAlloc. Once this
  1098  // is called the pageAlloc may no longer be used. The object itself will be
  1099  // collected by the garbage collector once it is no longer live.
  1100  func FreePageAlloc(pp *PageAlloc) {
  1101  	p := (*pageAlloc)(pp)
  1102  
  1103  	// Free all the mapped space for the summary levels.
  1104  	if pageAlloc64Bit != 0 {
  1105  		for l := 0; l < summaryLevels; l++ {
  1106  			// This isn't quite right, as some of this memory may
  1107  			// be Ready instead of Reserved. The mappedReady and
  1108  			// testSysStat adjustments below correct for the
  1109  			// difference.
  1110  			sysUnreserve(unsafe.Pointer(&p.summary[l][0]), uintptr(cap(p.summary[l]))*pallocSumBytes)
  1111  		}
  1112  	} else {
  1113  		resSize := uintptr(0)
  1114  		for _, s := range p.summary {
  1115  			resSize += uintptr(cap(s)) * pallocSumBytes
  1116  		}
  1117  		// See sysUnreserve comment above.
  1118  		sysUnreserve(unsafe.Pointer(&p.summary[0][0]), alignUp(resSize, physPageSize))
  1119  	}
  1120  
  1121  	// Subtract back out whatever we mapped for the summaries.
  1122  	// sysUsed adds to p.sysStat and memstats.mappedReady no matter what
  1123  	// (and in anger should actually be accounted for), and there's no other
  1124  	// way to figure out how much we actually mapped.
  1125  	gcController.mappedReady.Add(-int64(p.summaryMappedReady))
  1126  	testSysStat.add(-int64(p.summaryMappedReady))
  1127  
  1128  	// Free extra data structures.
  1129  	//
  1130  	// TODO(prattmic): As above, some of this may be Ready, so we should
  1131  	// manually adjust mappedReady and testSysStat?
  1132  	sysUnreserve(unsafe.Pointer(&p.scav.index.chunks[0]), uintptr(cap(p.scav.index.chunks))*unsafe.Sizeof(atomicScavChunkData{}))
  1133  
  1134  	// Free the mapped space for chunks.
  1135  	for i := range p.chunks {
  1136  		if x := p.chunks[i]; x != nil {
  1137  			p.chunks[i] = nil
  1138  			// This memory comes from sysAlloc and will always be page-aligned.
  1139  			sysFree(unsafe.Pointer(x), unsafe.Sizeof(*p.chunks[0]), testSysStat)
  1140  		}
  1141  	}
  1142  }
  1143  
  1144  // BaseChunkIdx is a convenient chunkIdx value which works on both
  1145  // 64 bit and 32 bit platforms, allowing the tests to share code
  1146  // between the two.
  1147  //
  1148  // This should not be higher than 0x100*pallocChunkBytes to support
  1149  // mips and mipsle, which only have 31-bit address spaces.
  1150  var BaseChunkIdx = func() ChunkIdx {
  1151  	var prefix uintptr
  1152  	if pageAlloc64Bit != 0 {
  1153  		prefix = 0xc000
  1154  	} else {
  1155  		prefix = 0x100
  1156  	}
  1157  	baseAddr := prefix * pallocChunkBytes
  1158  	if goos.IsAix != 0 {
  1159  		baseAddr += arenaBaseOffset
  1160  	}
  1161  	return ChunkIdx(chunkIndex(baseAddr))
  1162  }()
  1163  
  1164  // PageBase returns an address given a chunk index and a page index
  1165  // relative to that chunk.
  1166  func PageBase(c ChunkIdx, pageIdx uint) uintptr {
  1167  	return chunkBase(chunkIdx(c)) + uintptr(pageIdx)*pageSize
  1168  }
  1169  
  1170  type BitsMismatch struct {
  1171  	Base      uintptr
  1172  	Got, Want uint64
  1173  }
  1174  
  1175  func CheckScavengedBitsCleared(mismatches []BitsMismatch) (n int, ok bool) {
  1176  	ok = true
  1177  
  1178  	// Run on the system stack to avoid stack growth allocation.
  1179  	systemstack(func() {
  1180  		getg().m.mallocing++
  1181  
  1182  		// Lock so that we can safely access the bitmap.
  1183  		lock(&mheap_.lock)
  1184  
  1185  	chunkLoop:
  1186  		for i := mheap_.pages.start; i < mheap_.pages.end; i++ {
  1187  			chunk := mheap_.pages.tryChunkOf(i)
  1188  			if chunk == nil {
  1189  				continue
  1190  			}
  1191  			cb := chunkBase(i)
  1192  			for j := 0; j < pallocChunkPages/64; j++ {
  1193  				// Run over each 64-bit bitmap section and ensure
  1194  				// scavenged is being cleared properly on allocation.
  1195  				// If a used bit and scavenged bit are both set, that's
  1196  				// an error, and could indicate a larger problem, or
  1197  				// an accounting problem.
  1198  				want := chunk.scavenged[j] &^ chunk.pallocBits[j]
  1199  				got := chunk.scavenged[j]
  1200  				if want != got {
  1201  					ok = false
  1202  					if n >= len(mismatches) {
  1203  						break chunkLoop
  1204  					}
  1205  					mismatches[n] = BitsMismatch{
  1206  						Base: cb + uintptr(j)*64*pageSize,
  1207  						Got:  got,
  1208  						Want: want,
  1209  					}
  1210  					n++
  1211  				}
  1212  			}
  1213  		}
  1214  		unlock(&mheap_.lock)
  1215  
  1216  		getg().m.mallocing--
  1217  	})
  1218  
  1219  	if randomizeHeapBase && len(mismatches) > 0 {
  1220  		// When goexperiment.RandomizedHeapBase64 is set we use a series of
  1221  		// padding pages to generate randomized heap base address which have
  1222  		// both the alloc and scav bits set. Because of this we expect exactly
  1223  		// one arena will have mismatches, so check for that explicitly and
  1224  		// remove the mismatches if that property holds. If we see more than one
  1225  		// arena with this property, that is an indication something has
  1226  		// actually gone wrong, so return the mismatches.
  1227  		//
  1228  		// We do this, instead of ignoring the mismatches in the chunkLoop, because
  1229  		// it's not easy to determine which arena we added the padding pages to
  1230  		// programmatically, without explicitly recording the base address somewhere
  1231  		// in a global variable (which we'd rather not do as the address of that variable
  1232  		// is likely to be somewhat predictable, potentially defeating the purpose
  1233  		// of our randomization).
  1234  		affectedArenas := map[arenaIdx]bool{}
  1235  		for _, mismatch := range mismatches {
  1236  			if mismatch.Base > 0 {
  1237  				affectedArenas[arenaIndex(mismatch.Base)] = true
  1238  			}
  1239  		}
  1240  		if len(affectedArenas) == 1 {
  1241  			ok = true
  1242  			// zero the mismatches
  1243  			for i := range n {
  1244  				mismatches[i] = BitsMismatch{}
  1245  			}
  1246  		}
  1247  	}
  1248  
  1249  	return
  1250  }
  1251  
  1252  func PageCachePagesLeaked() (leaked uintptr) {
  1253  	stw := stopTheWorld(stwForTestPageCachePagesLeaked)
  1254  
  1255  	// Walk over destroyed Ps and look for unflushed caches.
  1256  	deadp := allp[len(allp):cap(allp)]
  1257  	for _, p := range deadp {
  1258  		// Since we're going past len(allp) we may see nil Ps.
  1259  		// Just ignore them.
  1260  		if p != nil {
  1261  			leaked += uintptr(sys.OnesCount64(p.pcache.cache))
  1262  		}
  1263  	}
  1264  
  1265  	startTheWorld(stw)
  1266  	return
  1267  }
  1268  
  1269  var ProcYield = procyield
  1270  var OSYield = osyield
  1271  
  1272  type Mutex = mutex
  1273  
  1274  var Lock = lock
  1275  var Unlock = unlock
  1276  
  1277  var MutexContended = mutexContended
  1278  
  1279  func SemRootLock(addr *uint32) *mutex {
  1280  	root := semtable.rootFor(addr)
  1281  	return &root.lock
  1282  }
  1283  
  1284  var Semacquire = semacquire
  1285  var Semrelease1 = semrelease1
  1286  
  1287  func SemNwait(addr *uint32) uint32 {
  1288  	root := semtable.rootFor(addr)
  1289  	return root.nwait.Load()
  1290  }
  1291  
  1292  const SemTableSize = semTabSize
  1293  
  1294  // SemTable is a wrapper around semTable exported for testing.
  1295  type SemTable struct {
  1296  	semTable
  1297  }
  1298  
  1299  // Enqueue simulates enqueuing a waiter for a semaphore (or lock) at addr.
  1300  func (t *SemTable) Enqueue(addr *uint32) {
  1301  	s := acquireSudog()
  1302  	s.releasetime = 0
  1303  	s.acquiretime = 0
  1304  	s.ticket = 0
  1305  	t.semTable.rootFor(addr).queue(addr, s, false)
  1306  }
  1307  
  1308  // Dequeue simulates dequeuing a waiter for a semaphore (or lock) at addr.
  1309  //
  1310  // Returns true if there actually was a waiter to be dequeued.
  1311  func (t *SemTable) Dequeue(addr *uint32) bool {
  1312  	s, _, _ := t.semTable.rootFor(addr).dequeue(addr)
  1313  	if s != nil {
  1314  		releaseSudog(s)
  1315  		return true
  1316  	}
  1317  	return false
  1318  }
  1319  
  1320  // mspan wrapper for testing.
  1321  type MSpan mspan
  1322  
  1323  // Allocate an mspan for testing.
  1324  func AllocMSpan() *MSpan {
  1325  	var s *mspan
  1326  	systemstack(func() {
  1327  		lock(&mheap_.lock)
  1328  		s = (*mspan)(mheap_.spanalloc.alloc())
  1329  		s.init(0, 0)
  1330  		unlock(&mheap_.lock)
  1331  	})
  1332  	return (*MSpan)(s)
  1333  }
  1334  
  1335  // Free an allocated mspan.
  1336  func FreeMSpan(s *MSpan) {
  1337  	systemstack(func() {
  1338  		lock(&mheap_.lock)
  1339  		mheap_.spanalloc.free(unsafe.Pointer(s))
  1340  		unlock(&mheap_.lock)
  1341  	})
  1342  }
  1343  
  1344  func MSpanCountAlloc(ms *MSpan, bits []byte) int {
  1345  	s := (*mspan)(ms)
  1346  	s.nelems = uint16(len(bits) * 8)
  1347  	s.gcmarkBits = (*gcBits)(unsafe.Pointer(&bits[0]))
  1348  	result := s.countAlloc()
  1349  	s.gcmarkBits = nil
  1350  	return result
  1351  }
  1352  
  1353  const (
  1354  	TimeHistSubBucketBits = timeHistSubBucketBits
  1355  	TimeHistNumSubBuckets = timeHistNumSubBuckets
  1356  	TimeHistNumBuckets    = timeHistNumBuckets
  1357  	TimeHistMinBucketBits = timeHistMinBucketBits
  1358  	TimeHistMaxBucketBits = timeHistMaxBucketBits
  1359  )
  1360  
  1361  type TimeHistogram timeHistogram
  1362  
  1363  // Count returns the counts for the given bucket, subBucket indices.
  1364  // Returns true if the bucket was valid, otherwise returns the counts
  1365  // for the overflow bucket if bucket > 0 or the underflow bucket if
  1366  // bucket < 0, and false.
  1367  func (th *TimeHistogram) Count(bucket, subBucket int) (uint64, bool) {
  1368  	t := (*timeHistogram)(th)
  1369  	if bucket < 0 {
  1370  		return t.underflow.Load(), false
  1371  	}
  1372  	i := bucket*TimeHistNumSubBuckets + subBucket
  1373  	if i >= len(t.counts) {
  1374  		return t.overflow.Load(), false
  1375  	}
  1376  	return t.counts[i].Load(), true
  1377  }
  1378  
  1379  func (th *TimeHistogram) Record(duration int64) {
  1380  	(*timeHistogram)(th).record(duration)
  1381  }
  1382  
  1383  var TimeHistogramMetricsBuckets = timeHistogramMetricsBuckets
  1384  
  1385  func SetIntArgRegs(a int) int {
  1386  	lock(&finlock)
  1387  	old := intArgRegs
  1388  	if a >= 0 {
  1389  		intArgRegs = a
  1390  	}
  1391  	unlock(&finlock)
  1392  	return old
  1393  }
  1394  
  1395  func FinalizerGAsleep() bool {
  1396  	return fingStatus.Load()&fingWait != 0
  1397  }
  1398  
  1399  // For GCTestMoveStackOnNextCall, it's important not to introduce an
  1400  // extra layer of call, since then there's a return before the "real"
  1401  // next call.
  1402  var GCTestMoveStackOnNextCall = gcTestMoveStackOnNextCall
  1403  
  1404  // For GCTestIsReachable, it's important that we do this as a call so
  1405  // escape analysis can see through it.
  1406  func GCTestIsReachable(ptrs ...unsafe.Pointer) (mask uint64) {
  1407  	return gcTestIsReachable(ptrs...)
  1408  }
  1409  
  1410  // For GCTestPointerClass, it's important that we do this as a call so
  1411  // escape analysis can see through it.
  1412  //
  1413  // This is nosplit because gcTestPointerClass is.
  1414  //
  1415  //go:nosplit
  1416  func GCTestPointerClass(p unsafe.Pointer) string {
  1417  	return gcTestPointerClass(p)
  1418  }
  1419  
  1420  const Raceenabled = raceenabled
  1421  
  1422  const (
  1423  	GCBackgroundUtilization            = gcBackgroundUtilization
  1424  	GCGoalUtilization                  = gcGoalUtilization
  1425  	DefaultHeapMinimum                 = defaultHeapMinimum
  1426  	MemoryLimitHeapGoalHeadroomPercent = memoryLimitHeapGoalHeadroomPercent
  1427  	MemoryLimitMinHeapGoalHeadroom     = memoryLimitMinHeapGoalHeadroom
  1428  )
  1429  
  1430  type GCController struct {
  1431  	gcControllerState
  1432  }
  1433  
  1434  func NewGCController(gcPercent int, memoryLimit int64) *GCController {
  1435  	// Force the controller to escape. We're going to
  1436  	// do 64-bit atomics on it, and if it gets stack-allocated
  1437  	// on a 32-bit architecture, it may get allocated unaligned
  1438  	// space.
  1439  	g := Escape(new(GCController))
  1440  	g.gcControllerState.test = true // Mark it as a test copy.
  1441  	g.init(int32(gcPercent), memoryLimit)
  1442  	return g
  1443  }
  1444  
  1445  func (c *GCController) StartCycle(stackSize, globalsSize uint64, scannableFrac float64, gomaxprocs int) {
  1446  	trigger, _ := c.trigger()
  1447  	if c.heapMarked > trigger {
  1448  		trigger = c.heapMarked
  1449  	}
  1450  	c.maxStackScan.Store(stackSize)
  1451  	c.globalsScan.Store(globalsSize)
  1452  	c.heapLive.Store(trigger)
  1453  	c.heapScan.Add(int64(float64(trigger-c.heapMarked) * scannableFrac))
  1454  	c.startCycle(0, gomaxprocs, gcTrigger{kind: gcTriggerHeap})
  1455  }
  1456  
  1457  func (c *GCController) AssistWorkPerByte() float64 {
  1458  	return c.assistWorkPerByte.Load()
  1459  }
  1460  
  1461  func (c *GCController) HeapGoal() uint64 {
  1462  	return c.heapGoal()
  1463  }
  1464  
  1465  func (c *GCController) HeapLive() uint64 {
  1466  	return c.heapLive.Load()
  1467  }
  1468  
  1469  func (c *GCController) HeapMarked() uint64 {
  1470  	return c.heapMarked
  1471  }
  1472  
  1473  func (c *GCController) Triggered() uint64 {
  1474  	return c.triggered
  1475  }
  1476  
  1477  type GCControllerReviseDelta struct {
  1478  	HeapLive        int64
  1479  	HeapScan        int64
  1480  	HeapScanWork    int64
  1481  	StackScanWork   int64
  1482  	GlobalsScanWork int64
  1483  }
  1484  
  1485  func (c *GCController) Revise(d GCControllerReviseDelta) {
  1486  	c.heapLive.Add(d.HeapLive)
  1487  	c.heapScan.Add(d.HeapScan)
  1488  	c.heapScanWork.Add(d.HeapScanWork)
  1489  	c.stackScanWork.Add(d.StackScanWork)
  1490  	c.globalsScanWork.Add(d.GlobalsScanWork)
  1491  	c.revise()
  1492  }
  1493  
  1494  func (c *GCController) EndCycle(bytesMarked uint64, assistTime, elapsed int64, gomaxprocs int) {
  1495  	c.assistTime.Store(assistTime)
  1496  	c.endCycle(elapsed, gomaxprocs)
  1497  	c.resetLive(bytesMarked)
  1498  	c.commit(false)
  1499  }
  1500  
  1501  func (c *GCController) AddIdleMarkWorker() bool {
  1502  	return c.addIdleMarkWorker()
  1503  }
  1504  
  1505  func (c *GCController) NeedIdleMarkWorker() bool {
  1506  	return c.needIdleMarkWorker()
  1507  }
  1508  
  1509  func (c *GCController) RemoveIdleMarkWorker() {
  1510  	c.removeIdleMarkWorker()
  1511  }
  1512  
  1513  func (c *GCController) SetMaxIdleMarkWorkers(max int32) {
  1514  	c.setMaxIdleMarkWorkers(max)
  1515  }
  1516  
  1517  var alwaysFalse bool
  1518  var escapeSink any
  1519  
  1520  func Escape[T any](x T) T {
  1521  	if alwaysFalse {
  1522  		escapeSink = x
  1523  	}
  1524  	return x
  1525  }
  1526  
  1527  // Acquirem blocks preemption.
  1528  func Acquirem() {
  1529  	acquirem()
  1530  }
  1531  
  1532  func Releasem() {
  1533  	releasem(getg().m)
  1534  }
  1535  
  1536  // GoschedIfBusy is an explicit preemption check to call back
  1537  // into the scheduler. This is useful for tests that run code
  1538  // which spend most of their time as non-preemptible, as it
  1539  // can be placed right after becoming preemptible again to ensure
  1540  // that the scheduler gets a chance to preempt the goroutine.
  1541  func GoschedIfBusy() {
  1542  	goschedIfBusy()
  1543  }
  1544  
  1545  type PIController struct {
  1546  	piController
  1547  }
  1548  
  1549  func NewPIController(kp, ti, tt, min, max float64) *PIController {
  1550  	return &PIController{piController{
  1551  		kp:  kp,
  1552  		ti:  ti,
  1553  		tt:  tt,
  1554  		min: min,
  1555  		max: max,
  1556  	}}
  1557  }
  1558  
  1559  func (c *PIController) Next(input, setpoint, period float64) (float64, bool) {
  1560  	return c.piController.next(input, setpoint, period)
  1561  }
  1562  
  1563  const (
  1564  	CapacityPerProc          = capacityPerProc
  1565  	GCCPULimiterUpdatePeriod = gcCPULimiterUpdatePeriod
  1566  )
  1567  
  1568  type GCCPULimiter struct {
  1569  	limiter gcCPULimiterState
  1570  }
  1571  
  1572  func NewGCCPULimiter(now int64, gomaxprocs int32) *GCCPULimiter {
  1573  	// Force the controller to escape. We're going to
  1574  	// do 64-bit atomics on it, and if it gets stack-allocated
  1575  	// on a 32-bit architecture, it may get allocated unaligned
  1576  	// space.
  1577  	l := Escape(new(GCCPULimiter))
  1578  	l.limiter.test = true
  1579  	l.limiter.resetCapacity(now, gomaxprocs)
  1580  	return l
  1581  }
  1582  
  1583  func (l *GCCPULimiter) Fill() uint64 {
  1584  	return l.limiter.bucket.fill
  1585  }
  1586  
  1587  func (l *GCCPULimiter) Capacity() uint64 {
  1588  	return l.limiter.bucket.capacity
  1589  }
  1590  
  1591  func (l *GCCPULimiter) Overflow() uint64 {
  1592  	return l.limiter.overflow
  1593  }
  1594  
  1595  func (l *GCCPULimiter) Limiting() bool {
  1596  	return l.limiter.limiting()
  1597  }
  1598  
  1599  func (l *GCCPULimiter) NeedUpdate(now int64) bool {
  1600  	return l.limiter.needUpdate(now)
  1601  }
  1602  
  1603  func (l *GCCPULimiter) StartGCTransition(enableGC bool, now int64) {
  1604  	l.limiter.startGCTransition(enableGC, now)
  1605  }
  1606  
  1607  func (l *GCCPULimiter) FinishGCTransition(now int64) {
  1608  	l.limiter.finishGCTransition(now)
  1609  }
  1610  
  1611  func (l *GCCPULimiter) Update(now int64) {
  1612  	l.limiter.update(now)
  1613  }
  1614  
  1615  func (l *GCCPULimiter) AddAssistTime(t int64) {
  1616  	l.limiter.addAssistTime(t)
  1617  }
  1618  
  1619  func (l *GCCPULimiter) ResetCapacity(now int64, nprocs int32) {
  1620  	l.limiter.resetCapacity(now, nprocs)
  1621  }
  1622  
  1623  const ScavengePercent = scavengePercent
  1624  
  1625  type Scavenger struct {
  1626  	Sleep      func(int64) int64
  1627  	Scavenge   func(uintptr) (uintptr, int64)
  1628  	ShouldStop func() bool
  1629  	GoMaxProcs func() int32
  1630  
  1631  	released  atomic.Uintptr
  1632  	scavenger scavengerState
  1633  	stop      chan<- struct{}
  1634  	done      <-chan struct{}
  1635  }
  1636  
  1637  func (s *Scavenger) Start() {
  1638  	if s.Sleep == nil || s.Scavenge == nil || s.ShouldStop == nil || s.GoMaxProcs == nil {
  1639  		panic("must populate all stubs")
  1640  	}
  1641  
  1642  	// Install hooks.
  1643  	s.scavenger.sleepStub = s.Sleep
  1644  	s.scavenger.scavenge = s.Scavenge
  1645  	s.scavenger.shouldStop = s.ShouldStop
  1646  	s.scavenger.gomaxprocs = s.GoMaxProcs
  1647  
  1648  	// Start up scavenger goroutine, and wait for it to be ready.
  1649  	stop := make(chan struct{})
  1650  	s.stop = stop
  1651  	done := make(chan struct{})
  1652  	s.done = done
  1653  	go func() {
  1654  		// This should match bgscavenge, loosely.
  1655  		s.scavenger.init()
  1656  		s.scavenger.park()
  1657  		for {
  1658  			select {
  1659  			case <-stop:
  1660  				close(done)
  1661  				return
  1662  			default:
  1663  			}
  1664  			released, workTime := s.scavenger.run()
  1665  			if released == 0 {
  1666  				s.scavenger.park()
  1667  				continue
  1668  			}
  1669  			s.released.Add(released)
  1670  			s.scavenger.sleep(workTime)
  1671  		}
  1672  	}()
  1673  	if !s.BlockUntilParked(1e9 /* 1 second */) {
  1674  		panic("timed out waiting for scavenger to get ready")
  1675  	}
  1676  }
  1677  
  1678  // BlockUntilParked blocks until the scavenger parks, or until
  1679  // timeout is exceeded. Returns true if the scavenger parked.
  1680  //
  1681  // Note that in testing, parked means something slightly different.
  1682  // In anger, the scavenger parks to sleep, too, but in testing,
  1683  // it only parks when it actually has no work to do.
  1684  func (s *Scavenger) BlockUntilParked(timeout int64) bool {
  1685  	// Just spin, waiting for it to park.
  1686  	//
  1687  	// The actual parking process is racy with respect to
  1688  	// wakeups, which is fine, but for testing we need something
  1689  	// a bit more robust.
  1690  	start := nanotime()
  1691  	for nanotime()-start < timeout {
  1692  		lock(&s.scavenger.lock)
  1693  		parked := s.scavenger.parked
  1694  		unlock(&s.scavenger.lock)
  1695  		if parked {
  1696  			return true
  1697  		}
  1698  		Gosched()
  1699  	}
  1700  	return false
  1701  }
  1702  
  1703  // Released returns how many bytes the scavenger released.
  1704  func (s *Scavenger) Released() uintptr {
  1705  	return s.released.Load()
  1706  }
  1707  
  1708  // Wake wakes up a parked scavenger to keep running.
  1709  func (s *Scavenger) Wake() {
  1710  	s.scavenger.wake()
  1711  }
  1712  
  1713  // Stop cleans up the scavenger's resources. The scavenger
  1714  // must be parked for this to work.
  1715  func (s *Scavenger) Stop() {
  1716  	lock(&s.scavenger.lock)
  1717  	parked := s.scavenger.parked
  1718  	unlock(&s.scavenger.lock)
  1719  	if !parked {
  1720  		panic("tried to clean up scavenger that is not parked")
  1721  	}
  1722  	close(s.stop)
  1723  	s.Wake()
  1724  	<-s.done
  1725  }
  1726  
  1727  type ScavengeIndex struct {
  1728  	i scavengeIndex
  1729  }
  1730  
  1731  func NewScavengeIndex(min, max ChunkIdx) *ScavengeIndex {
  1732  	s := new(ScavengeIndex)
  1733  	// This is a bit lazy but we easily guarantee we'll be able
  1734  	// to reference all the relevant chunks. The worst-case
  1735  	// memory usage here is 512 MiB, but tests generally use
  1736  	// small offsets from BaseChunkIdx, which results in ~100s
  1737  	// of KiB in memory use.
  1738  	//
  1739  	// This may still be worth making better, at least by sharing
  1740  	// this fairly large array across calls with a sync.Pool or
  1741  	// something. Currently, when the tests are run serially,
  1742  	// it takes around 0.5s. Not all that much, but if we have
  1743  	// a lot of tests like this it could add up.
  1744  	s.i.chunks = make([]atomicScavChunkData, max)
  1745  	s.i.min.Store(uintptr(min))
  1746  	s.i.max.Store(uintptr(max))
  1747  	s.i.minHeapIdx.Store(uintptr(min))
  1748  	s.i.test = true
  1749  	return s
  1750  }
  1751  
  1752  func (s *ScavengeIndex) Find(force bool) (ChunkIdx, uint) {
  1753  	ci, off := s.i.find(force)
  1754  	return ChunkIdx(ci), off
  1755  }
  1756  
  1757  func (s *ScavengeIndex) AllocRange(base, limit uintptr) {
  1758  	sc, ec := chunkIndex(base), chunkIndex(limit-1)
  1759  	si, ei := chunkPageIndex(base), chunkPageIndex(limit-1)
  1760  
  1761  	if sc == ec {
  1762  		// The range doesn't cross any chunk boundaries.
  1763  		s.i.alloc(sc, ei+1-si)
  1764  	} else {
  1765  		// The range crosses at least one chunk boundary.
  1766  		s.i.alloc(sc, pallocChunkPages-si)
  1767  		for c := sc + 1; c < ec; c++ {
  1768  			s.i.alloc(c, pallocChunkPages)
  1769  		}
  1770  		s.i.alloc(ec, ei+1)
  1771  	}
  1772  }
  1773  
  1774  func (s *ScavengeIndex) FreeRange(base, limit uintptr) {
  1775  	sc, ec := chunkIndex(base), chunkIndex(limit-1)
  1776  	si, ei := chunkPageIndex(base), chunkPageIndex(limit-1)
  1777  
  1778  	if sc == ec {
  1779  		// The range doesn't cross any chunk boundaries.
  1780  		s.i.free(sc, si, ei+1-si)
  1781  	} else {
  1782  		// The range crosses at least one chunk boundary.
  1783  		s.i.free(sc, si, pallocChunkPages-si)
  1784  		for c := sc + 1; c < ec; c++ {
  1785  			s.i.free(c, 0, pallocChunkPages)
  1786  		}
  1787  		s.i.free(ec, 0, ei+1)
  1788  	}
  1789  }
  1790  
  1791  func (s *ScavengeIndex) ResetSearchAddrs() {
  1792  	for _, a := range []*atomicOffAddr{&s.i.searchAddrBg, &s.i.searchAddrForce} {
  1793  		addr, marked := a.Load()
  1794  		if marked {
  1795  			a.StoreUnmark(addr, addr)
  1796  		}
  1797  		a.Clear()
  1798  	}
  1799  	s.i.freeHWM = minOffAddr
  1800  }
  1801  
  1802  func (s *ScavengeIndex) NextGen() {
  1803  	s.i.nextGen()
  1804  }
  1805  
  1806  func (s *ScavengeIndex) SetEmpty(ci ChunkIdx) {
  1807  	s.i.setEmpty(chunkIdx(ci))
  1808  }
  1809  
  1810  func CheckPackScavChunkData(gen uint32, inUse, lastInUse uint16, flags uint8) bool {
  1811  	sc0 := scavChunkData{
  1812  		gen:            gen,
  1813  		inUse:          inUse,
  1814  		lastInUse:      lastInUse,
  1815  		scavChunkFlags: scavChunkFlags(flags),
  1816  	}
  1817  	scp := sc0.pack()
  1818  	sc1 := unpackScavChunkData(scp)
  1819  	return sc0 == sc1
  1820  }
  1821  
  1822  const GTrackingPeriod = gTrackingPeriod
  1823  
  1824  var ZeroBase = unsafe.Pointer(&zerobase)
  1825  
  1826  const UserArenaChunkBytes = userArenaChunkBytes
  1827  
  1828  type UserArena struct {
  1829  	arena *userArena
  1830  }
  1831  
  1832  func NewUserArena() *UserArena {
  1833  	return &UserArena{newUserArena()}
  1834  }
  1835  
  1836  func (a *UserArena) New(out *any) {
  1837  	i := efaceOf(out)
  1838  	typ := i._type
  1839  	if typ.Kind() != abi.Pointer {
  1840  		panic("new result of non-ptr type")
  1841  	}
  1842  	typ = (*ptrtype)(unsafe.Pointer(typ)).Elem
  1843  	i.data = a.arena.new(typ)
  1844  }
  1845  
  1846  func (a *UserArena) Slice(sl any, cap int) {
  1847  	a.arena.slice(sl, cap)
  1848  }
  1849  
  1850  func (a *UserArena) Free() {
  1851  	a.arena.free()
  1852  }
  1853  
  1854  func GlobalWaitingArenaChunks() int {
  1855  	n := 0
  1856  	systemstack(func() {
  1857  		lock(&mheap_.lock)
  1858  		for s := mheap_.userArena.quarantineList.first; s != nil; s = s.next {
  1859  			n++
  1860  		}
  1861  		unlock(&mheap_.lock)
  1862  	})
  1863  	return n
  1864  }
  1865  
  1866  func UserArenaClone[T any](s T) T {
  1867  	return arena_heapify(s).(T)
  1868  }
  1869  
  1870  var AlignUp = alignUp
  1871  
  1872  func BlockUntilEmptyFinalizerQueue(timeout int64) bool {
  1873  	return blockUntilEmptyFinalizerQueue(timeout)
  1874  }
  1875  
  1876  func BlockUntilEmptyCleanupQueue(timeout int64) bool {
  1877  	return gcCleanups.blockUntilEmpty(timeout)
  1878  }
  1879  
  1880  func FrameStartLine(f *Frame) int {
  1881  	return f.startLine
  1882  }
  1883  
  1884  // PersistentAlloc allocates some memory that lives outside the Go heap.
  1885  // This memory will never be freed; use sparingly.
  1886  func PersistentAlloc(n, align uintptr) unsafe.Pointer {
  1887  	return persistentalloc(n, align, &memstats.other_sys)
  1888  }
  1889  
  1890  const TagAlign = tagAlign
  1891  
  1892  // FPCallers works like Callers and uses frame pointer unwinding to populate
  1893  // pcBuf with the return addresses of the physical frames on the stack.
  1894  func FPCallers(pcBuf []uintptr) int {
  1895  	return fpTracebackPCs(unsafe.Pointer(getfp()), pcBuf)
  1896  }
  1897  
  1898  const FramePointerEnabled = framepointer_enabled
  1899  
  1900  var (
  1901  	IsPinned      = isPinned
  1902  	GetPinCounter = pinnerGetPinCounter
  1903  )
  1904  
  1905  func SetPinnerLeakPanic(f func()) {
  1906  	pinnerLeakPanic = f
  1907  }
  1908  func GetPinnerLeakPanic() func() {
  1909  	return pinnerLeakPanic
  1910  }
  1911  
  1912  var testUintptr uintptr
  1913  
  1914  func MyGenericFunc[T any]() {
  1915  	systemstack(func() {
  1916  		testUintptr = 4
  1917  	})
  1918  }
  1919  
  1920  func UnsafePoint(pc uintptr) bool {
  1921  	fi := findfunc(pc)
  1922  	v := pcdatavalue(fi, abi.PCDATA_UnsafePoint, pc)
  1923  	switch v {
  1924  	case abi.UnsafePointUnsafe:
  1925  		return true
  1926  	case abi.UnsafePointSafe:
  1927  		return false
  1928  	case abi.UnsafePointRestart1, abi.UnsafePointRestart2, abi.UnsafePointRestartAtEntry:
  1929  		// These are all interruptible, they just encode a nonstandard
  1930  		// way of recovering when interrupted.
  1931  		return false
  1932  	default:
  1933  		var buf [20]byte
  1934  		panic("invalid unsafe point code " + string(itoa(buf[:], uint64(v))))
  1935  	}
  1936  }
  1937  
  1938  type TraceMap struct {
  1939  	traceMap
  1940  }
  1941  
  1942  func (m *TraceMap) PutString(s string) (uint64, bool) {
  1943  	return m.traceMap.put(unsafe.Pointer(unsafe.StringData(s)), uintptr(len(s)))
  1944  }
  1945  
  1946  func (m *TraceMap) Reset() {
  1947  	m.traceMap.reset()
  1948  }
  1949  
  1950  func SetSpinInGCMarkDone(spin bool) {
  1951  	gcDebugMarkDone.spinAfterRaggedBarrier.Store(spin)
  1952  }
  1953  
  1954  func GCMarkDoneRestarted() bool {
  1955  	// Only read this outside of the GC. If we're running during a GC, just report false.
  1956  	mp := acquirem()
  1957  	if gcphase != _GCoff {
  1958  		releasem(mp)
  1959  		return false
  1960  	}
  1961  	restarted := gcDebugMarkDone.restartedDueTo27993
  1962  	releasem(mp)
  1963  	return restarted
  1964  }
  1965  
  1966  func GCMarkDoneResetRestartFlag() {
  1967  	mp := acquirem()
  1968  	for gcphase != _GCoff {
  1969  		releasem(mp)
  1970  		Gosched()
  1971  		mp = acquirem()
  1972  	}
  1973  	gcDebugMarkDone.restartedDueTo27993 = false
  1974  	releasem(mp)
  1975  }
  1976  
  1977  type BitCursor struct {
  1978  	b bitCursor
  1979  }
  1980  
  1981  func NewBitCursor(buf *byte) BitCursor {
  1982  	return BitCursor{b: bitCursor{ptr: buf, n: 0}}
  1983  }
  1984  
  1985  func (b BitCursor) Write(data *byte, cnt uintptr) {
  1986  	b.b.write(data, cnt)
  1987  }
  1988  func (b BitCursor) Offset(cnt uintptr) BitCursor {
  1989  	return BitCursor{b: b.b.offset(cnt)}
  1990  }
  1991  
  1992  const (
  1993  	BubbleAssocUnbubbled     = bubbleAssocUnbubbled
  1994  	BubbleAssocCurrentBubble = bubbleAssocCurrentBubble
  1995  	BubbleAssocOtherBubble   = bubbleAssocOtherBubble
  1996  )
  1997  
  1998  type TraceStackTable traceStackTable
  1999  
  2000  func (t *TraceStackTable) Reset() {
  2001  	t.tab.reset()
  2002  }
  2003  
  2004  func TraceStack(gp *G, tab *TraceStackTable) {
  2005  	traceStack(0, gp, (*traceStackTable)(tab))
  2006  }
  2007  
  2008  var X86HasAVX = &x86HasAVX
  2009  
  2010  var DebugDecorateMappings = &debug.decoratemappings
  2011  
  2012  func SetVMANameSupported() bool { return setVMANameSupported() }
  2013  
  2014  type ListHead struct {
  2015  	l listHead
  2016  }
  2017  
  2018  func (head *ListHead) Init(off uintptr) {
  2019  	head.l.init(off)
  2020  }
  2021  
  2022  type ListNode struct {
  2023  	l listNode
  2024  }
  2025  
  2026  func (head *ListHead) Push(p unsafe.Pointer) {
  2027  	head.l.push(p)
  2028  }
  2029  
  2030  func (head *ListHead) Pop() unsafe.Pointer {
  2031  	return head.l.pop()
  2032  }
  2033  
  2034  func (head *ListHead) Remove(p unsafe.Pointer) {
  2035  	head.l.remove(p)
  2036  }
  2037  
  2038  type ListHeadManual struct {
  2039  	l listHeadManual
  2040  }
  2041  
  2042  func (head *ListHeadManual) Init(off uintptr) {
  2043  	head.l.init(off)
  2044  }
  2045  
  2046  type ListNodeManual struct {
  2047  	l listNodeManual
  2048  }
  2049  
  2050  func (head *ListHeadManual) Push(p unsafe.Pointer) {
  2051  	head.l.push(p)
  2052  }
  2053  
  2054  func (head *ListHeadManual) Pop() unsafe.Pointer {
  2055  	return head.l.pop()
  2056  }
  2057  
  2058  func (head *ListHeadManual) Remove(p unsafe.Pointer) {
  2059  	head.l.remove(p)
  2060  }
  2061  
  2062  func Hexdumper(base uintptr, wordBytes int, mark func(addr uintptr, start func()), data ...[]byte) string {
  2063  	buf := make([]byte, 0, 2048)
  2064  	getg().writebuf = buf
  2065  	h := hexdumper{addr: base, addrBytes: 4, wordBytes: uint8(wordBytes)}
  2066  	if mark != nil {
  2067  		h.mark = func(addr uintptr, m hexdumpMarker) {
  2068  			mark(addr, m.start)
  2069  		}
  2070  	}
  2071  	for _, d := range data {
  2072  		h.write(d)
  2073  	}
  2074  	h.close()
  2075  	n := len(getg().writebuf)
  2076  	getg().writebuf = nil
  2077  	if n == cap(buf) {
  2078  		panic("Hexdumper buf too small")
  2079  	}
  2080  	return string(buf[:n])
  2081  }
  2082  
  2083  func HexdumpWords(p, bytes uintptr) string {
  2084  	buf := make([]byte, 0, 2048)
  2085  	getg().writebuf = buf
  2086  	hexdumpWords(p, bytes, nil)
  2087  	n := len(getg().writebuf)
  2088  	getg().writebuf = nil
  2089  	if n == cap(buf) {
  2090  		panic("HexdumpWords buf too small")
  2091  	}
  2092  	return string(buf[:n])
  2093  }
  2094  
  2095  // DumpPrintQuoted provides access to print(quoted()) for the tests in
  2096  // runtime/print_quoted_test.go, allowing us to test that implementation.
  2097  func DumpPrintQuoted(s string) string {
  2098  	gp := getg()
  2099  	gp.writebuf = make([]byte, 0, 1<<20)
  2100  	print(quoted(s))
  2101  	buf := gp.writebuf
  2102  	gp.writebuf = nil
  2103  
  2104  	return string(buf)
  2105  }
  2106  
  2107  // PrintBacklog returns a copy of the runtime's print backlog.
  2108  func PrintBacklog() []byte {
  2109  	b := make([]byte, len(printBacklog))
  2110  	printlock()
  2111  	copy(b, printBacklog[:])
  2112  	printunlock()
  2113  	return b
  2114  }
  2115  
  2116  // DumpPrint returns the output of print(v).
  2117  func DumpPrint[T any](v T) string {
  2118  	gp := getg()
  2119  	gp.writebuf = make([]byte, 0, 2048)
  2120  	print(v)
  2121  	buf := gp.writebuf
  2122  	gp.writebuf = nil
  2123  
  2124  	return string(buf)
  2125  }
  2126  
  2127  var (
  2128  	Float64Bytes    = float64Bytes
  2129  	Float32Bytes    = float32Bytes
  2130  	Complex128Bytes = complex128Bytes
  2131  	Complex64Bytes  = complex64Bytes
  2132  )
  2133  
  2134  func GetScanAlloc() uintptr {
  2135  	c := getMCache(getg().m)
  2136  	return c.scanAlloc
  2137  }
  2138  
  2139  func MallocGC(size uintptr, typ *abi.Type, needzero bool) unsafe.Pointer {
  2140  	return mallocgc(size, typ, needzero)
  2141  }
  2142  
  2143  func FuncNamePiecesForPrint(name string) (string, string, string, string, string) {
  2144  	return funcNamePiecesForPrint(name)
  2145  }
  2146  
  2147  var InHeapOrStack = inHeapOrStack
  2148  

View as plain text