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  const RandomizeHeapBase = randomizeHeapBase
   578  
   579  func ValidArenaAddr(p uintptr) bool {
   580  	return arenaIndex(p) < 1<<arenaBits
   581  }
   582  
   583  // ArenaHintAddrs returns the heap's remaining arena hint addresses, in
   584  // chain order.
   585  func ArenaHintAddrs() []uintptr {
   586  	// Preallocate: appending while holding the heap lock would allocate
   587  	// under mheap_.lock. mallocinit generates at most 64 heap hints.
   588  	out := make([]uintptr, 0, 128)
   589  	lock(&mheap_.lock)
   590  	for h := mheap_.arenaHints; h != nil; h = h.next {
   591  		out = append(out, h.addr)
   592  	}
   593  	unlock(&mheap_.lock)
   594  	return out
   595  }
   596  
   597  type G = g
   598  
   599  type WaitingG = waitingG
   600  
   601  type XRegPerG = xRegPerG
   602  
   603  type ValgrindPerG = valgrindPerG
   604  
   605  type WasmContPerG = wasmContPerG
   606  
   607  func Getg() *G {
   608  	return getg()
   609  }
   610  
   611  func Goid() uint64 {
   612  	return getg().goid
   613  }
   614  
   615  func GIsWaitingOnMutex(gp *G) bool {
   616  	return readgstatus(gp) == _Gwaiting && gp.waitreason.isMutexWait()
   617  }
   618  
   619  var CasGStatusAlwaysTrack = &casgstatusAlwaysTrack
   620  
   621  //go:noinline
   622  func PanicForTesting(b []byte, i int) byte {
   623  	return unexportedPanicForTesting(b, i)
   624  }
   625  
   626  //go:noinline
   627  func unexportedPanicForTesting(b []byte, i int) byte {
   628  	return b[i]
   629  }
   630  
   631  func G0StackOverflow() {
   632  	systemstack(func() {
   633  		g0 := getg()
   634  		sp := sys.GetCallerSP()
   635  		// The stack bounds for g0 stack is not always precise.
   636  		// Use an artificially small stack, to trigger a stack overflow
   637  		// without actually run out of the system stack (which may seg fault).
   638  		g0.stack.lo = sp - 4096 - stackSystem
   639  		g0.stackguard0 = g0.stack.lo + stackGuard
   640  		g0.stackguard1 = g0.stackguard0
   641  
   642  		stackOverflow(nil)
   643  	})
   644  }
   645  
   646  func stackOverflow(x *byte) {
   647  	var buf [256]byte
   648  	stackOverflow(&buf[0])
   649  }
   650  
   651  func RunGetgThreadSwitchTest() {
   652  	// Test that getg works correctly with thread switch.
   653  	// With gccgo, if we generate getg inlined, the backend
   654  	// may cache the address of the TLS variable, which
   655  	// will become invalid after a thread switch. This test
   656  	// checks that the bad caching doesn't happen.
   657  
   658  	ch := make(chan int)
   659  	go func(ch chan int) {
   660  		ch <- 5
   661  		LockOSThread()
   662  	}(ch)
   663  
   664  	g1 := getg()
   665  
   666  	// Block on a receive. This is likely to get us a thread
   667  	// switch. If we yield to the sender goroutine, it will
   668  	// lock the thread, forcing us to resume on a different
   669  	// thread.
   670  	<-ch
   671  
   672  	g2 := getg()
   673  	if g1 != g2 {
   674  		panic("g1 != g2")
   675  	}
   676  
   677  	// Also test getg after some control flow, as the
   678  	// backend is sensitive to control flow.
   679  	g3 := getg()
   680  	if g1 != g3 {
   681  		panic("g1 != g3")
   682  	}
   683  }
   684  
   685  // Expose freegc for testing.
   686  func Freegc(p unsafe.Pointer, size uintptr, noscan bool) {
   687  	freegc(p, size, noscan)
   688  }
   689  
   690  // Expose gcAssistBytes for the current g for testing.
   691  func AssistCredit() int64 {
   692  	assistG := getg()
   693  	if assistG.m.curg != nil {
   694  		assistG = assistG.m.curg
   695  	}
   696  	return assistG.gcAssistBytes
   697  }
   698  
   699  // Expose gcBlackenEnabled for testing.
   700  func GcBlackenEnable() bool {
   701  	// Note we do a non-atomic load here.
   702  	// Some checks against gcBlackenEnabled (e.g., in mallocgc)
   703  	// are currently done via non-atomic load for performance reasons,
   704  	// but other checks are done via atomic load (e.g., in mgcmark.go),
   705  	// so interpreting this value in a test may be subtle.
   706  	return gcBlackenEnabled != 0
   707  }
   708  
   709  const SizeSpecializedMallocEnabled = sizeSpecializedMallocEnabled
   710  
   711  const RuntimeFreegcEnabled = runtimeFreegcEnabled
   712  
   713  const (
   714  	PageSize         = pageSize
   715  	PallocChunkPages = pallocChunkPages
   716  	PageAlloc64Bit   = pageAlloc64Bit
   717  	PallocSumBytes   = pallocSumBytes
   718  )
   719  
   720  // Expose pallocSum for testing.
   721  type PallocSum pallocSum
   722  
   723  func PackPallocSum(start, max, end uint) PallocSum { return PallocSum(packPallocSum(start, max, end)) }
   724  func (m PallocSum) Start() uint                    { return pallocSum(m).start() }
   725  func (m PallocSum) Max() uint                      { return pallocSum(m).max() }
   726  func (m PallocSum) End() uint                      { return pallocSum(m).end() }
   727  
   728  // Expose pallocBits for testing.
   729  type PallocBits pallocBits
   730  
   731  func (b *PallocBits) Find(npages uintptr, searchIdx uint) (uint, uint) {
   732  	return (*pallocBits)(b).find(npages, searchIdx)
   733  }
   734  func (b *PallocBits) AllocRange(i, n uint)       { (*pallocBits)(b).allocRange(i, n) }
   735  func (b *PallocBits) Free(i, n uint)             { (*pallocBits)(b).free(i, n) }
   736  func (b *PallocBits) Summarize() PallocSum       { return PallocSum((*pallocBits)(b).summarize()) }
   737  func (b *PallocBits) PopcntRange(i, n uint) uint { return (*pageBits)(b).popcntRange(i, n) }
   738  
   739  // SummarizeSlow is a slow but more obviously correct implementation
   740  // of (*pallocBits).summarize. Used for testing.
   741  func SummarizeSlow(b *PallocBits) PallocSum {
   742  	var start, most, end uint
   743  
   744  	const N = uint(len(b)) * 64
   745  	for start < N && (*pageBits)(b).get(start) == 0 {
   746  		start++
   747  	}
   748  	for end < N && (*pageBits)(b).get(N-end-1) == 0 {
   749  		end++
   750  	}
   751  	run := uint(0)
   752  	for i := uint(0); i < N; i++ {
   753  		if (*pageBits)(b).get(i) == 0 {
   754  			run++
   755  		} else {
   756  			run = 0
   757  		}
   758  		most = max(most, run)
   759  	}
   760  	return PackPallocSum(start, most, end)
   761  }
   762  
   763  // Expose non-trivial helpers for testing.
   764  func FindBitRange64(c uint64, n uint) uint { return findBitRange64(c, n) }
   765  
   766  // Given two PallocBits, returns a set of bit ranges where
   767  // they differ.
   768  func DiffPallocBits(a, b *PallocBits) []BitRange {
   769  	ba := (*pageBits)(a)
   770  	bb := (*pageBits)(b)
   771  
   772  	var d []BitRange
   773  	base, size := uint(0), uint(0)
   774  	for i := uint(0); i < uint(len(ba))*64; i++ {
   775  		if ba.get(i) != bb.get(i) {
   776  			if size == 0 {
   777  				base = i
   778  			}
   779  			size++
   780  		} else {
   781  			if size != 0 {
   782  				d = append(d, BitRange{base, size})
   783  			}
   784  			size = 0
   785  		}
   786  	}
   787  	if size != 0 {
   788  		d = append(d, BitRange{base, size})
   789  	}
   790  	return d
   791  }
   792  
   793  // StringifyPallocBits gets the bits in the bit range r from b,
   794  // and returns a string containing the bits as ASCII 0 and 1
   795  // characters.
   796  func StringifyPallocBits(b *PallocBits, r BitRange) string {
   797  	str := ""
   798  	for j := r.I; j < r.I+r.N; j++ {
   799  		if (*pageBits)(b).get(j) != 0 {
   800  			str += "1"
   801  		} else {
   802  			str += "0"
   803  		}
   804  	}
   805  	return str
   806  }
   807  
   808  // Expose pallocData for testing.
   809  type PallocData pallocData
   810  
   811  func (d *PallocData) FindScavengeCandidate(searchIdx uint, min, max uintptr) (uint, uint) {
   812  	return (*pallocData)(d).findScavengeCandidate(searchIdx, min, max)
   813  }
   814  func (d *PallocData) AllocRange(i, n uint) { (*pallocData)(d).allocRange(i, n) }
   815  func (d *PallocData) ScavengedSetRange(i, n uint) {
   816  	(*pallocData)(d).scavenged.setRange(i, n)
   817  }
   818  func (d *PallocData) PallocBits() *PallocBits {
   819  	return (*PallocBits)(&(*pallocData)(d).pallocBits)
   820  }
   821  func (d *PallocData) Scavenged() *PallocBits {
   822  	return (*PallocBits)(&(*pallocData)(d).scavenged)
   823  }
   824  
   825  // Expose fillAligned for testing.
   826  func FillAligned(x uint64, m uint) uint64 { return fillAligned(x, m) }
   827  
   828  // Expose pageCache for testing.
   829  type PageCache pageCache
   830  
   831  const PageCachePages = pageCachePages
   832  
   833  func NewPageCache(base uintptr, cache, scav uint64) PageCache {
   834  	return PageCache(pageCache{base: base, cache: cache, scav: scav})
   835  }
   836  func (c *PageCache) Empty() bool   { return (*pageCache)(c).empty() }
   837  func (c *PageCache) Base() uintptr { return (*pageCache)(c).base }
   838  func (c *PageCache) Cache() uint64 { return (*pageCache)(c).cache }
   839  func (c *PageCache) Scav() uint64  { return (*pageCache)(c).scav }
   840  func (c *PageCache) Alloc(npages uintptr) (uintptr, uintptr) {
   841  	return (*pageCache)(c).alloc(npages)
   842  }
   843  func (c *PageCache) Flush(s *PageAlloc) {
   844  	cp := (*pageCache)(c)
   845  	sp := (*pageAlloc)(s)
   846  
   847  	systemstack(func() {
   848  		// None of the tests need any higher-level locking, so we just
   849  		// take the lock internally.
   850  		lock(sp.mheapLock)
   851  		cp.flush(sp)
   852  		unlock(sp.mheapLock)
   853  	})
   854  }
   855  
   856  // Expose chunk index type.
   857  type ChunkIdx chunkIdx
   858  
   859  // Expose pageAlloc for testing. Note that because pageAlloc is
   860  // not in the heap, so is PageAlloc.
   861  type PageAlloc pageAlloc
   862  
   863  func (p *PageAlloc) Alloc(npages uintptr) (uintptr, uintptr) {
   864  	pp := (*pageAlloc)(p)
   865  
   866  	var addr, scav uintptr
   867  	systemstack(func() {
   868  		// None of the tests need any higher-level locking, so we just
   869  		// take the lock internally.
   870  		lock(pp.mheapLock)
   871  		addr, scav = pp.alloc(npages)
   872  		unlock(pp.mheapLock)
   873  	})
   874  	return addr, scav
   875  }
   876  func (p *PageAlloc) AllocToCache() PageCache {
   877  	pp := (*pageAlloc)(p)
   878  
   879  	var c PageCache
   880  	systemstack(func() {
   881  		// None of the tests need any higher-level locking, so we just
   882  		// take the lock internally.
   883  		lock(pp.mheapLock)
   884  		c = PageCache(pp.allocToCache())
   885  		unlock(pp.mheapLock)
   886  	})
   887  	return c
   888  }
   889  func (p *PageAlloc) Free(base, npages uintptr) {
   890  	pp := (*pageAlloc)(p)
   891  
   892  	systemstack(func() {
   893  		// None of the tests need any higher-level locking, so we just
   894  		// take the lock internally.
   895  		lock(pp.mheapLock)
   896  		pp.free(base, npages)
   897  		unlock(pp.mheapLock)
   898  	})
   899  }
   900  func (p *PageAlloc) Bounds() (ChunkIdx, ChunkIdx) {
   901  	return ChunkIdx((*pageAlloc)(p).start), ChunkIdx((*pageAlloc)(p).end)
   902  }
   903  func (p *PageAlloc) Scavenge(nbytes uintptr) (r uintptr) {
   904  	pp := (*pageAlloc)(p)
   905  	systemstack(func() {
   906  		r = pp.scavenge(nbytes, nil, true)
   907  	})
   908  	return
   909  }
   910  func (p *PageAlloc) InUse() []AddrRange {
   911  	ranges := make([]AddrRange, 0, len(p.inUse.ranges))
   912  	for _, r := range p.inUse.ranges {
   913  		ranges = append(ranges, AddrRange{r})
   914  	}
   915  	return ranges
   916  }
   917  
   918  // Returns nil if the PallocData's L2 is missing.
   919  func (p *PageAlloc) PallocData(i ChunkIdx) *PallocData {
   920  	ci := chunkIdx(i)
   921  	return (*PallocData)((*pageAlloc)(p).tryChunkOf(ci))
   922  }
   923  
   924  // AddrRange is a wrapper around addrRange for testing.
   925  type AddrRange struct {
   926  	addrRange
   927  }
   928  
   929  // MakeAddrRange creates a new address range.
   930  func MakeAddrRange(base, limit uintptr) AddrRange {
   931  	return AddrRange{makeAddrRange(base, limit)}
   932  }
   933  
   934  // Base returns the virtual base address of the address range.
   935  func (a AddrRange) Base() uintptr {
   936  	return a.addrRange.base.addr()
   937  }
   938  
   939  // Base returns the virtual address of the limit of the address range.
   940  func (a AddrRange) Limit() uintptr {
   941  	return a.addrRange.limit.addr()
   942  }
   943  
   944  // Equals returns true if the two address ranges are exactly equal.
   945  func (a AddrRange) Equals(b AddrRange) bool {
   946  	return a == b
   947  }
   948  
   949  // Size returns the size in bytes of the address range.
   950  func (a AddrRange) Size() uintptr {
   951  	return a.addrRange.size()
   952  }
   953  
   954  // testSysStat is the sysStat passed to test versions of various
   955  // runtime structures. We do actually have to keep track of this
   956  // because otherwise memstats.mappedReady won't actually line up
   957  // with other stats in the runtime during tests.
   958  var testSysStat = &memstats.other_sys
   959  
   960  // AddrRanges is a wrapper around addrRanges for testing.
   961  type AddrRanges struct {
   962  	addrRanges
   963  	mutable bool
   964  }
   965  
   966  // NewAddrRanges creates a new empty addrRanges.
   967  //
   968  // Note that this initializes addrRanges just like in the
   969  // runtime, so its memory is persistentalloc'd. Call this
   970  // function sparingly since the memory it allocates is
   971  // leaked.
   972  //
   973  // This AddrRanges is mutable, so we can test methods like
   974  // Add.
   975  func NewAddrRanges() AddrRanges {
   976  	r := addrRanges{}
   977  	r.init(testSysStat)
   978  	return AddrRanges{r, true}
   979  }
   980  
   981  // MakeAddrRanges creates a new addrRanges populated with
   982  // the ranges in a.
   983  //
   984  // The returned AddrRanges is immutable, so methods like
   985  // Add will fail.
   986  func MakeAddrRanges(a ...AddrRange) AddrRanges {
   987  	// Methods that manipulate the backing store of addrRanges.ranges should
   988  	// not be used on the result from this function (e.g. add) since they may
   989  	// trigger reallocation. That would normally be fine, except the new
   990  	// backing store won't come from the heap, but from persistentalloc, so
   991  	// we'll leak some memory implicitly.
   992  	ranges := make([]addrRange, 0, len(a))
   993  	total := uintptr(0)
   994  	for _, r := range a {
   995  		ranges = append(ranges, r.addrRange)
   996  		total += r.Size()
   997  	}
   998  	return AddrRanges{addrRanges{
   999  		ranges:     ranges,
  1000  		totalBytes: total,
  1001  		sysStat:    testSysStat,
  1002  	}, false}
  1003  }
  1004  
  1005  // Ranges returns a copy of the ranges described by the
  1006  // addrRanges.
  1007  func (a *AddrRanges) Ranges() []AddrRange {
  1008  	result := make([]AddrRange, 0, len(a.addrRanges.ranges))
  1009  	for _, r := range a.addrRanges.ranges {
  1010  		result = append(result, AddrRange{r})
  1011  	}
  1012  	return result
  1013  }
  1014  
  1015  // FindSucc returns the successor to base. See addrRanges.findSucc
  1016  // for more details.
  1017  func (a *AddrRanges) FindSucc(base uintptr) int {
  1018  	return a.findSucc(base)
  1019  }
  1020  
  1021  // Add adds a new AddrRange to the AddrRanges.
  1022  //
  1023  // The AddrRange must be mutable (i.e. created by NewAddrRanges),
  1024  // otherwise this method will throw.
  1025  func (a *AddrRanges) Add(r AddrRange) {
  1026  	if !a.mutable {
  1027  		throw("attempt to mutate immutable AddrRanges")
  1028  	}
  1029  	a.add(r.addrRange)
  1030  }
  1031  
  1032  // TotalBytes returns the totalBytes field of the addrRanges.
  1033  func (a *AddrRanges) TotalBytes() uintptr {
  1034  	return a.addrRanges.totalBytes
  1035  }
  1036  
  1037  // BitRange represents a range over a bitmap.
  1038  type BitRange struct {
  1039  	I, N uint // bit index and length in bits
  1040  }
  1041  
  1042  // NewPageAlloc creates a new page allocator for testing and
  1043  // initializes it with the scav and chunks maps. Each key in these maps
  1044  // represents a chunk index and each value is a series of bit ranges to
  1045  // set within each bitmap's chunk.
  1046  //
  1047  // The initialization of the pageAlloc preserves the invariant that if a
  1048  // scavenged bit is set the alloc bit is necessarily unset, so some
  1049  // of the bits described by scav may be cleared in the final bitmap if
  1050  // ranges in chunks overlap with them.
  1051  //
  1052  // scav is optional, and if nil, the scavenged bitmap will be cleared
  1053  // (as opposed to all 1s, which it usually is). Furthermore, every
  1054  // chunk index in scav must appear in chunks; ones that do not are
  1055  // ignored.
  1056  func NewPageAlloc(chunks, scav map[ChunkIdx][]BitRange) *PageAlloc {
  1057  	p := new(pageAlloc)
  1058  
  1059  	// We've got an entry, so initialize the pageAlloc.
  1060  	p.init(new(mutex), testSysStat, true)
  1061  	lockInit(p.mheapLock, lockRankMheap)
  1062  	for i, init := range chunks {
  1063  		addr := chunkBase(chunkIdx(i))
  1064  
  1065  		// Mark the chunk's existence in the pageAlloc.
  1066  		systemstack(func() {
  1067  			lock(p.mheapLock)
  1068  			p.grow(addr, pallocChunkBytes)
  1069  			unlock(p.mheapLock)
  1070  		})
  1071  
  1072  		// Initialize the bitmap and update pageAlloc metadata.
  1073  		ci := chunkIndex(addr)
  1074  		chunk := p.chunkOf(ci)
  1075  
  1076  		// Clear all the scavenged bits which grow set.
  1077  		chunk.scavenged.clearRange(0, pallocChunkPages)
  1078  
  1079  		// Simulate the allocation and subsequent free of all pages in
  1080  		// the chunk for the scavenge index. This sets the state equivalent
  1081  		// with all pages within the index being free.
  1082  		p.scav.index.alloc(ci, pallocChunkPages)
  1083  		p.scav.index.free(ci, 0, pallocChunkPages)
  1084  
  1085  		// Apply scavenge state if applicable.
  1086  		if scav != nil {
  1087  			if scvg, ok := scav[i]; ok {
  1088  				for _, s := range scvg {
  1089  					// Ignore the case of s.N == 0. setRange doesn't handle
  1090  					// it and it's a no-op anyway.
  1091  					if s.N != 0 {
  1092  						chunk.scavenged.setRange(s.I, s.N)
  1093  					}
  1094  				}
  1095  			}
  1096  		}
  1097  
  1098  		// Apply alloc state.
  1099  		for _, s := range init {
  1100  			// Ignore the case of s.N == 0. allocRange doesn't handle
  1101  			// it and it's a no-op anyway.
  1102  			if s.N != 0 {
  1103  				chunk.allocRange(s.I, s.N)
  1104  
  1105  				// Make sure the scavenge index is updated.
  1106  				p.scav.index.alloc(ci, s.N)
  1107  			}
  1108  		}
  1109  
  1110  		// Update heap metadata for the allocRange calls above.
  1111  		systemstack(func() {
  1112  			lock(p.mheapLock)
  1113  			p.update(addr, pallocChunkPages, false, false)
  1114  			unlock(p.mheapLock)
  1115  		})
  1116  	}
  1117  
  1118  	return (*PageAlloc)(p)
  1119  }
  1120  
  1121  // FreePageAlloc releases hard OS resources owned by the pageAlloc. Once this
  1122  // is called the pageAlloc may no longer be used. The object itself will be
  1123  // collected by the garbage collector once it is no longer live.
  1124  func FreePageAlloc(pp *PageAlloc) {
  1125  	p := (*pageAlloc)(pp)
  1126  
  1127  	// Free all the mapped space for the summary levels.
  1128  	if pageAlloc64Bit != 0 {
  1129  		for l := 0; l < summaryLevels; l++ {
  1130  			// This isn't quite right, as some of this memory may
  1131  			// be Ready instead of Reserved. The mappedReady and
  1132  			// testSysStat adjustments below correct for the
  1133  			// difference.
  1134  			sysUnreserve(unsafe.Pointer(&p.summary[l][0]), uintptr(cap(p.summary[l]))*pallocSumBytes)
  1135  		}
  1136  	} else {
  1137  		resSize := uintptr(0)
  1138  		for _, s := range p.summary {
  1139  			resSize += uintptr(cap(s)) * pallocSumBytes
  1140  		}
  1141  		// See sysUnreserve comment above.
  1142  		sysUnreserve(unsafe.Pointer(&p.summary[0][0]), alignUp(resSize, physPageSize))
  1143  	}
  1144  
  1145  	// Subtract back out whatever we mapped for the summaries.
  1146  	// sysUsed adds to p.sysStat and memstats.mappedReady no matter what
  1147  	// (and in anger should actually be accounted for), and there's no other
  1148  	// way to figure out how much we actually mapped.
  1149  	gcController.mappedReady.Add(-int64(p.summaryMappedReady))
  1150  	testSysStat.add(-int64(p.summaryMappedReady))
  1151  
  1152  	// Free extra data structures.
  1153  	//
  1154  	// TODO(prattmic): As above, some of this may be Ready, so we should
  1155  	// manually adjust mappedReady and testSysStat?
  1156  	sysUnreserve(unsafe.Pointer(&p.scav.index.chunks[0]), uintptr(cap(p.scav.index.chunks))*unsafe.Sizeof(atomicScavChunkData{}))
  1157  
  1158  	// Free the mapped space for chunks.
  1159  	for i := range p.chunks {
  1160  		if x := p.chunks[i]; x != nil {
  1161  			p.chunks[i] = nil
  1162  			// This memory comes from sysAlloc and will always be page-aligned.
  1163  			sysFree(unsafe.Pointer(x), unsafe.Sizeof(*p.chunks[0]), testSysStat)
  1164  		}
  1165  	}
  1166  }
  1167  
  1168  // BaseChunkIdx is a convenient chunkIdx value which works on both
  1169  // 64 bit and 32 bit platforms, allowing the tests to share code
  1170  // between the two.
  1171  //
  1172  // This should not be higher than 0x100*pallocChunkBytes to support
  1173  // mips and mipsle, which only have 31-bit address spaces.
  1174  var BaseChunkIdx = func() ChunkIdx {
  1175  	var prefix uintptr
  1176  	if pageAlloc64Bit != 0 {
  1177  		prefix = 0xc000
  1178  	} else {
  1179  		prefix = 0x100
  1180  	}
  1181  	baseAddr := prefix * pallocChunkBytes
  1182  	if goos.IsAix != 0 {
  1183  		baseAddr += arenaBaseOffset
  1184  	}
  1185  	return ChunkIdx(chunkIndex(baseAddr))
  1186  }()
  1187  
  1188  // PageBase returns an address given a chunk index and a page index
  1189  // relative to that chunk.
  1190  func PageBase(c ChunkIdx, pageIdx uint) uintptr {
  1191  	return chunkBase(chunkIdx(c)) + uintptr(pageIdx)*pageSize
  1192  }
  1193  
  1194  type BitsMismatch struct {
  1195  	Base      uintptr
  1196  	Got, Want uint64
  1197  }
  1198  
  1199  func CheckScavengedBitsCleared(mismatches []BitsMismatch) (n int, ok bool) {
  1200  	ok = true
  1201  
  1202  	// Run on the system stack to avoid stack growth allocation.
  1203  	systemstack(func() {
  1204  		getg().m.mallocing++
  1205  
  1206  		// Lock so that we can safely access the bitmap.
  1207  		lock(&mheap_.lock)
  1208  
  1209  	chunkLoop:
  1210  		for i := mheap_.pages.start; i < mheap_.pages.end; i++ {
  1211  			chunk := mheap_.pages.tryChunkOf(i)
  1212  			if chunk == nil {
  1213  				continue
  1214  			}
  1215  			cb := chunkBase(i)
  1216  			for j := 0; j < pallocChunkPages/64; j++ {
  1217  				// Run over each 64-bit bitmap section and ensure
  1218  				// scavenged is being cleared properly on allocation.
  1219  				// If a used bit and scavenged bit are both set, that's
  1220  				// an error, and could indicate a larger problem, or
  1221  				// an accounting problem.
  1222  				want := chunk.scavenged[j] &^ chunk.pallocBits[j]
  1223  				got := chunk.scavenged[j]
  1224  				if want != got {
  1225  					ok = false
  1226  					if n >= len(mismatches) {
  1227  						break chunkLoop
  1228  					}
  1229  					mismatches[n] = BitsMismatch{
  1230  						Base: cb + uintptr(j)*64*pageSize,
  1231  						Got:  got,
  1232  						Want: want,
  1233  					}
  1234  					n++
  1235  				}
  1236  			}
  1237  		}
  1238  		unlock(&mheap_.lock)
  1239  
  1240  		getg().m.mallocing--
  1241  	})
  1242  
  1243  	if randomizeHeapBase && len(mismatches) > 0 {
  1244  		// When goexperiment.RandomizedHeapBase64 is set we use a series of
  1245  		// padding pages to generate randomized heap base address which have
  1246  		// both the alloc and scav bits set. Because of this we expect exactly
  1247  		// one arena will have mismatches, so check for that explicitly and
  1248  		// remove the mismatches if that property holds. If we see more than one
  1249  		// arena with this property, that is an indication something has
  1250  		// actually gone wrong, so return the mismatches.
  1251  		//
  1252  		// We do this, instead of ignoring the mismatches in the chunkLoop, because
  1253  		// it's not easy to determine which arena we added the padding pages to
  1254  		// programmatically, without explicitly recording the base address somewhere
  1255  		// in a global variable (which we'd rather not do as the address of that variable
  1256  		// is likely to be somewhat predictable, potentially defeating the purpose
  1257  		// of our randomization).
  1258  		affectedArenas := map[arenaIdx]bool{}
  1259  		for _, mismatch := range mismatches {
  1260  			if mismatch.Base > 0 {
  1261  				affectedArenas[arenaIndex(mismatch.Base)] = true
  1262  			}
  1263  		}
  1264  		if len(affectedArenas) == 1 {
  1265  			ok = true
  1266  			// zero the mismatches
  1267  			for i := range n {
  1268  				mismatches[i] = BitsMismatch{}
  1269  			}
  1270  		}
  1271  	}
  1272  
  1273  	return
  1274  }
  1275  
  1276  func PageCachePagesLeaked() (leaked uintptr) {
  1277  	stw := stopTheWorld(stwForTestPageCachePagesLeaked)
  1278  
  1279  	// Walk over destroyed Ps and look for unflushed caches.
  1280  	deadp := allp[len(allp):cap(allp)]
  1281  	for _, p := range deadp {
  1282  		// Since we're going past len(allp) we may see nil Ps.
  1283  		// Just ignore them.
  1284  		if p != nil {
  1285  			leaked += uintptr(sys.OnesCount64(p.pcache.cache))
  1286  		}
  1287  	}
  1288  
  1289  	startTheWorld(stw)
  1290  	return
  1291  }
  1292  
  1293  var ProcYield = procyield
  1294  var OSYield = osyield
  1295  
  1296  func StealRunnextSleep(ns int64) {
  1297  	systemstack(func() { stealRunnextSleep(ns) })
  1298  }
  1299  
  1300  type Note = note
  1301  
  1302  var NoteClear = noteclear
  1303  var NoteTSleepG = notetsleepg
  1304  
  1305  // NoteTSleepG0 calls notetsleep on the system stack
  1306  func NoteTSleepG0(n *Note, ns int64) bool {
  1307  	var ok bool
  1308  	systemstack(func() {
  1309  		ok = notetsleep(n, ns)
  1310  	})
  1311  	return ok
  1312  }
  1313  
  1314  func Semacreate()            { semacreate(getg().m) }
  1315  func Semasleep(ns int64) int { return int(semasleep(ns)) }
  1316  func SemawakeupSelf()        { semawakeup(getg().m) }
  1317  
  1318  type Mutex = mutex
  1319  
  1320  var Lock = lock
  1321  var Unlock = unlock
  1322  
  1323  var MutexContended = mutexContended
  1324  
  1325  func SemRootLock(addr *uint32) *mutex {
  1326  	root := semtable.rootFor(addr)
  1327  	return &root.lock
  1328  }
  1329  
  1330  var Semacquire = semacquire
  1331  var Semrelease1 = semrelease1
  1332  
  1333  func SemNwait(addr *uint32) uint32 {
  1334  	root := semtable.rootFor(addr)
  1335  	return root.nwait.Load()
  1336  }
  1337  
  1338  const SemTableSize = semTabSize
  1339  
  1340  // SemTable is a wrapper around semTable exported for testing.
  1341  type SemTable struct {
  1342  	semTable
  1343  }
  1344  
  1345  // Enqueue simulates enqueuing a waiter for a semaphore (or lock) at addr.
  1346  func (t *SemTable) Enqueue(addr *uint32) {
  1347  	wg := acquireWaitingG(waitingGTypeSema)
  1348  	wg.releasetime = 0
  1349  	wg.acquiretime = 0
  1350  	wg.ticket = 0
  1351  	t.semTable.rootFor(addr).queue(addr, wg, false)
  1352  }
  1353  
  1354  // Dequeue simulates dequeuing a waiter for a semaphore (or lock) at addr.
  1355  //
  1356  // Returns true if there actually was a waiter to be dequeued.
  1357  func (t *SemTable) Dequeue(addr *uint32) bool {
  1358  	wg, _, _ := t.semTable.rootFor(addr).dequeue(addr)
  1359  	if wg != nil {
  1360  		releaseWaitingG(wg)
  1361  		return true
  1362  	}
  1363  	return false
  1364  }
  1365  
  1366  // mspan wrapper for testing.
  1367  type MSpan mspan
  1368  
  1369  // Allocate an mspan for testing.
  1370  func AllocMSpan() *MSpan {
  1371  	var s *mspan
  1372  	systemstack(func() {
  1373  		lock(&mheap_.lock)
  1374  		s = (*mspan)(mheap_.spanalloc.alloc())
  1375  		s.init(0, 0)
  1376  		unlock(&mheap_.lock)
  1377  	})
  1378  	return (*MSpan)(s)
  1379  }
  1380  
  1381  // Free an allocated mspan.
  1382  func FreeMSpan(s *MSpan) {
  1383  	systemstack(func() {
  1384  		lock(&mheap_.lock)
  1385  		mheap_.spanalloc.free(unsafe.Pointer(s))
  1386  		unlock(&mheap_.lock)
  1387  	})
  1388  }
  1389  
  1390  func MSpanCountAlloc(ms *MSpan, bits []byte) int {
  1391  	s := (*mspan)(ms)
  1392  	s.nelems = uint16(len(bits) * 8)
  1393  	s.gcmarkBits = (*gcBits)(unsafe.Pointer(&bits[0]))
  1394  	result := s.countAlloc()
  1395  	s.gcmarkBits = nil
  1396  	return result
  1397  }
  1398  
  1399  const (
  1400  	TimeHistSubBucketBits = timeHistSubBucketBits
  1401  	TimeHistNumSubBuckets = timeHistNumSubBuckets
  1402  	TimeHistNumBuckets    = timeHistNumBuckets
  1403  	TimeHistMinBucketBits = timeHistMinBucketBits
  1404  	TimeHistMaxBucketBits = timeHistMaxBucketBits
  1405  )
  1406  
  1407  type TimeHistogram timeHistogram
  1408  
  1409  // Count returns the counts for the given bucket, subBucket indices.
  1410  // Returns true if the bucket was valid, otherwise returns the counts
  1411  // for the overflow bucket if bucket > 0 or the underflow bucket if
  1412  // bucket < 0, and false.
  1413  func (th *TimeHistogram) Count(bucket, subBucket int) (uint64, bool) {
  1414  	t := (*timeHistogram)(th)
  1415  	if bucket < 0 {
  1416  		return t.underflow.Load(), false
  1417  	}
  1418  	i := bucket*TimeHistNumSubBuckets + subBucket
  1419  	if i >= len(t.counts) {
  1420  		return t.overflow.Load(), false
  1421  	}
  1422  	return t.counts[i].Load(), true
  1423  }
  1424  
  1425  func (th *TimeHistogram) Record(duration int64) {
  1426  	(*timeHistogram)(th).record(duration)
  1427  }
  1428  
  1429  var TimeHistogramMetricsBuckets = timeHistogramMetricsBuckets
  1430  
  1431  func SetIntArgRegs(a int) int {
  1432  	lock(&finlock)
  1433  	old := intArgRegs
  1434  	if a >= 0 {
  1435  		intArgRegs = a
  1436  	}
  1437  	unlock(&finlock)
  1438  	return old
  1439  }
  1440  
  1441  func FinalizerGAsleep() bool {
  1442  	return fingStatus.Load()&fingWait != 0
  1443  }
  1444  
  1445  // For GCTestMoveStackOnNextCall, it's important not to introduce an
  1446  // extra layer of call, since then there's a return before the "real"
  1447  // next call.
  1448  var GCTestMoveStackOnNextCall = gcTestMoveStackOnNextCall
  1449  
  1450  // For GCTestIsReachable, it's important that we do this as a call so
  1451  // escape analysis can see through it.
  1452  func GCTestIsReachable(ptrs ...unsafe.Pointer) (mask uint64) {
  1453  	return gcTestIsReachable(ptrs...)
  1454  }
  1455  
  1456  // For GCTestPointerClass, it's important that we do this as a call so
  1457  // escape analysis can see through it.
  1458  //
  1459  // This is nosplit because gcTestPointerClass is.
  1460  //
  1461  //go:nosplit
  1462  func GCTestPointerClass(p unsafe.Pointer) string {
  1463  	return gcTestPointerClass(p)
  1464  }
  1465  
  1466  const Raceenabled = raceenabled
  1467  
  1468  const (
  1469  	GCBackgroundUtilization            = gcBackgroundUtilization
  1470  	GCGoalUtilization                  = gcGoalUtilization
  1471  	DefaultHeapMinimum                 = defaultHeapMinimum
  1472  	MemoryLimitHeapGoalHeadroomPercent = memoryLimitHeapGoalHeadroomPercent
  1473  	MemoryLimitMinHeapGoalHeadroom     = memoryLimitMinHeapGoalHeadroom
  1474  )
  1475  
  1476  type GCController struct {
  1477  	gcControllerState
  1478  }
  1479  
  1480  func NewGCController(gcPercent int, memoryLimit int64) *GCController {
  1481  	// Force the controller to escape. We're going to
  1482  	// do 64-bit atomics on it, and if it gets stack-allocated
  1483  	// on a 32-bit architecture, it may get allocated unaligned
  1484  	// space.
  1485  	g := Escape(new(GCController))
  1486  	g.gcControllerState.test = true // Mark it as a test copy.
  1487  	g.init(int32(gcPercent), memoryLimit)
  1488  	return g
  1489  }
  1490  
  1491  func (c *GCController) StartCycle(stackSize, globalsSize uint64, scannableFrac float64, gomaxprocs int) {
  1492  	trigger, _ := c.trigger()
  1493  	if c.heapMarked > trigger {
  1494  		trigger = c.heapMarked
  1495  	}
  1496  	c.maxStackScan.Store(stackSize)
  1497  	c.globalsScan.Store(globalsSize)
  1498  	c.heapLive.Store(trigger)
  1499  	c.heapScan.Add(int64(float64(trigger-c.heapMarked) * scannableFrac))
  1500  	c.startCycle(0, gomaxprocs, gcTrigger{kind: gcTriggerHeap})
  1501  }
  1502  
  1503  func (c *GCController) AssistWorkPerByte() float64 {
  1504  	return c.assistWorkPerByte.Load()
  1505  }
  1506  
  1507  func (c *GCController) HeapGoal() uint64 {
  1508  	return c.heapGoal()
  1509  }
  1510  
  1511  func (c *GCController) HeapLive() uint64 {
  1512  	return c.heapLive.Load()
  1513  }
  1514  
  1515  func (c *GCController) HeapMarked() uint64 {
  1516  	return c.heapMarked
  1517  }
  1518  
  1519  func (c *GCController) Triggered() uint64 {
  1520  	return c.triggered
  1521  }
  1522  
  1523  type GCControllerReviseDelta struct {
  1524  	HeapLive        int64
  1525  	HeapScan        int64
  1526  	HeapScanWork    int64
  1527  	StackScanWork   int64
  1528  	GlobalsScanWork int64
  1529  }
  1530  
  1531  func (c *GCController) Revise(d GCControllerReviseDelta) {
  1532  	c.heapLive.Add(d.HeapLive)
  1533  	c.heapScan.Add(d.HeapScan)
  1534  	c.heapScanWork.Add(d.HeapScanWork)
  1535  	c.stackScanWork.Add(d.StackScanWork)
  1536  	c.globalsScanWork.Add(d.GlobalsScanWork)
  1537  	c.revise()
  1538  }
  1539  
  1540  func (c *GCController) EndCycle(bytesMarked uint64, assistTime, elapsed int64, gomaxprocs int) {
  1541  	c.assistTime.Store(assistTime)
  1542  	c.endCycle(elapsed, gomaxprocs)
  1543  	c.resetLive(bytesMarked)
  1544  	c.commit(false)
  1545  }
  1546  
  1547  func (c *GCController) AddIdleMarkWorker() bool {
  1548  	return c.addIdleMarkWorker()
  1549  }
  1550  
  1551  func (c *GCController) NeedIdleMarkWorker() bool {
  1552  	return c.needIdleMarkWorker()
  1553  }
  1554  
  1555  func (c *GCController) RemoveIdleMarkWorker() {
  1556  	c.removeIdleMarkWorker()
  1557  }
  1558  
  1559  func (c *GCController) SetMaxIdleMarkWorkers(max int32) {
  1560  	c.setMaxIdleMarkWorkers(max)
  1561  }
  1562  
  1563  var alwaysFalse bool
  1564  var escapeSink any
  1565  
  1566  func Escape[T any](x T) T {
  1567  	if alwaysFalse {
  1568  		escapeSink = x
  1569  	}
  1570  	return x
  1571  }
  1572  
  1573  // Acquirem blocks preemption.
  1574  func Acquirem() {
  1575  	acquirem()
  1576  }
  1577  
  1578  func Releasem() {
  1579  	releasem(getg().m)
  1580  }
  1581  
  1582  // GoschedIfBusy is an explicit preemption check to call back
  1583  // into the scheduler. This is useful for tests that run code
  1584  // which spend most of their time as non-preemptible, as it
  1585  // can be placed right after becoming preemptible again to ensure
  1586  // that the scheduler gets a chance to preempt the goroutine.
  1587  func GoschedIfBusy() {
  1588  	goschedIfBusy()
  1589  }
  1590  
  1591  type PIController struct {
  1592  	piController
  1593  }
  1594  
  1595  func NewPIController(kp, ti, tt, min, max float64) *PIController {
  1596  	return &PIController{piController{
  1597  		kp:  kp,
  1598  		ti:  ti,
  1599  		tt:  tt,
  1600  		min: min,
  1601  		max: max,
  1602  	}}
  1603  }
  1604  
  1605  func (c *PIController) Next(input, setpoint, period float64) (float64, bool) {
  1606  	return c.piController.next(input, setpoint, period)
  1607  }
  1608  
  1609  const (
  1610  	CapacityPerProc          = capacityPerProc
  1611  	GCCPULimiterUpdatePeriod = gcCPULimiterUpdatePeriod
  1612  )
  1613  
  1614  type GCCPULimiter struct {
  1615  	limiter gcCPULimiterState
  1616  }
  1617  
  1618  func NewGCCPULimiter(now int64, gomaxprocs int32) *GCCPULimiter {
  1619  	// Force the controller to escape. We're going to
  1620  	// do 64-bit atomics on it, and if it gets stack-allocated
  1621  	// on a 32-bit architecture, it may get allocated unaligned
  1622  	// space.
  1623  	l := Escape(new(GCCPULimiter))
  1624  	l.limiter.test = true
  1625  	l.limiter.resetCapacity(now, gomaxprocs)
  1626  	return l
  1627  }
  1628  
  1629  func (l *GCCPULimiter) Fill() uint64 {
  1630  	return l.limiter.bucket.fill
  1631  }
  1632  
  1633  func (l *GCCPULimiter) Capacity() uint64 {
  1634  	return l.limiter.bucket.capacity
  1635  }
  1636  
  1637  func (l *GCCPULimiter) Overflow() uint64 {
  1638  	return l.limiter.overflow
  1639  }
  1640  
  1641  func (l *GCCPULimiter) Limiting() bool {
  1642  	return l.limiter.limiting()
  1643  }
  1644  
  1645  func (l *GCCPULimiter) NeedUpdate(now int64) bool {
  1646  	return l.limiter.needUpdate(now)
  1647  }
  1648  
  1649  func (l *GCCPULimiter) StartGCTransition(enableGC bool, now int64) {
  1650  	l.limiter.startGCTransition(enableGC, now)
  1651  }
  1652  
  1653  func (l *GCCPULimiter) FinishGCTransition(now int64) {
  1654  	l.limiter.finishGCTransition(now)
  1655  }
  1656  
  1657  func (l *GCCPULimiter) Update(now int64) {
  1658  	l.limiter.update(now)
  1659  }
  1660  
  1661  func (l *GCCPULimiter) AddAssistTime(t int64) {
  1662  	l.limiter.addAssistTime(t)
  1663  }
  1664  
  1665  func (l *GCCPULimiter) ResetCapacity(now int64, nprocs int32) {
  1666  	l.limiter.resetCapacity(now, nprocs)
  1667  }
  1668  
  1669  const ScavengePercent = scavengePercent
  1670  
  1671  type Scavenger struct {
  1672  	Sleep      func(int64) int64
  1673  	Scavenge   func(uintptr) (uintptr, int64)
  1674  	ShouldStop func() bool
  1675  	GoMaxProcs func() int32
  1676  
  1677  	released  atomic.Uintptr
  1678  	scavenger scavengerState
  1679  	stop      chan<- struct{}
  1680  	done      <-chan struct{}
  1681  }
  1682  
  1683  func (s *Scavenger) Start() {
  1684  	if s.Sleep == nil || s.Scavenge == nil || s.ShouldStop == nil || s.GoMaxProcs == nil {
  1685  		panic("must populate all stubs")
  1686  	}
  1687  
  1688  	// Install hooks.
  1689  	s.scavenger.sleepStub = s.Sleep
  1690  	s.scavenger.scavenge = s.Scavenge
  1691  	s.scavenger.shouldStop = s.ShouldStop
  1692  	s.scavenger.gomaxprocs = s.GoMaxProcs
  1693  
  1694  	// Start up scavenger goroutine, and wait for it to be ready.
  1695  	stop := make(chan struct{})
  1696  	s.stop = stop
  1697  	done := make(chan struct{})
  1698  	s.done = done
  1699  	go func() {
  1700  		// This should match bgscavenge, loosely.
  1701  		s.scavenger.init()
  1702  		s.scavenger.park()
  1703  		for {
  1704  			select {
  1705  			case <-stop:
  1706  				close(done)
  1707  				return
  1708  			default:
  1709  			}
  1710  			released, workTime := s.scavenger.run()
  1711  			if released == 0 {
  1712  				s.scavenger.park()
  1713  				continue
  1714  			}
  1715  			s.released.Add(released)
  1716  			s.scavenger.sleep(workTime)
  1717  		}
  1718  	}()
  1719  	if !s.BlockUntilParked(1e9 /* 1 second */) {
  1720  		panic("timed out waiting for scavenger to get ready")
  1721  	}
  1722  }
  1723  
  1724  // BlockUntilParked blocks until the scavenger parks, or until
  1725  // timeout is exceeded. Returns true if the scavenger parked.
  1726  //
  1727  // Note that in testing, parked means something slightly different.
  1728  // In anger, the scavenger parks to sleep, too, but in testing,
  1729  // it only parks when it actually has no work to do.
  1730  func (s *Scavenger) BlockUntilParked(timeout int64) bool {
  1731  	// Just spin, waiting for it to park.
  1732  	//
  1733  	// The actual parking process is racy with respect to
  1734  	// wakeups, which is fine, but for testing we need something
  1735  	// a bit more robust.
  1736  	start := nanotime()
  1737  	for nanotime()-start < timeout {
  1738  		lock(&s.scavenger.lock)
  1739  		parked := s.scavenger.parked
  1740  		unlock(&s.scavenger.lock)
  1741  		if parked {
  1742  			return true
  1743  		}
  1744  		Gosched()
  1745  	}
  1746  	return false
  1747  }
  1748  
  1749  // Released returns how many bytes the scavenger released.
  1750  func (s *Scavenger) Released() uintptr {
  1751  	return s.released.Load()
  1752  }
  1753  
  1754  // Wake wakes up a parked scavenger to keep running.
  1755  func (s *Scavenger) Wake() {
  1756  	s.scavenger.wake()
  1757  }
  1758  
  1759  // Stop cleans up the scavenger's resources. The scavenger
  1760  // must be parked for this to work.
  1761  func (s *Scavenger) Stop() {
  1762  	lock(&s.scavenger.lock)
  1763  	parked := s.scavenger.parked
  1764  	unlock(&s.scavenger.lock)
  1765  	if !parked {
  1766  		panic("tried to clean up scavenger that is not parked")
  1767  	}
  1768  	close(s.stop)
  1769  	s.Wake()
  1770  	<-s.done
  1771  }
  1772  
  1773  type ScavengeIndex struct {
  1774  	i scavengeIndex
  1775  }
  1776  
  1777  func NewScavengeIndex(min, max ChunkIdx) *ScavengeIndex {
  1778  	s := new(ScavengeIndex)
  1779  	// This is a bit lazy but we easily guarantee we'll be able
  1780  	// to reference all the relevant chunks. The worst-case
  1781  	// memory usage here is 512 MiB, but tests generally use
  1782  	// small offsets from BaseChunkIdx, which results in ~100s
  1783  	// of KiB in memory use.
  1784  	//
  1785  	// This may still be worth making better, at least by sharing
  1786  	// this fairly large array across calls with a sync.Pool or
  1787  	// something. Currently, when the tests are run serially,
  1788  	// it takes around 0.5s. Not all that much, but if we have
  1789  	// a lot of tests like this it could add up.
  1790  	s.i.chunks = make([]atomicScavChunkData, max)
  1791  	s.i.min.Store(uintptr(min))
  1792  	s.i.max.Store(uintptr(max))
  1793  	s.i.minHeapIdx.Store(uintptr(min))
  1794  	s.i.test = true
  1795  	return s
  1796  }
  1797  
  1798  func (s *ScavengeIndex) Find(force bool) (ChunkIdx, uint) {
  1799  	ci, off := s.i.find(force)
  1800  	return ChunkIdx(ci), off
  1801  }
  1802  
  1803  func (s *ScavengeIndex) AllocRange(base, limit uintptr) {
  1804  	sc, ec := chunkIndex(base), chunkIndex(limit-1)
  1805  	si, ei := chunkPageIndex(base), chunkPageIndex(limit-1)
  1806  
  1807  	if sc == ec {
  1808  		// The range doesn't cross any chunk boundaries.
  1809  		s.i.alloc(sc, ei+1-si)
  1810  	} else {
  1811  		// The range crosses at least one chunk boundary.
  1812  		s.i.alloc(sc, pallocChunkPages-si)
  1813  		for c := sc + 1; c < ec; c++ {
  1814  			s.i.alloc(c, pallocChunkPages)
  1815  		}
  1816  		s.i.alloc(ec, ei+1)
  1817  	}
  1818  }
  1819  
  1820  func (s *ScavengeIndex) FreeRange(base, limit uintptr) {
  1821  	sc, ec := chunkIndex(base), chunkIndex(limit-1)
  1822  	si, ei := chunkPageIndex(base), chunkPageIndex(limit-1)
  1823  
  1824  	if sc == ec {
  1825  		// The range doesn't cross any chunk boundaries.
  1826  		s.i.free(sc, si, ei+1-si)
  1827  	} else {
  1828  		// The range crosses at least one chunk boundary.
  1829  		s.i.free(sc, si, pallocChunkPages-si)
  1830  		for c := sc + 1; c < ec; c++ {
  1831  			s.i.free(c, 0, pallocChunkPages)
  1832  		}
  1833  		s.i.free(ec, 0, ei+1)
  1834  	}
  1835  }
  1836  
  1837  func (s *ScavengeIndex) ResetSearchAddrs() {
  1838  	for _, a := range []*atomicOffAddr{&s.i.searchAddrBg, &s.i.searchAddrForce} {
  1839  		addr, marked := a.Load()
  1840  		if marked {
  1841  			a.StoreUnmark(addr, addr)
  1842  		}
  1843  		a.Clear()
  1844  	}
  1845  	s.i.freeHWM = minOffAddr
  1846  }
  1847  
  1848  func (s *ScavengeIndex) NextGen() {
  1849  	s.i.nextGen()
  1850  }
  1851  
  1852  func (s *ScavengeIndex) SetEmpty(ci ChunkIdx) {
  1853  	s.i.setEmpty(chunkIdx(ci))
  1854  }
  1855  
  1856  func CheckPackScavChunkData(gen uint32, inUse, lastInUse uint16, flags uint8) bool {
  1857  	sc0 := scavChunkData{
  1858  		gen:            gen,
  1859  		inUse:          inUse,
  1860  		lastInUse:      lastInUse,
  1861  		scavChunkFlags: scavChunkFlags(flags),
  1862  	}
  1863  	scp := sc0.pack()
  1864  	sc1 := unpackScavChunkData(scp)
  1865  	return sc0 == sc1
  1866  }
  1867  
  1868  const GTrackingPeriod = gTrackingPeriod
  1869  
  1870  var ZeroBase = unsafe.Pointer(&zerobase)
  1871  
  1872  const UserArenaChunkBytes = userArenaChunkBytes
  1873  
  1874  type UserArena struct {
  1875  	arena *userArena
  1876  }
  1877  
  1878  func NewUserArena() *UserArena {
  1879  	return &UserArena{newUserArena()}
  1880  }
  1881  
  1882  func (a *UserArena) New(out *any) {
  1883  	i := efaceOf(out)
  1884  	typ := i._type
  1885  	if typ.Kind() != abi.Pointer {
  1886  		panic("new result of non-ptr type")
  1887  	}
  1888  	typ = (*ptrtype)(unsafe.Pointer(typ)).Elem
  1889  	i.data = a.arena.new(typ)
  1890  }
  1891  
  1892  func (a *UserArena) Slice(sl any, cap int) {
  1893  	a.arena.slice(sl, cap)
  1894  }
  1895  
  1896  func (a *UserArena) Free() {
  1897  	a.arena.free()
  1898  }
  1899  
  1900  func GlobalWaitingArenaChunks() int {
  1901  	n := 0
  1902  	systemstack(func() {
  1903  		lock(&mheap_.lock)
  1904  		for s := mheap_.userArena.quarantineList.first; s != nil; s = s.next {
  1905  			n++
  1906  		}
  1907  		unlock(&mheap_.lock)
  1908  	})
  1909  	return n
  1910  }
  1911  
  1912  func UserArenaClone[T any](s T) T {
  1913  	return arena_heapify(s).(T)
  1914  }
  1915  
  1916  var AlignUp = alignUp
  1917  
  1918  func BlockUntilEmptyFinalizerQueue(timeout int64) bool {
  1919  	return blockUntilEmptyFinalizerQueue(timeout)
  1920  }
  1921  
  1922  func BlockUntilEmptyCleanupQueue(timeout int64) bool {
  1923  	return gcCleanups.blockUntilEmpty(timeout)
  1924  }
  1925  
  1926  func FrameStartLine(f *Frame) int {
  1927  	return f.startLine
  1928  }
  1929  
  1930  // PersistentAlloc allocates some memory that lives outside the Go heap.
  1931  // This memory will never be freed; use sparingly.
  1932  func PersistentAlloc(n, align uintptr) unsafe.Pointer {
  1933  	return persistentalloc(n, align, &memstats.other_sys)
  1934  }
  1935  
  1936  const TagAlign = tagAlign
  1937  
  1938  // FPCallers works like Callers and uses frame pointer unwinding to populate
  1939  // pcBuf with the return addresses of the physical frames on the stack.
  1940  func FPCallers(pcBuf []uintptr) int {
  1941  	return fpTracebackPCs(unsafe.Pointer(getfp()), pcBuf)
  1942  }
  1943  
  1944  const FramePointerEnabled = framepointer_enabled
  1945  
  1946  var (
  1947  	IsPinned      = isPinned
  1948  	GetPinCounter = pinnerGetPinCounter
  1949  )
  1950  
  1951  func SetPinnerLeakPanic(f func()) {
  1952  	pinnerLeakPanic = f
  1953  }
  1954  func GetPinnerLeakPanic() func() {
  1955  	return pinnerLeakPanic
  1956  }
  1957  
  1958  var testUintptr uintptr
  1959  
  1960  func MyGenericFunc[T any]() {
  1961  	systemstack(func() {
  1962  		testUintptr = 4
  1963  	})
  1964  }
  1965  
  1966  func UnsafePoint(pc uintptr) bool {
  1967  	fi := findfunc(pc)
  1968  	v := pcdatavalue(fi, abi.PCDATA_UnsafePoint, pc)
  1969  	switch v {
  1970  	case abi.UnsafePointUnsafe:
  1971  		return true
  1972  	case abi.UnsafePointSafe:
  1973  		return false
  1974  	case abi.UnsafePointRestart1, abi.UnsafePointRestart2, abi.UnsafePointRestartAtEntry:
  1975  		// These are all interruptible, they just encode a nonstandard
  1976  		// way of recovering when interrupted.
  1977  		return false
  1978  	default:
  1979  		var buf [20]byte
  1980  		panic("invalid unsafe point code " + string(itoa(buf[:], uint64(v))))
  1981  	}
  1982  }
  1983  
  1984  type TraceMap struct {
  1985  	traceMap
  1986  }
  1987  
  1988  func (m *TraceMap) PutString(s string) (uint64, bool) {
  1989  	return m.traceMap.put(unsafe.Pointer(unsafe.StringData(s)), uintptr(len(s)))
  1990  }
  1991  
  1992  func (m *TraceMap) Reset() {
  1993  	m.traceMap.reset()
  1994  }
  1995  
  1996  func SetSpinInGCMarkDone(spin bool) {
  1997  	gcDebugMarkDone.spinAfterRaggedBarrier.Store(spin)
  1998  }
  1999  
  2000  func GCMarkDoneRestarted() bool {
  2001  	// Only read this outside of the GC. If we're running during a GC, just report false.
  2002  	mp := acquirem()
  2003  	if gcphase != _GCoff {
  2004  		releasem(mp)
  2005  		return false
  2006  	}
  2007  	restarted := gcDebugMarkDone.restartedDueTo27993
  2008  	releasem(mp)
  2009  	return restarted
  2010  }
  2011  
  2012  func GCMarkDoneResetRestartFlag() {
  2013  	mp := acquirem()
  2014  	for gcphase != _GCoff {
  2015  		releasem(mp)
  2016  		Gosched()
  2017  		mp = acquirem()
  2018  	}
  2019  	gcDebugMarkDone.restartedDueTo27993 = false
  2020  	releasem(mp)
  2021  }
  2022  
  2023  type BitCursor struct {
  2024  	b bitCursor
  2025  }
  2026  
  2027  func NewBitCursor(buf *byte) BitCursor {
  2028  	return BitCursor{b: bitCursor{ptr: buf, n: 0}}
  2029  }
  2030  
  2031  func (b BitCursor) Write(data *byte, cnt uintptr) {
  2032  	b.b.write(data, cnt)
  2033  }
  2034  func (b BitCursor) Offset(cnt uintptr) BitCursor {
  2035  	return BitCursor{b: b.b.offset(cnt)}
  2036  }
  2037  
  2038  const (
  2039  	BubbleAssocUnbubbled     = bubbleAssocUnbubbled
  2040  	BubbleAssocCurrentBubble = bubbleAssocCurrentBubble
  2041  	BubbleAssocOtherBubble   = bubbleAssocOtherBubble
  2042  )
  2043  
  2044  type TraceStackTable traceStackTable
  2045  
  2046  func (t *TraceStackTable) Reset() {
  2047  	t.tab.reset()
  2048  }
  2049  
  2050  func TraceStack(gp *G, tab *TraceStackTable) {
  2051  	traceStack(0, gp, (*traceStackTable)(tab))
  2052  }
  2053  
  2054  var X86HasAVX = &x86HasAVX
  2055  
  2056  var DebugDecorateMappings = &debug.decoratemappings
  2057  
  2058  func SetVMANameSupported() bool { return setVMANameSupported() }
  2059  
  2060  type ListHead struct {
  2061  	l listHead
  2062  }
  2063  
  2064  func (head *ListHead) Init(off uintptr) {
  2065  	head.l.init(off)
  2066  }
  2067  
  2068  type ListNode struct {
  2069  	l listNode
  2070  }
  2071  
  2072  func (head *ListHead) Push(p unsafe.Pointer) {
  2073  	head.l.push(p)
  2074  }
  2075  
  2076  func (head *ListHead) Pop() unsafe.Pointer {
  2077  	return head.l.pop()
  2078  }
  2079  
  2080  func (head *ListHead) Remove(p unsafe.Pointer) {
  2081  	head.l.remove(p)
  2082  }
  2083  
  2084  type ListHeadManual struct {
  2085  	l listHeadManual
  2086  }
  2087  
  2088  func (head *ListHeadManual) Init(off uintptr) {
  2089  	head.l.init(off)
  2090  }
  2091  
  2092  type ListNodeManual struct {
  2093  	l listNodeManual
  2094  }
  2095  
  2096  func (head *ListHeadManual) Push(p unsafe.Pointer) {
  2097  	head.l.push(p)
  2098  }
  2099  
  2100  func (head *ListHeadManual) Pop() unsafe.Pointer {
  2101  	return head.l.pop()
  2102  }
  2103  
  2104  func (head *ListHeadManual) Remove(p unsafe.Pointer) {
  2105  	head.l.remove(p)
  2106  }
  2107  
  2108  // capturePrint calls f. Any print output of f is appended to buf and
  2109  // returned. Output that does not fit in cap(buf) is dropped.
  2110  func capturePrint(buf []byte, f func()) []byte {
  2111  	// The goroutine must stay on this M while writebufg is set.
  2112  	mp := acquirem()
  2113  	mp.writebuf = buf
  2114  	mp.writebufg.set(getg())
  2115  	f()
  2116  	buf = mp.writebuf
  2117  	mp.writebuf = nil
  2118  	mp.writebufg = 0
  2119  	releasem(mp)
  2120  	return buf
  2121  }
  2122  
  2123  func Hexdumper(base uintptr, wordBytes int, mark func(addr uintptr, start func()), data ...[]byte) string {
  2124  	buf := capturePrint(make([]byte, 0, 2048), func() {
  2125  		h := hexdumper{addr: base, addrBytes: 4, wordBytes: uint8(wordBytes)}
  2126  		if mark != nil {
  2127  			h.mark = func(addr uintptr, m hexdumpMarker) {
  2128  				mark(addr, m.start)
  2129  			}
  2130  		}
  2131  		for _, d := range data {
  2132  			h.write(d)
  2133  		}
  2134  		h.close()
  2135  	})
  2136  	if len(buf) == cap(buf) {
  2137  		panic("Hexdumper buf too small")
  2138  	}
  2139  	return string(buf)
  2140  }
  2141  
  2142  func HexdumpWords(p, bytes uintptr) string {
  2143  	buf := capturePrint(make([]byte, 0, 2048), func() {
  2144  		hexdumpWords(p, bytes, nil)
  2145  	})
  2146  	if len(buf) == cap(buf) {
  2147  		panic("HexdumpWords buf too small")
  2148  	}
  2149  	return string(buf)
  2150  }
  2151  
  2152  // DumpPrintQuoted provides access to print(quoted()) for the tests in
  2153  // runtime/print_quoted_test.go, allowing us to test that implementation.
  2154  func DumpPrintQuoted(s string) string {
  2155  	buf := capturePrint(make([]byte, 0, 1<<20), func() {
  2156  		print(quoted(s))
  2157  	})
  2158  	return string(buf)
  2159  }
  2160  
  2161  // PrintBacklog returns a copy of the runtime's print backlog.
  2162  func PrintBacklog() []byte {
  2163  	b := make([]byte, len(printBacklog))
  2164  	printlock()
  2165  	copy(b, printBacklog[:])
  2166  	printunlock()
  2167  	return b
  2168  }
  2169  
  2170  // DumpPrint returns the output of print(v).
  2171  func DumpPrint[T any](v T) string {
  2172  	buf := capturePrint(make([]byte, 0, 2048), func() {
  2173  		print(v)
  2174  	})
  2175  	return string(buf)
  2176  }
  2177  
  2178  var (
  2179  	Float64Bytes    = float64Bytes
  2180  	Float32Bytes    = float32Bytes
  2181  	Complex128Bytes = complex128Bytes
  2182  	Complex64Bytes  = complex64Bytes
  2183  )
  2184  
  2185  func GetScanAlloc() uintptr {
  2186  	c := getMCache(getg().m)
  2187  	return c.scanAlloc
  2188  }
  2189  
  2190  func MallocGC(size uintptr, typ *abi.Type, needzero bool) unsafe.Pointer {
  2191  	return mallocgc(size, typ, needzero)
  2192  }
  2193  
  2194  // AllocSize returns how many bytes mallocgc uses for an object of the given
  2195  // size of a type that contains pointers: the size of its size class,
  2196  // including the malloc header if the object has one. A large object has no
  2197  // size class, and the result is its size rounded up to a page.
  2198  func AllocSize(size uintptr) uintptr {
  2199  	if size <= maxSmallSize-gc.MallocHeaderSize && !heapBitsInSpan(size) {
  2200  		// roundupsize subtracts the malloc header from the size class.
  2201  		return roundupsize(size, false) + gc.MallocHeaderSize
  2202  	}
  2203  	return roundupsize(size, false)
  2204  }
  2205  
  2206  func FuncNamePiecesForPrint(name string) (string, string, string, string, string) {
  2207  	return funcNamePiecesForPrint(name)
  2208  }
  2209  
  2210  var InHeapOrStack = inHeapOrStack
  2211  
  2212  func SysRSS() (rss, shared uint64, hasShared bool) { return sysRSS() }
  2213  

View as plain text