github.com/ice-blockchain/go/src@v0.0.0-20240403114104-1564d284e521/runtime/trace.go (about) 1 // Copyright 2014 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 //go:build !goexperiment.exectracer2 6 7 // Go execution tracer. 8 // The tracer captures a wide range of execution events like goroutine 9 // creation/blocking/unblocking, syscall enter/exit/block, GC-related events, 10 // changes of heap size, processor start/stop, etc and writes them to a buffer 11 // in a compact form. A precise nanosecond-precision timestamp and a stack 12 // trace is captured for most events. 13 // See https://golang.org/s/go15trace for more info. 14 15 package runtime 16 17 import ( 18 "internal/abi" 19 "internal/goarch" 20 "internal/goos" 21 "runtime/internal/atomic" 22 "runtime/internal/sys" 23 "unsafe" 24 ) 25 26 // Event types in the trace, args are given in square brackets. 27 const ( 28 traceEvNone = 0 // unused 29 traceEvBatch = 1 // start of per-P batch of events [pid, timestamp] 30 traceEvFrequency = 2 // contains tracer timer frequency [frequency (ticks per second)] 31 traceEvStack = 3 // stack [stack id, number of PCs, array of {PC, func string ID, file string ID, line}] 32 traceEvGomaxprocs = 4 // current value of GOMAXPROCS [timestamp, GOMAXPROCS, stack id] 33 traceEvProcStart = 5 // start of P [timestamp, thread id] 34 traceEvProcStop = 6 // stop of P [timestamp] 35 traceEvGCStart = 7 // GC start [timestamp, seq, stack id] 36 traceEvGCDone = 8 // GC done [timestamp] 37 traceEvSTWStart = 9 // STW start [timestamp, kind] 38 traceEvSTWDone = 10 // STW done [timestamp] 39 traceEvGCSweepStart = 11 // GC sweep start [timestamp, stack id] 40 traceEvGCSweepDone = 12 // GC sweep done [timestamp, swept, reclaimed] 41 traceEvGoCreate = 13 // goroutine creation [timestamp, new goroutine id, new stack id, stack id] 42 traceEvGoStart = 14 // goroutine starts running [timestamp, goroutine id, seq] 43 traceEvGoEnd = 15 // goroutine ends [timestamp] 44 traceEvGoStop = 16 // goroutine stops (like in select{}) [timestamp, stack] 45 traceEvGoSched = 17 // goroutine calls Gosched [timestamp, stack] 46 traceEvGoPreempt = 18 // goroutine is preempted [timestamp, stack] 47 traceEvGoSleep = 19 // goroutine calls Sleep [timestamp, stack] 48 traceEvGoBlock = 20 // goroutine blocks [timestamp, stack] 49 traceEvGoUnblock = 21 // goroutine is unblocked [timestamp, goroutine id, seq, stack] 50 traceEvGoBlockSend = 22 // goroutine blocks on chan send [timestamp, stack] 51 traceEvGoBlockRecv = 23 // goroutine blocks on chan recv [timestamp, stack] 52 traceEvGoBlockSelect = 24 // goroutine blocks on select [timestamp, stack] 53 traceEvGoBlockSync = 25 // goroutine blocks on Mutex/RWMutex [timestamp, stack] 54 traceEvGoBlockCond = 26 // goroutine blocks on Cond [timestamp, stack] 55 traceEvGoBlockNet = 27 // goroutine blocks on network [timestamp, stack] 56 traceEvGoSysCall = 28 // syscall enter [timestamp, stack] 57 traceEvGoSysExit = 29 // syscall exit [timestamp, goroutine id, seq, real timestamp] 58 traceEvGoSysBlock = 30 // syscall blocks [timestamp] 59 traceEvGoWaiting = 31 // denotes that goroutine is blocked when tracing starts [timestamp, goroutine id] 60 traceEvGoInSyscall = 32 // denotes that goroutine is in syscall when tracing starts [timestamp, goroutine id] 61 traceEvHeapAlloc = 33 // gcController.heapLive change [timestamp, heap_alloc] 62 traceEvHeapGoal = 34 // gcController.heapGoal() (formerly next_gc) change [timestamp, heap goal in bytes] 63 traceEvTimerGoroutine = 35 // not currently used; previously denoted timer goroutine [timer goroutine id] 64 traceEvFutileWakeup = 36 // not currently used; denotes that the previous wakeup of this goroutine was futile [timestamp] 65 traceEvString = 37 // string dictionary entry [ID, length, string] 66 traceEvGoStartLocal = 38 // goroutine starts running on the same P as the last event [timestamp, goroutine id] 67 traceEvGoUnblockLocal = 39 // goroutine is unblocked on the same P as the last event [timestamp, goroutine id, stack] 68 traceEvGoSysExitLocal = 40 // syscall exit on the same P as the last event [timestamp, goroutine id, real timestamp] 69 traceEvGoStartLabel = 41 // goroutine starts running with label [timestamp, goroutine id, seq, label string id] 70 traceEvGoBlockGC = 42 // goroutine blocks on GC assist [timestamp, stack] 71 traceEvGCMarkAssistStart = 43 // GC mark assist start [timestamp, stack] 72 traceEvGCMarkAssistDone = 44 // GC mark assist done [timestamp] 73 traceEvUserTaskCreate = 45 // trace.NewTask [timestamp, internal task id, internal parent task id, name string, stack] 74 traceEvUserTaskEnd = 46 // end of a task [timestamp, internal task id, stack] 75 traceEvUserRegion = 47 // trace.WithRegion [timestamp, internal task id, mode(0:start, 1:end), name string, stack] 76 traceEvUserLog = 48 // trace.Log [timestamp, internal task id, key string id, stack, value string] 77 traceEvCPUSample = 49 // CPU profiling sample [timestamp, real timestamp, real P id (-1 when absent), goroutine id, stack] 78 traceEvCount = 50 79 // Byte is used but only 6 bits are available for event type. 80 // The remaining 2 bits are used to specify the number of arguments. 81 // That means, the max event type value is 63. 82 ) 83 84 // traceBlockReason is an enumeration of reasons a goroutine might block. 85 // This is the interface the rest of the runtime uses to tell the 86 // tracer why a goroutine blocked. The tracer then propagates this information 87 // into the trace however it sees fit. 88 // 89 // Note that traceBlockReasons should not be compared, since reasons that are 90 // distinct by name may *not* be distinct by value. 91 type traceBlockReason uint8 92 93 // For maximal efficiency, just map the trace block reason directly to a trace 94 // event. 95 const ( 96 traceBlockGeneric traceBlockReason = traceEvGoBlock 97 traceBlockForever = traceEvGoStop 98 traceBlockNet = traceEvGoBlockNet 99 traceBlockSelect = traceEvGoBlockSelect 100 traceBlockCondWait = traceEvGoBlockCond 101 traceBlockSync = traceEvGoBlockSync 102 traceBlockChanSend = traceEvGoBlockSend 103 traceBlockChanRecv = traceEvGoBlockRecv 104 traceBlockGCMarkAssist = traceEvGoBlockGC 105 traceBlockGCSweep = traceEvGoBlock 106 traceBlockSystemGoroutine = traceEvGoBlock 107 traceBlockPreempted = traceEvGoBlock 108 traceBlockDebugCall = traceEvGoBlock 109 traceBlockUntilGCEnds = traceEvGoBlock 110 traceBlockSleep = traceEvGoSleep 111 ) 112 113 const ( 114 // Timestamps in trace are cputicks/traceTickDiv. 115 // This makes absolute values of timestamp diffs smaller, 116 // and so they are encoded in less number of bytes. 117 // 64 on x86 is somewhat arbitrary (one tick is ~20ns on a 3GHz machine). 118 // The suggested increment frequency for PowerPC's time base register is 119 // 512 MHz according to Power ISA v2.07 section 6.2, so we use 16 on ppc64 120 // and ppc64le. 121 traceTimeDiv = 16 + 48*(goarch.Is386|goarch.IsAmd64) 122 // Maximum number of PCs in a single stack trace. 123 // Since events contain only stack id rather than whole stack trace, 124 // we can allow quite large values here. 125 traceStackSize = 128 126 // Identifier of a fake P that is used when we trace without a real P. 127 traceGlobProc = -1 128 // Maximum number of bytes to encode uint64 in base-128. 129 traceBytesPerNumber = 10 130 // Shift of the number of arguments in the first event byte. 131 traceArgCountShift = 6 132 ) 133 134 // trace is global tracing context. 135 var trace struct { 136 // trace.lock must only be acquired on the system stack where 137 // stack splits cannot happen while it is held. 138 lock mutex // protects the following members 139 enabled bool // when set runtime traces events 140 shutdown bool // set when we are waiting for trace reader to finish after setting enabled to false 141 headerWritten bool // whether ReadTrace has emitted trace header 142 footerWritten bool // whether ReadTrace has emitted trace footer 143 shutdownSema uint32 // used to wait for ReadTrace completion 144 seqStart uint64 // sequence number when tracing was started 145 startTicks int64 // cputicks when tracing was started 146 endTicks int64 // cputicks when tracing was stopped 147 startNanotime int64 // nanotime when tracing was started 148 endNanotime int64 // nanotime when tracing was stopped 149 startTime traceTime // traceClockNow when tracing started 150 endTime traceTime // traceClockNow when tracing stopped 151 seqGC uint64 // GC start/done sequencer 152 reading traceBufPtr // buffer currently handed off to user 153 empty traceBufPtr // stack of empty buffers 154 fullHead traceBufPtr // queue of full buffers 155 fullTail traceBufPtr 156 stackTab traceStackTable // maps stack traces to unique ids 157 // cpuLogRead accepts CPU profile samples from the signal handler where 158 // they're generated. It uses a two-word header to hold the IDs of the P and 159 // G (respectively) that were active at the time of the sample. Because 160 // profBuf uses a record with all zeros in its header to indicate overflow, 161 // we make sure to make the P field always non-zero: The ID of a real P will 162 // start at bit 1, and bit 0 will be set. Samples that arrive while no P is 163 // running (such as near syscalls) will set the first header field to 0b10. 164 // This careful handling of the first header field allows us to store ID of 165 // the active G directly in the second field, even though that will be 0 166 // when sampling g0. 167 cpuLogRead *profBuf 168 // cpuLogBuf is a trace buffer to hold events corresponding to CPU profile 169 // samples, which arrive out of band and not directly connected to a 170 // specific P. 171 cpuLogBuf traceBufPtr 172 173 reader atomic.Pointer[g] // goroutine that called ReadTrace, or nil 174 175 signalLock atomic.Uint32 // protects use of the following member, only usable in signal handlers 176 cpuLogWrite *profBuf // copy of cpuLogRead for use in signal handlers, set without signalLock 177 178 // Dictionary for traceEvString. 179 // 180 // TODO: central lock to access the map is not ideal. 181 // option: pre-assign ids to all user annotation region names and tags 182 // option: per-P cache 183 // option: sync.Map like data structure 184 stringsLock mutex 185 strings map[string]uint64 186 stringSeq uint64 187 188 // markWorkerLabels maps gcMarkWorkerMode to string ID. 189 markWorkerLabels [len(gcMarkWorkerModeStrings)]uint64 190 191 bufLock mutex // protects buf 192 buf traceBufPtr // global trace buffer, used when running without a p 193 } 194 195 // gTraceState is per-G state for the tracer. 196 type gTraceState struct { 197 sysExitTime traceTime // timestamp when syscall has returned 198 tracedSyscallEnter bool // syscall or cgo was entered while trace was enabled or StartTrace has emitted EvGoInSyscall about this goroutine 199 seq uint64 // trace event sequencer 200 lastP puintptr // last P emitted an event for this goroutine 201 } 202 203 // Unused; for compatibility with the new tracer. 204 func (s *gTraceState) reset() {} 205 206 // mTraceState is per-M state for the tracer. 207 type mTraceState struct { 208 startingTrace bool // this M is in TraceStart, potentially before traceEnabled is true 209 tracedSTWStart bool // this M traced a STW start, so it should trace an end 210 } 211 212 // pTraceState is per-P state for the tracer. 213 type pTraceState struct { 214 buf traceBufPtr 215 216 // inSweep indicates the sweep events should be traced. 217 // This is used to defer the sweep start event until a span 218 // has actually been swept. 219 inSweep bool 220 221 // swept and reclaimed track the number of bytes swept and reclaimed 222 // by sweeping in the current sweep loop (while inSweep was true). 223 swept, reclaimed uintptr 224 } 225 226 // traceLockInit initializes global trace locks. 227 func traceLockInit() { 228 lockInit(&trace.bufLock, lockRankTraceBuf) 229 lockInit(&trace.stringsLock, lockRankTraceStrings) 230 lockInit(&trace.lock, lockRankTrace) 231 lockInit(&trace.stackTab.lock, lockRankTraceStackTab) 232 } 233 234 // traceBufHeader is per-P tracing buffer. 235 type traceBufHeader struct { 236 link traceBufPtr // in trace.empty/full 237 lastTime traceTime // when we wrote the last event 238 pos int // next write offset in arr 239 stk [traceStackSize]uintptr // scratch buffer for traceback 240 } 241 242 // traceBuf is per-P tracing buffer. 243 type traceBuf struct { 244 _ sys.NotInHeap 245 traceBufHeader 246 arr [64<<10 - unsafe.Sizeof(traceBufHeader{})]byte // underlying buffer for traceBufHeader.buf 247 } 248 249 // traceBufPtr is a *traceBuf that is not traced by the garbage 250 // collector and doesn't have write barriers. traceBufs are not 251 // allocated from the GC'd heap, so this is safe, and are often 252 // manipulated in contexts where write barriers are not allowed, so 253 // this is necessary. 254 // 255 // TODO: Since traceBuf is now embedded runtime/internal/sys.NotInHeap, this isn't necessary. 256 type traceBufPtr uintptr 257 258 func (tp traceBufPtr) ptr() *traceBuf { return (*traceBuf)(unsafe.Pointer(tp)) } 259 func (tp *traceBufPtr) set(b *traceBuf) { *tp = traceBufPtr(unsafe.Pointer(b)) } 260 func traceBufPtrOf(b *traceBuf) traceBufPtr { 261 return traceBufPtr(unsafe.Pointer(b)) 262 } 263 264 // traceEnabled returns true if the trace is currently enabled. 265 // 266 // nosplit because it's called on the syscall path when stack movement is forbidden. 267 // 268 //go:nosplit 269 func traceEnabled() bool { 270 return trace.enabled 271 } 272 273 // traceShuttingDown returns true if the trace is currently shutting down. 274 // 275 //go:nosplit 276 func traceShuttingDown() bool { 277 return trace.shutdown 278 } 279 280 // traceLocker represents an M writing trace events. While a traceLocker value 281 // is valid, the tracer observes all operations on the G/M/P or trace events being 282 // written as happening atomically. 283 // 284 // This doesn't do much for the current tracer, because the current tracer doesn't 285 // need atomicity around non-trace runtime operations. All the state it needs it 286 // collects carefully during a STW. 287 type traceLocker struct { 288 enabled bool 289 } 290 291 // traceAcquire prepares this M for writing one or more trace events. 292 // 293 // This exists for compatibility with the upcoming new tracer; it doesn't do much 294 // in the current tracer. 295 // 296 // nosplit because it's called on the syscall path when stack movement is forbidden. 297 // 298 //go:nosplit 299 func traceAcquire() traceLocker { 300 if !traceEnabled() { 301 return traceLocker{false} 302 } 303 return traceLocker{true} 304 } 305 306 // ok returns true if the traceLocker is valid (i.e. tracing is enabled). 307 // 308 // nosplit because it's called on the syscall path when stack movement is forbidden. 309 // 310 //go:nosplit 311 func (tl traceLocker) ok() bool { 312 return tl.enabled 313 } 314 315 // traceRelease indicates that this M is done writing trace events. 316 // 317 // This exists for compatibility with the upcoming new tracer; it doesn't do anything 318 // in the current tracer. 319 // 320 // nosplit because it's called on the syscall path when stack movement is forbidden. 321 // 322 //go:nosplit 323 func traceRelease(tl traceLocker) { 324 } 325 326 // StartTrace enables tracing for the current process. 327 // While tracing, the data will be buffered and available via [ReadTrace]. 328 // StartTrace returns an error if tracing is already enabled. 329 // Most clients should use the [runtime/trace] package or the [testing] package's 330 // -test.trace flag instead of calling StartTrace directly. 331 func StartTrace() error { 332 // Stop the world so that we can take a consistent snapshot 333 // of all goroutines at the beginning of the trace. 334 // Do not stop the world during GC so we ensure we always see 335 // a consistent view of GC-related events (e.g. a start is always 336 // paired with an end). 337 stw := stopTheWorldGC(stwStartTrace) 338 339 // Prevent sysmon from running any code that could generate events. 340 lock(&sched.sysmonlock) 341 342 // We are in stop-the-world, but syscalls can finish and write to trace concurrently. 343 // Exitsyscall could check trace.enabled long before and then suddenly wake up 344 // and decide to write to trace at a random point in time. 345 // However, such syscall will use the global trace.buf buffer, because we've 346 // acquired all p's by doing stop-the-world. So this protects us from such races. 347 lock(&trace.bufLock) 348 349 if trace.enabled || trace.shutdown { 350 unlock(&trace.bufLock) 351 unlock(&sched.sysmonlock) 352 startTheWorldGC(stw) 353 return errorString("tracing is already enabled") 354 } 355 356 // Can't set trace.enabled yet. While the world is stopped, exitsyscall could 357 // already emit a delayed event (see exitTicks in exitsyscall) if we set trace.enabled here. 358 // That would lead to an inconsistent trace: 359 // - either GoSysExit appears before EvGoInSyscall, 360 // - or GoSysExit appears for a goroutine for which we don't emit EvGoInSyscall below. 361 // To instruct traceEvent that it must not ignore events below, we set trace.startingTrace. 362 // trace.enabled is set afterwards once we have emitted all preliminary events. 363 mp := getg().m 364 mp.trace.startingTrace = true 365 366 // Obtain current stack ID to use in all traceEvGoCreate events below. 367 stkBuf := make([]uintptr, traceStackSize) 368 stackID := traceStackID(mp, stkBuf, 2) 369 370 profBuf := newProfBuf(2, profBufWordCount, profBufTagCount) // after the timestamp, header is [pp.id, gp.goid] 371 trace.cpuLogRead = profBuf 372 373 // We must not acquire trace.signalLock outside of a signal handler: a 374 // profiling signal may arrive at any time and try to acquire it, leading to 375 // deadlock. Because we can't use that lock to protect updates to 376 // trace.cpuLogWrite (only use of the structure it references), reads and 377 // writes of the pointer must be atomic. (And although this field is never 378 // the sole pointer to the profBuf value, it's best to allow a write barrier 379 // here.) 380 atomicstorep(unsafe.Pointer(&trace.cpuLogWrite), unsafe.Pointer(profBuf)) 381 382 // World is stopped, no need to lock. 383 forEachGRace(func(gp *g) { 384 status := readgstatus(gp) 385 if status != _Gdead { 386 gp.trace.seq = 0 387 gp.trace.lastP = getg().m.p 388 // +PCQuantum because traceFrameForPC expects return PCs and subtracts PCQuantum. 389 id := trace.stackTab.put([]uintptr{logicalStackSentinel, startPCforTrace(gp.startpc) + sys.PCQuantum}) 390 traceEvent(traceEvGoCreate, -1, gp.goid, uint64(id), stackID) 391 } 392 if status == _Gwaiting { 393 // traceEvGoWaiting is implied to have seq=1. 394 gp.trace.seq++ 395 traceEvent(traceEvGoWaiting, -1, gp.goid) 396 } 397 if status == _Gsyscall { 398 gp.trace.seq++ 399 gp.trace.tracedSyscallEnter = true 400 traceEvent(traceEvGoInSyscall, -1, gp.goid) 401 } else if status == _Gdead && gp.m != nil && gp.m.isextra { 402 // Trigger two trace events for the dead g in the extra m, 403 // since the next event of the g will be traceEvGoSysExit in exitsyscall, 404 // while calling from C thread to Go. 405 gp.trace.seq = 0 406 gp.trace.lastP = getg().m.p 407 // +PCQuantum because traceFrameForPC expects return PCs and subtracts PCQuantum. 408 id := trace.stackTab.put([]uintptr{logicalStackSentinel, startPCforTrace(0) + sys.PCQuantum}) // no start pc 409 traceEvent(traceEvGoCreate, -1, gp.goid, uint64(id), stackID) 410 gp.trace.seq++ 411 gp.trace.tracedSyscallEnter = true 412 traceEvent(traceEvGoInSyscall, -1, gp.goid) 413 } else { 414 // We need to explicitly clear the flag. A previous trace might have ended with a goroutine 415 // not emitting a GoSysExit and clearing the flag, leaving it in a stale state. Clearing 416 // it here makes it unambiguous to any goroutine exiting a syscall racing with us that 417 // no EvGoInSyscall event was emitted for it. (It's not racy to set this flag here, because 418 // it'll only get checked when the goroutine runs again, which will be after the world starts 419 // again.) 420 gp.trace.tracedSyscallEnter = false 421 } 422 }) 423 // Use a dummy traceLocker. The trace isn't enabled yet, but we can still write events. 424 tl := traceLocker{} 425 tl.ProcStart() 426 tl.GoStart() 427 // Note: startTicks needs to be set after we emit traceEvGoInSyscall events. 428 // If we do it the other way around, it is possible that exitsyscall will 429 // query sysExitTime after startTicks but before traceEvGoInSyscall timestamp. 430 // It will lead to a false conclusion that cputicks is broken. 431 trace.startTime = traceClockNow() 432 trace.startTicks = cputicks() 433 trace.startNanotime = nanotime() 434 trace.headerWritten = false 435 trace.footerWritten = false 436 437 // string to id mapping 438 // 0 : reserved for an empty string 439 // remaining: other strings registered by traceString 440 trace.stringSeq = 0 441 trace.strings = make(map[string]uint64) 442 443 trace.seqGC = 0 444 mp.trace.startingTrace = false 445 trace.enabled = true 446 447 // Register runtime goroutine labels. 448 _, pid, bufp := traceAcquireBuffer() 449 for i, label := range gcMarkWorkerModeStrings[:] { 450 trace.markWorkerLabels[i], bufp = traceString(bufp, pid, label) 451 } 452 traceReleaseBuffer(mp, pid) 453 454 unlock(&trace.bufLock) 455 456 unlock(&sched.sysmonlock) 457 458 // Record the current state of HeapGoal to avoid information loss in trace. 459 // 460 // Use the same dummy trace locker. The trace can't end until after we start 461 // the world, and we can safely trace from here. 462 tl.HeapGoal() 463 464 startTheWorldGC(stw) 465 return nil 466 } 467 468 // StopTrace stops tracing, if it was previously enabled. 469 // StopTrace only returns after all the reads for the trace have completed. 470 func StopTrace() { 471 // Stop the world so that we can collect the trace buffers from all p's below, 472 // and also to avoid races with traceEvent. 473 stw := stopTheWorldGC(stwStopTrace) 474 475 // See the comment in StartTrace. 476 lock(&sched.sysmonlock) 477 478 // See the comment in StartTrace. 479 lock(&trace.bufLock) 480 481 if !trace.enabled { 482 unlock(&trace.bufLock) 483 unlock(&sched.sysmonlock) 484 startTheWorldGC(stw) 485 return 486 } 487 488 // Trace GoSched for us, and use a dummy locker. The world is stopped 489 // and we control whether the trace is enabled, so this is safe. 490 tl := traceLocker{} 491 tl.GoSched() 492 493 atomicstorep(unsafe.Pointer(&trace.cpuLogWrite), nil) 494 trace.cpuLogRead.close() 495 traceReadCPU() 496 497 // Loop over all allocated Ps because dead Ps may still have 498 // trace buffers. 499 for _, p := range allp[:cap(allp)] { 500 buf := p.trace.buf 501 if buf != 0 { 502 traceFullQueue(buf) 503 p.trace.buf = 0 504 } 505 } 506 if trace.buf != 0 { 507 buf := trace.buf 508 trace.buf = 0 509 if buf.ptr().pos != 0 { 510 traceFullQueue(buf) 511 } 512 } 513 if trace.cpuLogBuf != 0 { 514 buf := trace.cpuLogBuf 515 trace.cpuLogBuf = 0 516 if buf.ptr().pos != 0 { 517 traceFullQueue(buf) 518 } 519 } 520 521 // Wait for startNanotime != endNanotime. On Windows the default interval between 522 // system clock ticks is typically between 1 and 15 milliseconds, which may not 523 // have passed since the trace started. Without nanotime moving forward, trace 524 // tooling has no way of identifying how much real time each cputicks time deltas 525 // represent. 526 for { 527 trace.endTime = traceClockNow() 528 trace.endTicks = cputicks() 529 trace.endNanotime = nanotime() 530 531 if trace.endNanotime != trace.startNanotime || faketime != 0 { 532 break 533 } 534 osyield() 535 } 536 537 trace.enabled = false 538 trace.shutdown = true 539 unlock(&trace.bufLock) 540 541 unlock(&sched.sysmonlock) 542 543 startTheWorldGC(stw) 544 545 // The world is started but we've set trace.shutdown, so new tracing can't start. 546 // Wait for the trace reader to flush pending buffers and stop. 547 semacquire(&trace.shutdownSema) 548 if raceenabled { 549 raceacquire(unsafe.Pointer(&trace.shutdownSema)) 550 } 551 552 systemstack(func() { 553 // The lock protects us from races with StartTrace/StopTrace because they do stop-the-world. 554 lock(&trace.lock) 555 for _, p := range allp[:cap(allp)] { 556 if p.trace.buf != 0 { 557 throw("trace: non-empty trace buffer in proc") 558 } 559 } 560 if trace.buf != 0 { 561 throw("trace: non-empty global trace buffer") 562 } 563 if trace.fullHead != 0 || trace.fullTail != 0 { 564 throw("trace: non-empty full trace buffer") 565 } 566 if trace.reading != 0 || trace.reader.Load() != nil { 567 throw("trace: reading after shutdown") 568 } 569 for trace.empty != 0 { 570 buf := trace.empty 571 trace.empty = buf.ptr().link 572 sysFree(unsafe.Pointer(buf), unsafe.Sizeof(*buf.ptr()), &memstats.other_sys) 573 } 574 trace.strings = nil 575 trace.shutdown = false 576 trace.cpuLogRead = nil 577 unlock(&trace.lock) 578 }) 579 } 580 581 // traceAdvance is called from panic, it does nothing for the legacy tracer. 582 func traceAdvance(stopTrace bool) {} 583 584 // ReadTrace returns the next chunk of binary tracing data, blocking until data 585 // is available. If tracing is turned off and all the data accumulated while it 586 // was on has been returned, ReadTrace returns nil. The caller must copy the 587 // returned data before calling ReadTrace again. 588 // ReadTrace must be called from one goroutine at a time. 589 func ReadTrace() []byte { 590 top: 591 var buf []byte 592 var park bool 593 systemstack(func() { 594 buf, park = readTrace0() 595 }) 596 if park { 597 gopark(func(gp *g, _ unsafe.Pointer) bool { 598 if !trace.reader.CompareAndSwapNoWB(nil, gp) { 599 // We're racing with another reader. 600 // Wake up and handle this case. 601 return false 602 } 603 604 if g2 := traceReader(); gp == g2 { 605 // New data arrived between unlocking 606 // and the CAS and we won the wake-up 607 // race, so wake up directly. 608 return false 609 } else if g2 != nil { 610 printlock() 611 println("runtime: got trace reader", g2, g2.goid) 612 throw("unexpected trace reader") 613 } 614 615 return true 616 }, nil, waitReasonTraceReaderBlocked, traceBlockSystemGoroutine, 2) 617 goto top 618 } 619 620 return buf 621 } 622 623 // readTrace0 is ReadTrace's continuation on g0. This must run on the 624 // system stack because it acquires trace.lock. 625 // 626 //go:systemstack 627 func readTrace0() (buf []byte, park bool) { 628 if raceenabled { 629 // g0 doesn't have a race context. Borrow the user G's. 630 if getg().racectx != 0 { 631 throw("expected racectx == 0") 632 } 633 getg().racectx = getg().m.curg.racectx 634 // (This defer should get open-coded, which is safe on 635 // the system stack.) 636 defer func() { getg().racectx = 0 }() 637 } 638 639 // Optimistically look for CPU profile samples. This may write new stack 640 // records, and may write new tracing buffers. This must be done with the 641 // trace lock not held. footerWritten and shutdown are safe to access 642 // here. They are only mutated by this goroutine or during a STW. 643 if !trace.footerWritten && !trace.shutdown { 644 traceReadCPU() 645 } 646 647 // This function must not allocate while holding trace.lock: 648 // allocation can call heap allocate, which will try to emit a trace 649 // event while holding heap lock. 650 lock(&trace.lock) 651 652 if trace.reader.Load() != nil { 653 // More than one goroutine reads trace. This is bad. 654 // But we rather do not crash the program because of tracing, 655 // because tracing can be enabled at runtime on prod servers. 656 unlock(&trace.lock) 657 println("runtime: ReadTrace called from multiple goroutines simultaneously") 658 return nil, false 659 } 660 // Recycle the old buffer. 661 if buf := trace.reading; buf != 0 { 662 buf.ptr().link = trace.empty 663 trace.empty = buf 664 trace.reading = 0 665 } 666 // Write trace header. 667 if !trace.headerWritten { 668 trace.headerWritten = true 669 unlock(&trace.lock) 670 return []byte("go 1.21 trace\x00\x00\x00"), false 671 } 672 // Wait for new data. 673 if trace.fullHead == 0 && !trace.shutdown { 674 // We don't simply use a note because the scheduler 675 // executes this goroutine directly when it wakes up 676 // (also a note would consume an M). 677 unlock(&trace.lock) 678 return nil, true 679 } 680 newFull: 681 assertLockHeld(&trace.lock) 682 // Write a buffer. 683 if trace.fullHead != 0 { 684 buf := traceFullDequeue() 685 trace.reading = buf 686 unlock(&trace.lock) 687 return buf.ptr().arr[:buf.ptr().pos], false 688 } 689 690 // Write footer with timer frequency. 691 if !trace.footerWritten { 692 trace.footerWritten = true 693 freq := (float64(trace.endTicks-trace.startTicks) / traceTimeDiv) / (float64(trace.endNanotime-trace.startNanotime) / 1e9) 694 if freq <= 0 { 695 throw("trace: ReadTrace got invalid frequency") 696 } 697 unlock(&trace.lock) 698 699 // Write frequency event. 700 bufp := traceFlush(0, 0) 701 buf := bufp.ptr() 702 buf.byte(traceEvFrequency | 0<<traceArgCountShift) 703 buf.varint(uint64(freq)) 704 705 // Dump stack table. 706 // This will emit a bunch of full buffers, we will pick them up 707 // on the next iteration. 708 bufp = trace.stackTab.dump(bufp) 709 710 // Flush final buffer. 711 lock(&trace.lock) 712 traceFullQueue(bufp) 713 goto newFull // trace.lock should be held at newFull 714 } 715 // Done. 716 if trace.shutdown { 717 unlock(&trace.lock) 718 if raceenabled { 719 // Model synchronization on trace.shutdownSema, which race 720 // detector does not see. This is required to avoid false 721 // race reports on writer passed to trace.Start. 722 racerelease(unsafe.Pointer(&trace.shutdownSema)) 723 } 724 // trace.enabled is already reset, so can call traceable functions. 725 semrelease(&trace.shutdownSema) 726 return nil, false 727 } 728 // Also bad, but see the comment above. 729 unlock(&trace.lock) 730 println("runtime: spurious wakeup of trace reader") 731 return nil, false 732 } 733 734 // traceReader returns the trace reader that should be woken up, if any. 735 // Callers should first check that trace.enabled or trace.shutdown is set. 736 // 737 // This must run on the system stack because it acquires trace.lock. 738 // 739 //go:systemstack 740 func traceReader() *g { 741 // Optimistic check first 742 if traceReaderAvailable() == nil { 743 return nil 744 } 745 lock(&trace.lock) 746 gp := traceReaderAvailable() 747 if gp == nil || !trace.reader.CompareAndSwapNoWB(gp, nil) { 748 unlock(&trace.lock) 749 return nil 750 } 751 unlock(&trace.lock) 752 return gp 753 } 754 755 // traceReaderAvailable returns the trace reader if it is not currently 756 // scheduled and should be. Callers should first check that trace.enabled 757 // or trace.shutdown is set. 758 func traceReaderAvailable() *g { 759 if trace.fullHead != 0 || trace.shutdown { 760 return trace.reader.Load() 761 } 762 return nil 763 } 764 765 // traceProcFree frees trace buffer associated with pp. 766 // 767 // This must run on the system stack because it acquires trace.lock. 768 // 769 //go:systemstack 770 func traceProcFree(pp *p) { 771 buf := pp.trace.buf 772 pp.trace.buf = 0 773 if buf == 0 { 774 return 775 } 776 lock(&trace.lock) 777 traceFullQueue(buf) 778 unlock(&trace.lock) 779 } 780 781 // ThreadDestroy is a no-op. It exists as a stub to support the new tracer. 782 // 783 // This must run on the system stack, just to match the new tracer. 784 func traceThreadDestroy(_ *m) { 785 // No-op in old tracer. 786 } 787 788 // traceFullQueue queues buf into queue of full buffers. 789 func traceFullQueue(buf traceBufPtr) { 790 buf.ptr().link = 0 791 if trace.fullHead == 0 { 792 trace.fullHead = buf 793 } else { 794 trace.fullTail.ptr().link = buf 795 } 796 trace.fullTail = buf 797 } 798 799 // traceFullDequeue dequeues from queue of full buffers. 800 func traceFullDequeue() traceBufPtr { 801 buf := trace.fullHead 802 if buf == 0 { 803 return 0 804 } 805 trace.fullHead = buf.ptr().link 806 if trace.fullHead == 0 { 807 trace.fullTail = 0 808 } 809 buf.ptr().link = 0 810 return buf 811 } 812 813 // traceEvent writes a single event to trace buffer, flushing the buffer if necessary. 814 // ev is event type. 815 // If skip > 0, write current stack id as the last argument (skipping skip top frames). 816 // If skip = 0, this event type should contain a stack, but we don't want 817 // to collect and remember it for this particular call. 818 func traceEvent(ev byte, skip int, args ...uint64) { 819 mp, pid, bufp := traceAcquireBuffer() 820 // Double-check trace.enabled now that we've done m.locks++ and acquired bufLock. 821 // This protects from races between traceEvent and StartTrace/StopTrace. 822 823 // The caller checked that trace.enabled == true, but trace.enabled might have been 824 // turned off between the check and now. Check again. traceLockBuffer did mp.locks++, 825 // StopTrace does stopTheWorld, and stopTheWorld waits for mp.locks to go back to zero, 826 // so if we see trace.enabled == true now, we know it's true for the rest of the function. 827 // Exitsyscall can run even during stopTheWorld. The race with StartTrace/StopTrace 828 // during tracing in exitsyscall is resolved by locking trace.bufLock in traceLockBuffer. 829 // 830 // Note trace_userTaskCreate runs the same check. 831 if !trace.enabled && !mp.trace.startingTrace { 832 traceReleaseBuffer(mp, pid) 833 return 834 } 835 836 if skip > 0 { 837 if getg() == mp.curg { 838 skip++ // +1 because stack is captured in traceEventLocked. 839 } 840 } 841 traceEventLocked(0, mp, pid, bufp, ev, 0, skip, args...) 842 traceReleaseBuffer(mp, pid) 843 } 844 845 // traceEventLocked writes a single event of type ev to the trace buffer bufp, 846 // flushing the buffer if necessary. pid is the id of the current P, or 847 // traceGlobProc if we're tracing without a real P. 848 // 849 // Preemption is disabled, and if running without a real P the global tracing 850 // buffer is locked. 851 // 852 // Events types that do not include a stack set skip to -1. Event types that 853 // include a stack may explicitly reference a stackID from the trace.stackTab 854 // (obtained by an earlier call to traceStackID). Without an explicit stackID, 855 // this function will automatically capture the stack of the goroutine currently 856 // running on mp, skipping skip top frames or, if skip is 0, writing out an 857 // empty stack record. 858 // 859 // It records the event's args to the traceBuf, and also makes an effort to 860 // reserve extraBytes bytes of additional space immediately following the event, 861 // in the same traceBuf. 862 func traceEventLocked(extraBytes int, mp *m, pid int32, bufp *traceBufPtr, ev byte, stackID uint32, skip int, args ...uint64) { 863 buf := bufp.ptr() 864 // TODO: test on non-zero extraBytes param. 865 maxSize := 2 + 5*traceBytesPerNumber + extraBytes // event type, length, sequence, timestamp, stack id and two add params 866 if buf == nil || len(buf.arr)-buf.pos < maxSize { 867 systemstack(func() { 868 buf = traceFlush(traceBufPtrOf(buf), pid).ptr() 869 }) 870 bufp.set(buf) 871 } 872 873 ts := traceClockNow() 874 if ts <= buf.lastTime { 875 ts = buf.lastTime + 1 876 } 877 tsDiff := uint64(ts - buf.lastTime) 878 buf.lastTime = ts 879 narg := byte(len(args)) 880 if stackID != 0 || skip >= 0 { 881 narg++ 882 } 883 // We have only 2 bits for number of arguments. 884 // If number is >= 3, then the event type is followed by event length in bytes. 885 if narg > 3 { 886 narg = 3 887 } 888 startPos := buf.pos 889 buf.byte(ev | narg<<traceArgCountShift) 890 var lenp *byte 891 if narg == 3 { 892 // Reserve the byte for length assuming that length < 128. 893 buf.varint(0) 894 lenp = &buf.arr[buf.pos-1] 895 } 896 buf.varint(tsDiff) 897 for _, a := range args { 898 buf.varint(a) 899 } 900 if stackID != 0 { 901 buf.varint(uint64(stackID)) 902 } else if skip == 0 { 903 buf.varint(0) 904 } else if skip > 0 { 905 buf.varint(traceStackID(mp, buf.stk[:], skip)) 906 } 907 evSize := buf.pos - startPos 908 if evSize > maxSize { 909 throw("invalid length of trace event") 910 } 911 if lenp != nil { 912 // Fill in actual length. 913 *lenp = byte(evSize - 2) 914 } 915 } 916 917 // traceCPUSample writes a CPU profile sample stack to the execution tracer's 918 // profiling buffer. It is called from a signal handler, so is limited in what 919 // it can do. 920 func traceCPUSample(gp *g, _ *m, pp *p, stk []uintptr) { 921 if !traceEnabled() { 922 // Tracing is usually turned off; don't spend time acquiring the signal 923 // lock unless it's active. 924 return 925 } 926 927 // Match the clock used in traceEventLocked 928 now := traceClockNow() 929 // The "header" here is the ID of the P that was running the profiled code, 930 // followed by the ID of the goroutine. (For normal CPU profiling, it's 931 // usually the number of samples with the given stack.) Near syscalls, pp 932 // may be nil. Reporting goid of 0 is fine for either g0 or a nil gp. 933 var hdr [2]uint64 934 if pp != nil { 935 // Overflow records in profBuf have all header values set to zero. Make 936 // sure that real headers have at least one bit set. 937 hdr[0] = uint64(pp.id)<<1 | 0b1 938 } else { 939 hdr[0] = 0b10 940 } 941 if gp != nil { 942 hdr[1] = gp.goid 943 } 944 945 // Allow only one writer at a time 946 for !trace.signalLock.CompareAndSwap(0, 1) { 947 // TODO: Is it safe to osyield here? https://go.dev/issue/52672 948 osyield() 949 } 950 951 if log := (*profBuf)(atomic.Loadp(unsafe.Pointer(&trace.cpuLogWrite))); log != nil { 952 // Note: we don't pass a tag pointer here (how should profiling tags 953 // interact with the execution tracer?), but if we did we'd need to be 954 // careful about write barriers. See the long comment in profBuf.write. 955 log.write(nil, int64(now), hdr[:], stk) 956 } 957 958 trace.signalLock.Store(0) 959 } 960 961 func traceReadCPU() { 962 bufp := &trace.cpuLogBuf 963 964 for { 965 data, tags, _ := trace.cpuLogRead.read(profBufNonBlocking) 966 if len(data) == 0 { 967 break 968 } 969 for len(data) > 0 { 970 if len(data) < 4 || data[0] > uint64(len(data)) { 971 break // truncated profile 972 } 973 if data[0] < 4 || tags != nil && len(tags) < 1 { 974 break // malformed profile 975 } 976 if len(tags) < 1 { 977 break // mismatched profile records and tags 978 } 979 timestamp := data[1] 980 ppid := data[2] >> 1 981 if hasP := (data[2] & 0b1) != 0; !hasP { 982 ppid = ^uint64(0) 983 } 984 goid := data[3] 985 stk := data[4:data[0]] 986 empty := len(stk) == 1 && data[2] == 0 && data[3] == 0 987 data = data[data[0]:] 988 // No support here for reporting goroutine tags at the moment; if 989 // that information is to be part of the execution trace, we'd 990 // probably want to see when the tags are applied and when they 991 // change, instead of only seeing them when we get a CPU sample. 992 tags = tags[1:] 993 994 if empty { 995 // Looks like an overflow record from the profBuf. Not much to 996 // do here, we only want to report full records. 997 // 998 // TODO: should we start a goroutine to drain the profBuf, 999 // rather than relying on a high-enough volume of tracing events 1000 // to keep ReadTrace busy? https://go.dev/issue/52674 1001 continue 1002 } 1003 1004 buf := bufp.ptr() 1005 if buf == nil { 1006 systemstack(func() { 1007 *bufp = traceFlush(*bufp, 0) 1008 }) 1009 buf = bufp.ptr() 1010 } 1011 nstk := 1 1012 buf.stk[0] = logicalStackSentinel 1013 for ; nstk < len(buf.stk) && nstk-1 < len(stk); nstk++ { 1014 buf.stk[nstk] = uintptr(stk[nstk-1]) 1015 } 1016 stackID := trace.stackTab.put(buf.stk[:nstk]) 1017 1018 traceEventLocked(0, nil, 0, bufp, traceEvCPUSample, stackID, 1, timestamp, ppid, goid) 1019 } 1020 } 1021 } 1022 1023 // logicalStackSentinel is a sentinel value at pcBuf[0] signifying that 1024 // pcBuf[1:] holds a logical stack requiring no further processing. Any other 1025 // value at pcBuf[0] represents a skip value to apply to the physical stack in 1026 // pcBuf[1:] after inline expansion. 1027 const logicalStackSentinel = ^uintptr(0) 1028 1029 // traceStackID captures a stack trace into pcBuf, registers it in the trace 1030 // stack table, and returns its unique ID. pcBuf should have a length equal to 1031 // traceStackSize. skip controls the number of leaf frames to omit in order to 1032 // hide tracer internals from stack traces, see CL 5523. 1033 func traceStackID(mp *m, pcBuf []uintptr, skip int) uint64 { 1034 gp := getg() 1035 curgp := mp.curg 1036 nstk := 1 1037 if tracefpunwindoff() || mp.hasCgoOnStack() { 1038 // Slow path: Unwind using default unwinder. Used when frame pointer 1039 // unwinding is unavailable or disabled (tracefpunwindoff), or might 1040 // produce incomplete results or crashes (hasCgoOnStack). Note that no 1041 // cgo callback related crashes have been observed yet. The main 1042 // motivation is to take advantage of a potentially registered cgo 1043 // symbolizer. 1044 pcBuf[0] = logicalStackSentinel 1045 if curgp == gp { 1046 nstk += callers(skip+1, pcBuf[1:]) 1047 } else if curgp != nil { 1048 nstk += gcallers(curgp, skip, pcBuf[1:]) 1049 } 1050 } else { 1051 // Fast path: Unwind using frame pointers. 1052 pcBuf[0] = uintptr(skip) 1053 if curgp == gp { 1054 nstk += fpTracebackPCs(unsafe.Pointer(getfp()), pcBuf[1:]) 1055 } else if curgp != nil { 1056 // We're called on the g0 stack through mcall(fn) or systemstack(fn). To 1057 // behave like gcallers above, we start unwinding from sched.bp, which 1058 // points to the caller frame of the leaf frame on g's stack. The return 1059 // address of the leaf frame is stored in sched.pc, which we manually 1060 // capture here. 1061 pcBuf[1] = curgp.sched.pc 1062 nstk += 1 + fpTracebackPCs(unsafe.Pointer(curgp.sched.bp), pcBuf[2:]) 1063 } 1064 } 1065 if nstk > 0 { 1066 nstk-- // skip runtime.goexit 1067 } 1068 if nstk > 0 && curgp.goid == 1 { 1069 nstk-- // skip runtime.main 1070 } 1071 id := trace.stackTab.put(pcBuf[:nstk]) 1072 return uint64(id) 1073 } 1074 1075 // tracefpunwindoff returns true if frame pointer unwinding for the tracer is 1076 // disabled via GODEBUG or not supported by the architecture. 1077 // TODO(#60254): support frame pointer unwinding on plan9/amd64. 1078 func tracefpunwindoff() bool { 1079 return debug.tracefpunwindoff != 0 || (goarch.ArchFamily != goarch.AMD64 && goarch.ArchFamily != goarch.ARM64) || goos.IsPlan9 == 1 1080 } 1081 1082 // fpTracebackPCs populates pcBuf with the return addresses for each frame and 1083 // returns the number of PCs written to pcBuf. The returned PCs correspond to 1084 // "physical frames" rather than "logical frames"; that is if A is inlined into 1085 // B, this will return a PC for only B. 1086 func fpTracebackPCs(fp unsafe.Pointer, pcBuf []uintptr) (i int) { 1087 for i = 0; i < len(pcBuf) && fp != nil; i++ { 1088 // return addr sits one word above the frame pointer 1089 pcBuf[i] = *(*uintptr)(unsafe.Pointer(uintptr(fp) + goarch.PtrSize)) 1090 // follow the frame pointer to the next one 1091 fp = unsafe.Pointer(*(*uintptr)(fp)) 1092 } 1093 return i 1094 } 1095 1096 // traceAcquireBuffer returns trace buffer to use and, if necessary, locks it. 1097 func traceAcquireBuffer() (mp *m, pid int32, bufp *traceBufPtr) { 1098 // Any time we acquire a buffer, we may end up flushing it, 1099 // but flushes are rare. Record the lock edge even if it 1100 // doesn't happen this time. 1101 lockRankMayTraceFlush() 1102 1103 mp = acquirem() 1104 if p := mp.p.ptr(); p != nil { 1105 return mp, p.id, &p.trace.buf 1106 } 1107 lock(&trace.bufLock) 1108 return mp, traceGlobProc, &trace.buf 1109 } 1110 1111 // traceReleaseBuffer releases a buffer previously acquired with traceAcquireBuffer. 1112 func traceReleaseBuffer(mp *m, pid int32) { 1113 if pid == traceGlobProc { 1114 unlock(&trace.bufLock) 1115 } 1116 releasem(mp) 1117 } 1118 1119 // lockRankMayTraceFlush records the lock ranking effects of a 1120 // potential call to traceFlush. 1121 func lockRankMayTraceFlush() { 1122 lockWithRankMayAcquire(&trace.lock, getLockRank(&trace.lock)) 1123 } 1124 1125 // traceFlush puts buf onto stack of full buffers and returns an empty buffer. 1126 // 1127 // This must run on the system stack because it acquires trace.lock. 1128 // 1129 //go:systemstack 1130 func traceFlush(buf traceBufPtr, pid int32) traceBufPtr { 1131 lock(&trace.lock) 1132 if buf != 0 { 1133 traceFullQueue(buf) 1134 } 1135 if trace.empty != 0 { 1136 buf = trace.empty 1137 trace.empty = buf.ptr().link 1138 } else { 1139 buf = traceBufPtr(sysAlloc(unsafe.Sizeof(traceBuf{}), &memstats.other_sys)) 1140 if buf == 0 { 1141 throw("trace: out of memory") 1142 } 1143 } 1144 bufp := buf.ptr() 1145 bufp.link.set(nil) 1146 bufp.pos = 0 1147 1148 // initialize the buffer for a new batch 1149 ts := traceClockNow() 1150 if ts <= bufp.lastTime { 1151 ts = bufp.lastTime + 1 1152 } 1153 bufp.lastTime = ts 1154 bufp.byte(traceEvBatch | 1<<traceArgCountShift) 1155 bufp.varint(uint64(pid)) 1156 bufp.varint(uint64(ts)) 1157 1158 unlock(&trace.lock) 1159 return buf 1160 } 1161 1162 // traceString adds a string to the trace.strings and returns the id. 1163 func traceString(bufp *traceBufPtr, pid int32, s string) (uint64, *traceBufPtr) { 1164 if s == "" { 1165 return 0, bufp 1166 } 1167 1168 lock(&trace.stringsLock) 1169 if raceenabled { 1170 // raceacquire is necessary because the map access 1171 // below is race annotated. 1172 raceacquire(unsafe.Pointer(&trace.stringsLock)) 1173 } 1174 1175 if id, ok := trace.strings[s]; ok { 1176 if raceenabled { 1177 racerelease(unsafe.Pointer(&trace.stringsLock)) 1178 } 1179 unlock(&trace.stringsLock) 1180 1181 return id, bufp 1182 } 1183 1184 trace.stringSeq++ 1185 id := trace.stringSeq 1186 trace.strings[s] = id 1187 1188 if raceenabled { 1189 racerelease(unsafe.Pointer(&trace.stringsLock)) 1190 } 1191 unlock(&trace.stringsLock) 1192 1193 // memory allocation in above may trigger tracing and 1194 // cause *bufp changes. Following code now works with *bufp, 1195 // so there must be no memory allocation or any activities 1196 // that causes tracing after this point. 1197 1198 buf := bufp.ptr() 1199 size := 1 + 2*traceBytesPerNumber + len(s) 1200 if buf == nil || len(buf.arr)-buf.pos < size { 1201 systemstack(func() { 1202 buf = traceFlush(traceBufPtrOf(buf), pid).ptr() 1203 bufp.set(buf) 1204 }) 1205 } 1206 buf.byte(traceEvString) 1207 buf.varint(id) 1208 1209 // double-check the string and the length can fit. 1210 // Otherwise, truncate the string. 1211 slen := len(s) 1212 if room := len(buf.arr) - buf.pos; room < slen+traceBytesPerNumber { 1213 slen = room 1214 } 1215 1216 buf.varint(uint64(slen)) 1217 buf.pos += copy(buf.arr[buf.pos:], s[:slen]) 1218 1219 bufp.set(buf) 1220 return id, bufp 1221 } 1222 1223 // varint appends v to buf in little-endian-base-128 encoding. 1224 func (buf *traceBuf) varint(v uint64) { 1225 pos := buf.pos 1226 for ; v >= 0x80; v >>= 7 { 1227 buf.arr[pos] = 0x80 | byte(v) 1228 pos++ 1229 } 1230 buf.arr[pos] = byte(v) 1231 pos++ 1232 buf.pos = pos 1233 } 1234 1235 // varintAt writes varint v at byte position pos in buf. This always 1236 // consumes traceBytesPerNumber bytes. This is intended for when the 1237 // caller needs to reserve space for a varint but can't populate it 1238 // until later. 1239 func (buf *traceBuf) varintAt(pos int, v uint64) { 1240 for i := 0; i < traceBytesPerNumber; i++ { 1241 if i < traceBytesPerNumber-1 { 1242 buf.arr[pos] = 0x80 | byte(v) 1243 } else { 1244 buf.arr[pos] = byte(v) 1245 } 1246 v >>= 7 1247 pos++ 1248 } 1249 } 1250 1251 // byte appends v to buf. 1252 func (buf *traceBuf) byte(v byte) { 1253 buf.arr[buf.pos] = v 1254 buf.pos++ 1255 } 1256 1257 // traceStackTable maps stack traces (arrays of PC's) to unique uint32 ids. 1258 // It is lock-free for reading. 1259 type traceStackTable struct { 1260 lock mutex // Must be acquired on the system stack 1261 seq uint32 1262 mem traceAlloc 1263 tab [1 << 13]traceStackPtr 1264 } 1265 1266 // traceStack is a single stack in traceStackTable. 1267 type traceStack struct { 1268 link traceStackPtr 1269 hash uintptr 1270 id uint32 1271 n int 1272 stk [0]uintptr // real type [n]uintptr 1273 } 1274 1275 type traceStackPtr uintptr 1276 1277 func (tp traceStackPtr) ptr() *traceStack { return (*traceStack)(unsafe.Pointer(tp)) } 1278 1279 // stack returns slice of PCs. 1280 func (ts *traceStack) stack() []uintptr { 1281 return (*[traceStackSize]uintptr)(unsafe.Pointer(&ts.stk))[:ts.n] 1282 } 1283 1284 // put returns a unique id for the stack trace pcs and caches it in the table, 1285 // if it sees the trace for the first time. 1286 func (tab *traceStackTable) put(pcs []uintptr) uint32 { 1287 if len(pcs) == 0 { 1288 return 0 1289 } 1290 hash := memhash(unsafe.Pointer(&pcs[0]), 0, uintptr(len(pcs))*unsafe.Sizeof(pcs[0])) 1291 // First, search the hashtable w/o the mutex. 1292 if id := tab.find(pcs, hash); id != 0 { 1293 return id 1294 } 1295 // Now, double check under the mutex. 1296 // Switch to the system stack so we can acquire tab.lock 1297 var id uint32 1298 systemstack(func() { 1299 lock(&tab.lock) 1300 if id = tab.find(pcs, hash); id != 0 { 1301 unlock(&tab.lock) 1302 return 1303 } 1304 // Create new record. 1305 tab.seq++ 1306 stk := tab.newStack(len(pcs)) 1307 stk.hash = hash 1308 stk.id = tab.seq 1309 id = stk.id 1310 stk.n = len(pcs) 1311 stkpc := stk.stack() 1312 copy(stkpc, pcs) 1313 part := int(hash % uintptr(len(tab.tab))) 1314 stk.link = tab.tab[part] 1315 atomicstorep(unsafe.Pointer(&tab.tab[part]), unsafe.Pointer(stk)) 1316 unlock(&tab.lock) 1317 }) 1318 return id 1319 } 1320 1321 // find checks if the stack trace pcs is already present in the table. 1322 func (tab *traceStackTable) find(pcs []uintptr, hash uintptr) uint32 { 1323 part := int(hash % uintptr(len(tab.tab))) 1324 Search: 1325 for stk := tab.tab[part].ptr(); stk != nil; stk = stk.link.ptr() { 1326 if stk.hash == hash && stk.n == len(pcs) { 1327 for i, stkpc := range stk.stack() { 1328 if stkpc != pcs[i] { 1329 continue Search 1330 } 1331 } 1332 return stk.id 1333 } 1334 } 1335 return 0 1336 } 1337 1338 // newStack allocates a new stack of size n. 1339 func (tab *traceStackTable) newStack(n int) *traceStack { 1340 return (*traceStack)(tab.mem.alloc(unsafe.Sizeof(traceStack{}) + uintptr(n)*goarch.PtrSize)) 1341 } 1342 1343 // traceFrames returns the frames corresponding to pcs. It may 1344 // allocate and may emit trace events. 1345 func traceFrames(bufp traceBufPtr, pcs []uintptr) ([]traceFrame, traceBufPtr) { 1346 frames := make([]traceFrame, 0, len(pcs)) 1347 ci := CallersFrames(pcs) 1348 for { 1349 var frame traceFrame 1350 f, more := ci.Next() 1351 frame, bufp = traceFrameForPC(bufp, 0, f) 1352 frames = append(frames, frame) 1353 if !more { 1354 return frames, bufp 1355 } 1356 } 1357 } 1358 1359 // dump writes all previously cached stacks to trace buffers, 1360 // releases all memory and resets state. 1361 // 1362 // This must run on the system stack because it calls traceFlush. 1363 // 1364 //go:systemstack 1365 func (tab *traceStackTable) dump(bufp traceBufPtr) traceBufPtr { 1366 for i := range tab.tab { 1367 stk := tab.tab[i].ptr() 1368 for ; stk != nil; stk = stk.link.ptr() { 1369 var frames []traceFrame 1370 frames, bufp = traceFrames(bufp, fpunwindExpand(stk.stack())) 1371 1372 // Estimate the size of this record. This 1373 // bound is pretty loose, but avoids counting 1374 // lots of varint sizes. 1375 maxSize := 1 + traceBytesPerNumber + (2+4*len(frames))*traceBytesPerNumber 1376 // Make sure we have enough buffer space. 1377 if buf := bufp.ptr(); len(buf.arr)-buf.pos < maxSize { 1378 bufp = traceFlush(bufp, 0) 1379 } 1380 1381 // Emit header, with space reserved for length. 1382 buf := bufp.ptr() 1383 buf.byte(traceEvStack | 3<<traceArgCountShift) 1384 lenPos := buf.pos 1385 buf.pos += traceBytesPerNumber 1386 1387 // Emit body. 1388 recPos := buf.pos 1389 buf.varint(uint64(stk.id)) 1390 buf.varint(uint64(len(frames))) 1391 for _, frame := range frames { 1392 buf.varint(uint64(frame.PC)) 1393 buf.varint(frame.funcID) 1394 buf.varint(frame.fileID) 1395 buf.varint(frame.line) 1396 } 1397 1398 // Fill in size header. 1399 buf.varintAt(lenPos, uint64(buf.pos-recPos)) 1400 } 1401 } 1402 1403 tab.mem.drop() 1404 *tab = traceStackTable{} 1405 lockInit(&((*tab).lock), lockRankTraceStackTab) 1406 1407 return bufp 1408 } 1409 1410 // fpunwindExpand checks if pcBuf contains logical frames (which include inlined 1411 // frames) or physical frames (produced by frame pointer unwinding) using a 1412 // sentinel value in pcBuf[0]. Logical frames are simply returned without the 1413 // sentinel. Physical frames are turned into logical frames via inline unwinding 1414 // and by applying the skip value that's stored in pcBuf[0]. 1415 func fpunwindExpand(pcBuf []uintptr) []uintptr { 1416 if len(pcBuf) > 0 && pcBuf[0] == logicalStackSentinel { 1417 // pcBuf contains logical rather than inlined frames, skip has already been 1418 // applied, just return it without the sentinel value in pcBuf[0]. 1419 return pcBuf[1:] 1420 } 1421 1422 var ( 1423 lastFuncID = abi.FuncIDNormal 1424 newPCBuf = make([]uintptr, 0, traceStackSize) 1425 skip = pcBuf[0] 1426 // skipOrAdd skips or appends retPC to newPCBuf and returns true if more 1427 // pcs can be added. 1428 skipOrAdd = func(retPC uintptr) bool { 1429 if skip > 0 { 1430 skip-- 1431 } else { 1432 newPCBuf = append(newPCBuf, retPC) 1433 } 1434 return len(newPCBuf) < cap(newPCBuf) 1435 } 1436 ) 1437 1438 outer: 1439 for _, retPC := range pcBuf[1:] { 1440 callPC := retPC - 1 1441 fi := findfunc(callPC) 1442 if !fi.valid() { 1443 // There is no funcInfo if callPC belongs to a C function. In this case 1444 // we still keep the pc, but don't attempt to expand inlined frames. 1445 if more := skipOrAdd(retPC); !more { 1446 break outer 1447 } 1448 continue 1449 } 1450 1451 u, uf := newInlineUnwinder(fi, callPC) 1452 for ; uf.valid(); uf = u.next(uf) { 1453 sf := u.srcFunc(uf) 1454 if sf.funcID == abi.FuncIDWrapper && elideWrapperCalling(lastFuncID) { 1455 // ignore wrappers 1456 } else if more := skipOrAdd(uf.pc + 1); !more { 1457 break outer 1458 } 1459 lastFuncID = sf.funcID 1460 } 1461 } 1462 return newPCBuf 1463 } 1464 1465 type traceFrame struct { 1466 PC uintptr 1467 funcID uint64 1468 fileID uint64 1469 line uint64 1470 } 1471 1472 // traceFrameForPC records the frame information. 1473 // It may allocate memory. 1474 func traceFrameForPC(buf traceBufPtr, pid int32, f Frame) (traceFrame, traceBufPtr) { 1475 bufp := &buf 1476 var frame traceFrame 1477 frame.PC = f.PC 1478 1479 fn := f.Function 1480 const maxLen = 1 << 10 1481 if len(fn) > maxLen { 1482 fn = fn[len(fn)-maxLen:] 1483 } 1484 frame.funcID, bufp = traceString(bufp, pid, fn) 1485 frame.line = uint64(f.Line) 1486 file := f.File 1487 if len(file) > maxLen { 1488 file = file[len(file)-maxLen:] 1489 } 1490 frame.fileID, bufp = traceString(bufp, pid, file) 1491 return frame, (*bufp) 1492 } 1493 1494 // traceAlloc is a non-thread-safe region allocator. 1495 // It holds a linked list of traceAllocBlock. 1496 type traceAlloc struct { 1497 head traceAllocBlockPtr 1498 off uintptr 1499 } 1500 1501 // traceAllocBlock is a block in traceAlloc. 1502 // 1503 // traceAllocBlock is allocated from non-GC'd memory, so it must not 1504 // contain heap pointers. Writes to pointers to traceAllocBlocks do 1505 // not need write barriers. 1506 type traceAllocBlock struct { 1507 _ sys.NotInHeap 1508 next traceAllocBlockPtr 1509 data [64<<10 - goarch.PtrSize]byte 1510 } 1511 1512 // TODO: Since traceAllocBlock is now embedded runtime/internal/sys.NotInHeap, this isn't necessary. 1513 type traceAllocBlockPtr uintptr 1514 1515 func (p traceAllocBlockPtr) ptr() *traceAllocBlock { return (*traceAllocBlock)(unsafe.Pointer(p)) } 1516 func (p *traceAllocBlockPtr) set(x *traceAllocBlock) { *p = traceAllocBlockPtr(unsafe.Pointer(x)) } 1517 1518 // alloc allocates n-byte block. 1519 func (a *traceAlloc) alloc(n uintptr) unsafe.Pointer { 1520 n = alignUp(n, goarch.PtrSize) 1521 if a.head == 0 || a.off+n > uintptr(len(a.head.ptr().data)) { 1522 if n > uintptr(len(a.head.ptr().data)) { 1523 throw("trace: alloc too large") 1524 } 1525 block := (*traceAllocBlock)(sysAlloc(unsafe.Sizeof(traceAllocBlock{}), &memstats.other_sys)) 1526 if block == nil { 1527 throw("trace: out of memory") 1528 } 1529 block.next.set(a.head.ptr()) 1530 a.head.set(block) 1531 a.off = 0 1532 } 1533 p := &a.head.ptr().data[a.off] 1534 a.off += n 1535 return unsafe.Pointer(p) 1536 } 1537 1538 // drop frees all previously allocated memory and resets the allocator. 1539 func (a *traceAlloc) drop() { 1540 for a.head != 0 { 1541 block := a.head.ptr() 1542 a.head.set(block.next.ptr()) 1543 sysFree(unsafe.Pointer(block), unsafe.Sizeof(traceAllocBlock{}), &memstats.other_sys) 1544 } 1545 } 1546 1547 // The following functions write specific events to trace. 1548 1549 func (_ traceLocker) Gomaxprocs(procs int32) { 1550 traceEvent(traceEvGomaxprocs, 1, uint64(procs)) 1551 } 1552 1553 func (_ traceLocker) ProcStart() { 1554 traceEvent(traceEvProcStart, -1, uint64(getg().m.id)) 1555 } 1556 1557 func (_ traceLocker) ProcStop(pp *p) { 1558 // Sysmon and stopTheWorld can stop Ps blocked in syscalls, 1559 // to handle this we temporary employ the P. 1560 mp := acquirem() 1561 oldp := mp.p 1562 mp.p.set(pp) 1563 traceEvent(traceEvProcStop, -1) 1564 mp.p = oldp 1565 releasem(mp) 1566 } 1567 1568 func (_ traceLocker) GCStart() { 1569 traceEvent(traceEvGCStart, 3, trace.seqGC) 1570 trace.seqGC++ 1571 } 1572 1573 func (_ traceLocker) GCDone() { 1574 traceEvent(traceEvGCDone, -1) 1575 } 1576 1577 func (_ traceLocker) STWStart(reason stwReason) { 1578 // Don't trace if this STW is for trace start/stop, since traceEnabled 1579 // switches during a STW. 1580 if reason == stwStartTrace || reason == stwStopTrace { 1581 return 1582 } 1583 getg().m.trace.tracedSTWStart = true 1584 traceEvent(traceEvSTWStart, -1, uint64(reason)) 1585 } 1586 1587 func (_ traceLocker) STWDone() { 1588 mp := getg().m 1589 if !mp.trace.tracedSTWStart { 1590 return 1591 } 1592 mp.trace.tracedSTWStart = false 1593 traceEvent(traceEvSTWDone, -1) 1594 } 1595 1596 // traceGCSweepStart prepares to trace a sweep loop. This does not 1597 // emit any events until traceGCSweepSpan is called. 1598 // 1599 // traceGCSweepStart must be paired with traceGCSweepDone and there 1600 // must be no preemption points between these two calls. 1601 func (_ traceLocker) GCSweepStart() { 1602 // Delay the actual GCSweepStart event until the first span 1603 // sweep. If we don't sweep anything, don't emit any events. 1604 pp := getg().m.p.ptr() 1605 if pp.trace.inSweep { 1606 throw("double traceGCSweepStart") 1607 } 1608 pp.trace.inSweep, pp.trace.swept, pp.trace.reclaimed = true, 0, 0 1609 } 1610 1611 // traceGCSweepSpan traces the sweep of a single page. 1612 // 1613 // This may be called outside a traceGCSweepStart/traceGCSweepDone 1614 // pair; however, it will not emit any trace events in this case. 1615 func (_ traceLocker) GCSweepSpan(bytesSwept uintptr) { 1616 pp := getg().m.p.ptr() 1617 if pp.trace.inSweep { 1618 if pp.trace.swept == 0 { 1619 traceEvent(traceEvGCSweepStart, 1) 1620 } 1621 pp.trace.swept += bytesSwept 1622 } 1623 } 1624 1625 func (_ traceLocker) GCSweepDone() { 1626 pp := getg().m.p.ptr() 1627 if !pp.trace.inSweep { 1628 throw("missing traceGCSweepStart") 1629 } 1630 if pp.trace.swept != 0 { 1631 traceEvent(traceEvGCSweepDone, -1, uint64(pp.trace.swept), uint64(pp.trace.reclaimed)) 1632 } 1633 pp.trace.inSweep = false 1634 } 1635 1636 func (_ traceLocker) GCMarkAssistStart() { 1637 traceEvent(traceEvGCMarkAssistStart, 1) 1638 } 1639 1640 func (_ traceLocker) GCMarkAssistDone() { 1641 traceEvent(traceEvGCMarkAssistDone, -1) 1642 } 1643 1644 // N.B. the last argument is used only for iter.Pull. 1645 func (_ traceLocker) GoCreate(newg *g, pc uintptr, blocked bool) { 1646 if blocked { 1647 throw("tried to emit event for newly-created blocked goroutine: unsupported in the v1 tracer") 1648 } 1649 newg.trace.seq = 0 1650 newg.trace.lastP = getg().m.p 1651 // +PCQuantum because traceFrameForPC expects return PCs and subtracts PCQuantum. 1652 id := trace.stackTab.put([]uintptr{logicalStackSentinel, startPCforTrace(pc) + sys.PCQuantum}) 1653 traceEvent(traceEvGoCreate, 2, newg.goid, uint64(id)) 1654 } 1655 1656 func (_ traceLocker) GoStart() { 1657 gp := getg().m.curg 1658 pp := gp.m.p 1659 gp.trace.seq++ 1660 if pp.ptr().gcMarkWorkerMode != gcMarkWorkerNotWorker { 1661 traceEvent(traceEvGoStartLabel, -1, gp.goid, gp.trace.seq, trace.markWorkerLabels[pp.ptr().gcMarkWorkerMode]) 1662 } else if gp.trace.lastP == pp { 1663 traceEvent(traceEvGoStartLocal, -1, gp.goid) 1664 } else { 1665 gp.trace.lastP = pp 1666 traceEvent(traceEvGoStart, -1, gp.goid, gp.trace.seq) 1667 } 1668 } 1669 1670 func (_ traceLocker) GoEnd() { 1671 traceEvent(traceEvGoEnd, -1) 1672 } 1673 1674 func (_ traceLocker) GoSched() { 1675 gp := getg() 1676 gp.trace.lastP = gp.m.p 1677 traceEvent(traceEvGoSched, 1) 1678 } 1679 1680 func (_ traceLocker) GoPreempt() { 1681 gp := getg() 1682 gp.trace.lastP = gp.m.p 1683 traceEvent(traceEvGoPreempt, 1) 1684 } 1685 1686 func (_ traceLocker) GoPark(reason traceBlockReason, skip int) { 1687 // Convert the block reason directly to a trace event type. 1688 // See traceBlockReason for more information. 1689 traceEvent(byte(reason), skip) 1690 } 1691 1692 func (_ traceLocker) GoUnpark(gp *g, skip int) { 1693 pp := getg().m.p 1694 gp.trace.seq++ 1695 if gp.trace.lastP == pp { 1696 traceEvent(traceEvGoUnblockLocal, skip, gp.goid) 1697 } else { 1698 gp.trace.lastP = pp 1699 traceEvent(traceEvGoUnblock, skip, gp.goid, gp.trace.seq) 1700 } 1701 } 1702 1703 func (_ traceLocker) GoSwitch(_ *g, _ bool) { 1704 throw("tried to emit event for a direct goroutine switch: unsupported in the v1 tracer") 1705 } 1706 1707 func (_ traceLocker) GoSysCall() { 1708 var skip int 1709 switch { 1710 case tracefpunwindoff(): 1711 // Unwind by skipping 1 frame relative to gp.syscallsp which is captured 3 1712 // frames above this frame. For frame pointer unwinding we produce the same 1713 // results by hard coding the number of frames in between our caller and the 1714 // actual syscall, see cases below. 1715 // TODO(felixge): Implement gp.syscallbp to avoid this workaround? 1716 skip = 1 1717 case GOOS == "solaris" || GOOS == "illumos": 1718 // These platforms don't use a libc_read_trampoline. 1719 skip = 3 1720 default: 1721 // Skip the extra trampoline frame used on most systems. 1722 skip = 4 1723 } 1724 getg().m.curg.trace.tracedSyscallEnter = true 1725 traceEvent(traceEvGoSysCall, skip) 1726 } 1727 1728 func (_ traceLocker) GoSysExit(lostP bool) { 1729 if !lostP { 1730 throw("lostP must always be true in the old tracer for GoSysExit") 1731 } 1732 gp := getg().m.curg 1733 if !gp.trace.tracedSyscallEnter { 1734 // There was no syscall entry traced for us at all, so there's definitely 1735 // no EvGoSysBlock or EvGoInSyscall before us, which EvGoSysExit requires. 1736 return 1737 } 1738 gp.trace.tracedSyscallEnter = false 1739 ts := gp.trace.sysExitTime 1740 if ts != 0 && ts < trace.startTime { 1741 // There is a race between the code that initializes sysExitTimes 1742 // (in exitsyscall, which runs without a P, and therefore is not 1743 // stopped with the rest of the world) and the code that initializes 1744 // a new trace. The recorded sysExitTime must therefore be treated 1745 // as "best effort". If they are valid for this trace, then great, 1746 // use them for greater accuracy. But if they're not valid for this 1747 // trace, assume that the trace was started after the actual syscall 1748 // exit (but before we actually managed to start the goroutine, 1749 // aka right now), and assign a fresh time stamp to keep the log consistent. 1750 ts = 0 1751 } 1752 gp.trace.sysExitTime = 0 1753 gp.trace.seq++ 1754 gp.trace.lastP = gp.m.p 1755 traceEvent(traceEvGoSysExit, -1, gp.goid, gp.trace.seq, uint64(ts)) 1756 } 1757 1758 // nosplit because it's called from exitsyscall without a P. 1759 // 1760 //go:nosplit 1761 func (_ traceLocker) RecordSyscallExitedTime(gp *g, oldp *p) { 1762 // Wait till traceGoSysBlock event is emitted. 1763 // This ensures consistency of the trace (the goroutine is started after it is blocked). 1764 for oldp != nil && oldp.syscalltick == gp.m.syscalltick { 1765 osyield() 1766 } 1767 // We can't trace syscall exit right now because we don't have a P. 1768 // Tracing code can invoke write barriers that cannot run without a P. 1769 // So instead we remember the syscall exit time and emit the event 1770 // in execute when we have a P. 1771 gp.trace.sysExitTime = traceClockNow() 1772 } 1773 1774 func (_ traceLocker) GoSysBlock(pp *p) { 1775 // Sysmon and stopTheWorld can declare syscalls running on remote Ps as blocked, 1776 // to handle this we temporary employ the P. 1777 mp := acquirem() 1778 oldp := mp.p 1779 mp.p.set(pp) 1780 traceEvent(traceEvGoSysBlock, -1) 1781 mp.p = oldp 1782 releasem(mp) 1783 } 1784 1785 func (t traceLocker) ProcSteal(pp *p, forMe bool) { 1786 t.ProcStop(pp) 1787 } 1788 1789 func (_ traceLocker) HeapAlloc(live uint64) { 1790 traceEvent(traceEvHeapAlloc, -1, live) 1791 } 1792 1793 func (_ traceLocker) HeapGoal() { 1794 heapGoal := gcController.heapGoal() 1795 if heapGoal == ^uint64(0) { 1796 // Heap-based triggering is disabled. 1797 traceEvent(traceEvHeapGoal, -1, 0) 1798 } else { 1799 traceEvent(traceEvHeapGoal, -1, heapGoal) 1800 } 1801 } 1802 1803 // To access runtime functions from runtime/trace. 1804 // See runtime/trace/annotation.go 1805 1806 //go:linkname trace_userTaskCreate runtime/trace.userTaskCreate 1807 func trace_userTaskCreate(id, parentID uint64, taskType string) { 1808 if !trace.enabled { 1809 return 1810 } 1811 1812 // Same as in traceEvent. 1813 mp, pid, bufp := traceAcquireBuffer() 1814 if !trace.enabled && !mp.trace.startingTrace { 1815 traceReleaseBuffer(mp, pid) 1816 return 1817 } 1818 1819 typeStringID, bufp := traceString(bufp, pid, taskType) 1820 traceEventLocked(0, mp, pid, bufp, traceEvUserTaskCreate, 0, 3, id, parentID, typeStringID) 1821 traceReleaseBuffer(mp, pid) 1822 } 1823 1824 //go:linkname trace_userTaskEnd runtime/trace.userTaskEnd 1825 func trace_userTaskEnd(id uint64) { 1826 traceEvent(traceEvUserTaskEnd, 2, id) 1827 } 1828 1829 //go:linkname trace_userRegion runtime/trace.userRegion 1830 func trace_userRegion(id, mode uint64, name string) { 1831 if !trace.enabled { 1832 return 1833 } 1834 1835 mp, pid, bufp := traceAcquireBuffer() 1836 if !trace.enabled && !mp.trace.startingTrace { 1837 traceReleaseBuffer(mp, pid) 1838 return 1839 } 1840 1841 nameStringID, bufp := traceString(bufp, pid, name) 1842 traceEventLocked(0, mp, pid, bufp, traceEvUserRegion, 0, 3, id, mode, nameStringID) 1843 traceReleaseBuffer(mp, pid) 1844 } 1845 1846 //go:linkname trace_userLog runtime/trace.userLog 1847 func trace_userLog(id uint64, category, message string) { 1848 if !trace.enabled { 1849 return 1850 } 1851 1852 mp, pid, bufp := traceAcquireBuffer() 1853 if !trace.enabled && !mp.trace.startingTrace { 1854 traceReleaseBuffer(mp, pid) 1855 return 1856 } 1857 1858 categoryID, bufp := traceString(bufp, pid, category) 1859 1860 // The log message is recorded after all of the normal trace event 1861 // arguments, including the task, category, and stack IDs. We must ask 1862 // traceEventLocked to reserve extra space for the length of the message 1863 // and the message itself. 1864 extraSpace := traceBytesPerNumber + len(message) 1865 traceEventLocked(extraSpace, mp, pid, bufp, traceEvUserLog, 0, 3, id, categoryID) 1866 buf := bufp.ptr() 1867 1868 // double-check the message and its length can fit. 1869 // Otherwise, truncate the message. 1870 slen := len(message) 1871 if room := len(buf.arr) - buf.pos; room < slen+traceBytesPerNumber { 1872 slen = room 1873 } 1874 buf.varint(uint64(slen)) 1875 buf.pos += copy(buf.arr[buf.pos:], message[:slen]) 1876 1877 traceReleaseBuffer(mp, pid) 1878 } 1879 1880 // the start PC of a goroutine for tracing purposes. If pc is a wrapper, 1881 // it returns the PC of the wrapped function. Otherwise it returns pc. 1882 func startPCforTrace(pc uintptr) uintptr { 1883 f := findfunc(pc) 1884 if !f.valid() { 1885 return pc // may happen for locked g in extra M since its pc is 0. 1886 } 1887 w := funcdata(f, abi.FUNCDATA_WrapInfo) 1888 if w == nil { 1889 return pc // not a wrapper 1890 } 1891 return f.datap.textAddr(*(*uint32)(w)) 1892 } 1893 1894 // OneNewExtraM registers the fact that a new extra M was created with 1895 // the tracer. This matters if the M (which has an attached G) is used while 1896 // the trace is still active because if it is, we need the fact that it exists 1897 // to show up in the final trace. 1898 func (tl traceLocker) OneNewExtraM(gp *g) { 1899 // Trigger two trace events for the locked g in the extra m, 1900 // since the next event of the g will be traceEvGoSysExit in exitsyscall, 1901 // while calling from C thread to Go. 1902 tl.GoCreate(gp, 0, false) // no start pc 1903 gp.trace.seq++ 1904 traceEvent(traceEvGoInSyscall, -1, gp.goid) 1905 } 1906 1907 // Used only in the new tracer. 1908 func (tl traceLocker) GoCreateSyscall(gp *g) { 1909 } 1910 1911 // Used only in the new tracer. 1912 func (tl traceLocker) GoDestroySyscall() { 1913 } 1914 1915 // traceTime represents a timestamp for the trace. 1916 type traceTime uint64 1917 1918 // traceClockNow returns a monotonic timestamp. The clock this function gets 1919 // the timestamp from is specific to tracing, and shouldn't be mixed with other 1920 // clock sources. 1921 // 1922 // nosplit because it's called from exitsyscall, which is nosplit. 1923 // 1924 //go:nosplit 1925 func traceClockNow() traceTime { 1926 return traceTime(cputicks() / traceTimeDiv) 1927 } 1928 1929 func traceExitingSyscall() { 1930 } 1931 1932 func traceExitedSyscall() { 1933 } 1934 1935 // Not used in the old tracer. Defined for compatibility. 1936 const defaultTraceAdvancePeriod = 0