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 execution tracer.
6// The tracer captures a wide range of execution events like goroutine
7// creation/blocking/unblocking, syscall enter/exit/block, GC-related events,
8// changes of heap size, processor start/stop, etc and writes them to a buffer
9// in a compact form. A precise nanosecond-precision timestamp and a stack
10// trace is captured for most events.
11// See https://golang.org/s/go15trace for more info.
12
13package runtime
14
15import (
16	"runtime/internal/sys"
17	"unsafe"
18)
19
20// Event types in the trace, args are given in square brackets.
21const (
22	traceEvNone              = 0  // unused
23	traceEvBatch             = 1  // start of per-P batch of events [pid, timestamp]
24	traceEvFrequency         = 2  // contains tracer timer frequency [frequency (ticks per second)]
25	traceEvStack             = 3  // stack [stack id, number of PCs, array of {PC, func string ID, file string ID, line}]
26	traceEvGomaxprocs        = 4  // current value of GOMAXPROCS [timestamp, GOMAXPROCS, stack id]
27	traceEvProcStart         = 5  // start of P [timestamp, thread id]
28	traceEvProcStop          = 6  // stop of P [timestamp]
29	traceEvGCStart           = 7  // GC start [timestamp, seq, stack id]
30	traceEvGCDone            = 8  // GC done [timestamp]
31	traceEvGCSTWStart        = 9  // GC STW start [timestamp, kind]
32	traceEvGCSTWDone         = 10 // GC STW done [timestamp]
33	traceEvGCSweepStart      = 11 // GC sweep start [timestamp, stack id]
34	traceEvGCSweepDone       = 12 // GC sweep done [timestamp, swept, reclaimed]
35	traceEvGoCreate          = 13 // goroutine creation [timestamp, new goroutine id, new stack id, stack id]
36	traceEvGoStart           = 14 // goroutine starts running [timestamp, goroutine id, seq]
37	traceEvGoEnd             = 15 // goroutine ends [timestamp]
38	traceEvGoStop            = 16 // goroutine stops (like in select{}) [timestamp, stack]
39	traceEvGoSched           = 17 // goroutine calls Gosched [timestamp, stack]
40	traceEvGoPreempt         = 18 // goroutine is preempted [timestamp, stack]
41	traceEvGoSleep           = 19 // goroutine calls Sleep [timestamp, stack]
42	traceEvGoBlock           = 20 // goroutine blocks [timestamp, stack]
43	traceEvGoUnblock         = 21 // goroutine is unblocked [timestamp, goroutine id, seq, stack]
44	traceEvGoBlockSend       = 22 // goroutine blocks on chan send [timestamp, stack]
45	traceEvGoBlockRecv       = 23 // goroutine blocks on chan recv [timestamp, stack]
46	traceEvGoBlockSelect     = 24 // goroutine blocks on select [timestamp, stack]
47	traceEvGoBlockSync       = 25 // goroutine blocks on Mutex/RWMutex [timestamp, stack]
48	traceEvGoBlockCond       = 26 // goroutine blocks on Cond [timestamp, stack]
49	traceEvGoBlockNet        = 27 // goroutine blocks on network [timestamp, stack]
50	traceEvGoSysCall         = 28 // syscall enter [timestamp, stack]
51	traceEvGoSysExit         = 29 // syscall exit [timestamp, goroutine id, seq, real timestamp]
52	traceEvGoSysBlock        = 30 // syscall blocks [timestamp]
53	traceEvGoWaiting         = 31 // denotes that goroutine is blocked when tracing starts [timestamp, goroutine id]
54	traceEvGoInSyscall       = 32 // denotes that goroutine is in syscall when tracing starts [timestamp, goroutine id]
55	traceEvHeapAlloc         = 33 // memstats.heap_live change [timestamp, heap_alloc]
56	traceEvNextGC            = 34 // memstats.next_gc change [timestamp, next_gc]
57	traceEvTimerGoroutine    = 35 // not currently used; previously denoted timer goroutine [timer goroutine id]
58	traceEvFutileWakeup      = 36 // denotes that the previous wakeup of this goroutine was futile [timestamp]
59	traceEvString            = 37 // string dictionary entry [ID, length, string]
60	traceEvGoStartLocal      = 38 // goroutine starts running on the same P as the last event [timestamp, goroutine id]
61	traceEvGoUnblockLocal    = 39 // goroutine is unblocked on the same P as the last event [timestamp, goroutine id, stack]
62	traceEvGoSysExitLocal    = 40 // syscall exit on the same P as the last event [timestamp, goroutine id, real timestamp]
63	traceEvGoStartLabel      = 41 // goroutine starts running with label [timestamp, goroutine id, seq, label string id]
64	traceEvGoBlockGC         = 42 // goroutine blocks on GC assist [timestamp, stack]
65	traceEvGCMarkAssistStart = 43 // GC mark assist start [timestamp, stack]
66	traceEvGCMarkAssistDone  = 44 // GC mark assist done [timestamp]
67	traceEvUserTaskCreate    = 45 // trace.NewContext [timestamp, internal task id, internal parent task id, stack, name string]
68	traceEvUserTaskEnd       = 46 // end of a task [timestamp, internal task id, stack]
69	traceEvUserRegion        = 47 // trace.WithRegion [timestamp, internal task id, mode(0:start, 1:end), stack, name string]
70	traceEvUserLog           = 48 // trace.Log [timestamp, internal task id, key string id, stack, value string]
71	traceEvCount             = 49
72	// Byte is used but only 6 bits are available for event type.
73	// The remaining 2 bits are used to specify the number of arguments.
74	// That means, the max event type value is 63.
75)
76
77const (
78	// Timestamps in trace are cputicks/traceTickDiv.
79	// This makes absolute values of timestamp diffs smaller,
80	// and so they are encoded in less number of bytes.
81	// 64 on x86 is somewhat arbitrary (one tick is ~20ns on a 3GHz machine).
82	// The suggested increment frequency for PowerPC's time base register is
83	// 512 MHz according to Power ISA v2.07 section 6.2, so we use 16 on ppc64
84	// and ppc64le.
85	// Tracing won't work reliably for architectures where cputicks is emulated
86	// by nanotime, so the value doesn't matter for those architectures.
87	traceTickDiv = 16 + 48*(sys.Goarch386|sys.GoarchAmd64)
88	// Maximum number of PCs in a single stack trace.
89	// Since events contain only stack id rather than whole stack trace,
90	// we can allow quite large values here.
91	traceStackSize = 128
92	// Identifier of a fake P that is used when we trace without a real P.
93	traceGlobProc = -1
94	// Maximum number of bytes to encode uint64 in base-128.
95	traceBytesPerNumber = 10
96	// Shift of the number of arguments in the first event byte.
97	traceArgCountShift = 6
98	// Flag passed to traceGoPark to denote that the previous wakeup of this
99	// goroutine was futile. For example, a goroutine was unblocked on a mutex,
100	// but another goroutine got ahead and acquired the mutex before the first
101	// goroutine is scheduled, so the first goroutine has to block again.
102	// Such wakeups happen on buffered channels and sync.Mutex,
103	// but are generally not interesting for end user.
104	traceFutileWakeup byte = 128
105)
106
107// trace is global tracing context.
108var trace struct {
109	lock          mutex       // protects the following members
110	lockOwner     *g          // to avoid deadlocks during recursive lock locks
111	enabled       bool        // when set runtime traces events
112	shutdown      bool        // set when we are waiting for trace reader to finish after setting enabled to false
113	headerWritten bool        // whether ReadTrace has emitted trace header
114	footerWritten bool        // whether ReadTrace has emitted trace footer
115	shutdownSema  uint32      // used to wait for ReadTrace completion
116	seqStart      uint64      // sequence number when tracing was started
117	ticksStart    int64       // cputicks when tracing was started
118	ticksEnd      int64       // cputicks when tracing was stopped
119	timeStart     int64       // nanotime when tracing was started
120	timeEnd       int64       // nanotime when tracing was stopped
121	seqGC         uint64      // GC start/done sequencer
122	reading       traceBufPtr // buffer currently handed off to user
123	empty         traceBufPtr // stack of empty buffers
124	fullHead      traceBufPtr // queue of full buffers
125	fullTail      traceBufPtr
126	reader        guintptr        // goroutine that called ReadTrace, or nil
127	stackTab      traceStackTable // maps stack traces to unique ids
128
129	// Dictionary for traceEvString.
130	//
131	// TODO: central lock to access the map is not ideal.
132	//   option: pre-assign ids to all user annotation region names and tags
133	//   option: per-P cache
134	//   option: sync.Map like data structure
135	stringsLock mutex
136	strings     map[string]uint64
137	stringSeq   uint64
138
139	// markWorkerLabels maps gcMarkWorkerMode to string ID.
140	markWorkerLabels [len(gcMarkWorkerModeStrings)]uint64
141
142	bufLock mutex       // protects buf
143	buf     traceBufPtr // global trace buffer, used when running without a p
144}
145
146// traceBufHeader is per-P tracing buffer.
147type traceBufHeader struct {
148	link      traceBufPtr             // in trace.empty/full
149	lastTicks uint64                  // when we wrote the last event
150	pos       int                     // next write offset in arr
151	stk       [traceStackSize]uintptr // scratch buffer for traceback
152}
153
154// traceBuf is per-P tracing buffer.
155//
156//go:notinheap
157type traceBuf struct {
158	traceBufHeader
159	arr [64<<10 - unsafe.Sizeof(traceBufHeader{})]byte // underlying buffer for traceBufHeader.buf
160}
161
162// traceBufPtr is a *traceBuf that is not traced by the garbage
163// collector and doesn't have write barriers. traceBufs are not
164// allocated from the GC'd heap, so this is safe, and are often
165// manipulated in contexts where write barriers are not allowed, so
166// this is necessary.
167//
168// TODO: Since traceBuf is now go:notinheap, this isn't necessary.
169type traceBufPtr uintptr
170
171func (tp traceBufPtr) ptr() *traceBuf   { return (*traceBuf)(unsafe.Pointer(tp)) }
172func (tp *traceBufPtr) set(b *traceBuf) { *tp = traceBufPtr(unsafe.Pointer(b)) }
173func traceBufPtrOf(b *traceBuf) traceBufPtr {
174	return traceBufPtr(unsafe.Pointer(b))
175}
176
177// StartTrace enables tracing for the current process.
178// While tracing, the data will be buffered and available via ReadTrace.
179// StartTrace returns an error if tracing is already enabled.
180// Most clients should use the runtime/trace package or the testing package's
181// -test.trace flag instead of calling StartTrace directly.
182func StartTrace() error {
183	// Stop the world, so that we can take a consistent snapshot
184	// of all goroutines at the beginning of the trace.
185	stopTheWorld("start tracing")
186
187	// We are in stop-the-world, but syscalls can finish and write to trace concurrently.
188	// Exitsyscall could check trace.enabled long before and then suddenly wake up
189	// and decide to write to trace at a random point in time.
190	// However, such syscall will use the global trace.buf buffer, because we've
191	// acquired all p's by doing stop-the-world. So this protects us from such races.
192	lock(&trace.bufLock)
193
194	if trace.enabled || trace.shutdown {
195		unlock(&trace.bufLock)
196		startTheWorld()
197		return errorString("tracing is already enabled")
198	}
199
200	// Can't set trace.enabled yet. While the world is stopped, exitsyscall could
201	// already emit a delayed event (see exitTicks in exitsyscall) if we set trace.enabled here.
202	// That would lead to an inconsistent trace:
203	// - either GoSysExit appears before EvGoInSyscall,
204	// - or GoSysExit appears for a goroutine for which we don't emit EvGoInSyscall below.
205	// To instruct traceEvent that it must not ignore events below, we set startingtrace.
206	// trace.enabled is set afterwards once we have emitted all preliminary events.
207	_g_ := getg()
208	_g_.m.startingtrace = true
209
210	// Obtain current stack ID to use in all traceEvGoCreate events below.
211	mp := acquirem()
212	stkBuf := make([]uintptr, traceStackSize)
213	stackID := traceStackID(mp, stkBuf, 2)
214	releasem(mp)
215
216	for _, gp := range allgs {
217		status := readgstatus(gp)
218		if status != _Gdead {
219			gp.traceseq = 0
220			gp.tracelastp = getg().m.p
221			// +PCQuantum because traceFrameForPC expects return PCs and subtracts PCQuantum.
222			id := trace.stackTab.put([]uintptr{gp.startpc + sys.PCQuantum})
223			traceEvent(traceEvGoCreate, -1, uint64(gp.goid), uint64(id), stackID)
224		}
225		if status == _Gwaiting {
226			// traceEvGoWaiting is implied to have seq=1.
227			gp.traceseq++
228			traceEvent(traceEvGoWaiting, -1, uint64(gp.goid))
229		}
230		if status == _Gsyscall {
231			gp.traceseq++
232			traceEvent(traceEvGoInSyscall, -1, uint64(gp.goid))
233		} else {
234			gp.sysblocktraced = false
235		}
236	}
237	traceProcStart()
238	traceGoStart()
239	// Note: ticksStart needs to be set after we emit traceEvGoInSyscall events.
240	// If we do it the other way around, it is possible that exitsyscall will
241	// query sysexitticks after ticksStart but before traceEvGoInSyscall timestamp.
242	// It will lead to a false conclusion that cputicks is broken.
243	trace.ticksStart = cputicks()
244	trace.timeStart = nanotime()
245	trace.headerWritten = false
246	trace.footerWritten = false
247
248	// string to id mapping
249	//  0 : reserved for an empty string
250	//  remaining: other strings registered by traceString
251	trace.stringSeq = 0
252	trace.strings = make(map[string]uint64)
253
254	trace.seqGC = 0
255	_g_.m.startingtrace = false
256	trace.enabled = true
257
258	// Register runtime goroutine labels.
259	_, pid, bufp := traceAcquireBuffer()
260	for i, label := range gcMarkWorkerModeStrings[:] {
261		trace.markWorkerLabels[i], bufp = traceString(bufp, pid, label)
262	}
263	traceReleaseBuffer(pid)
264
265	unlock(&trace.bufLock)
266
267	startTheWorld()
268	return nil
269}
270
271// StopTrace stops tracing, if it was previously enabled.
272// StopTrace only returns after all the reads for the trace have completed.
273func StopTrace() {
274	// Stop the world so that we can collect the trace buffers from all p's below,
275	// and also to avoid races with traceEvent.
276	stopTheWorld("stop tracing")
277
278	// See the comment in StartTrace.
279	lock(&trace.bufLock)
280
281	if !trace.enabled {
282		unlock(&trace.bufLock)
283		startTheWorld()
284		return
285	}
286
287	traceGoSched()
288
289	// Loop over all allocated Ps because dead Ps may still have
290	// trace buffers.
291	for _, p := range allp[:cap(allp)] {
292		buf := p.tracebuf
293		if buf != 0 {
294			traceFullQueue(buf)
295			p.tracebuf = 0
296		}
297	}
298	if trace.buf != 0 {
299		buf := trace.buf
300		trace.buf = 0
301		if buf.ptr().pos != 0 {
302			traceFullQueue(buf)
303		}
304	}
305
306	for {
307		trace.ticksEnd = cputicks()
308		trace.timeEnd = nanotime()
309		// Windows time can tick only every 15ms, wait for at least one tick.
310		if trace.timeEnd != trace.timeStart {
311			break
312		}
313		osyield()
314	}
315
316	trace.enabled = false
317	trace.shutdown = true
318	unlock(&trace.bufLock)
319
320	startTheWorld()
321
322	// The world is started but we've set trace.shutdown, so new tracing can't start.
323	// Wait for the trace reader to flush pending buffers and stop.
324	semacquire(&trace.shutdownSema)
325	if raceenabled {
326		raceacquire(unsafe.Pointer(&trace.shutdownSema))
327	}
328
329	// The lock protects us from races with StartTrace/StopTrace because they do stop-the-world.
330	lock(&trace.lock)
331	for _, p := range allp[:cap(allp)] {
332		if p.tracebuf != 0 {
333			throw("trace: non-empty trace buffer in proc")
334		}
335	}
336	if trace.buf != 0 {
337		throw("trace: non-empty global trace buffer")
338	}
339	if trace.fullHead != 0 || trace.fullTail != 0 {
340		throw("trace: non-empty full trace buffer")
341	}
342	if trace.reading != 0 || trace.reader != 0 {
343		throw("trace: reading after shutdown")
344	}
345	for trace.empty != 0 {
346		buf := trace.empty
347		trace.empty = buf.ptr().link
348		sysFree(unsafe.Pointer(buf), unsafe.Sizeof(*buf.ptr()), &memstats.other_sys)
349	}
350	trace.strings = nil
351	trace.shutdown = false
352	unlock(&trace.lock)
353}
354
355// ReadTrace returns the next chunk of binary tracing data, blocking until data
356// is available. If tracing is turned off and all the data accumulated while it
357// was on has been returned, ReadTrace returns nil. The caller must copy the
358// returned data before calling ReadTrace again.
359// ReadTrace must be called from one goroutine at a time.
360func ReadTrace() []byte {
361	// This function may need to lock trace.lock recursively
362	// (goparkunlock -> traceGoPark -> traceEvent -> traceFlush).
363	// To allow this we use trace.lockOwner.
364	// Also this function must not allocate while holding trace.lock:
365	// allocation can call heap allocate, which will try to emit a trace
366	// event while holding heap lock.
367	lock(&trace.lock)
368	trace.lockOwner = getg()
369
370	if trace.reader != 0 {
371		// More than one goroutine reads trace. This is bad.
372		// But we rather do not crash the program because of tracing,
373		// because tracing can be enabled at runtime on prod servers.
374		trace.lockOwner = nil
375		unlock(&trace.lock)
376		println("runtime: ReadTrace called from multiple goroutines simultaneously")
377		return nil
378	}
379	// Recycle the old buffer.
380	if buf := trace.reading; buf != 0 {
381		buf.ptr().link = trace.empty
382		trace.empty = buf
383		trace.reading = 0
384	}
385	// Write trace header.
386	if !trace.headerWritten {
387		trace.headerWritten = true
388		trace.lockOwner = nil
389		unlock(&trace.lock)
390		return []byte("go 1.11 trace\x00\x00\x00")
391	}
392	// Wait for new data.
393	if trace.fullHead == 0 && !trace.shutdown {
394		trace.reader.set(getg())
395		goparkunlock(&trace.lock, waitReasonTraceReaderBlocked, traceEvGoBlock, 2)
396		lock(&trace.lock)
397	}
398	// Write a buffer.
399	if trace.fullHead != 0 {
400		buf := traceFullDequeue()
401		trace.reading = buf
402		trace.lockOwner = nil
403		unlock(&trace.lock)
404		return buf.ptr().arr[:buf.ptr().pos]
405	}
406	// Write footer with timer frequency.
407	if !trace.footerWritten {
408		trace.footerWritten = true
409		// Use float64 because (trace.ticksEnd - trace.ticksStart) * 1e9 can overflow int64.
410		freq := float64(trace.ticksEnd-trace.ticksStart) * 1e9 / float64(trace.timeEnd-trace.timeStart) / traceTickDiv
411		trace.lockOwner = nil
412		unlock(&trace.lock)
413		var data []byte
414		data = append(data, traceEvFrequency|0<<traceArgCountShift)
415		data = traceAppend(data, uint64(freq))
416		// This will emit a bunch of full buffers, we will pick them up
417		// on the next iteration.
418		trace.stackTab.dump()
419		return data
420	}
421	// Done.
422	if trace.shutdown {
423		trace.lockOwner = nil
424		unlock(&trace.lock)
425		if raceenabled {
426			// Model synchronization on trace.shutdownSema, which race
427			// detector does not see. This is required to avoid false
428			// race reports on writer passed to trace.Start.
429			racerelease(unsafe.Pointer(&trace.shutdownSema))
430		}
431		// trace.enabled is already reset, so can call traceable functions.
432		semrelease(&trace.shutdownSema)
433		return nil
434	}
435	// Also bad, but see the comment above.
436	trace.lockOwner = nil
437	unlock(&trace.lock)
438	println("runtime: spurious wakeup of trace reader")
439	return nil
440}
441
442// traceReader returns the trace reader that should be woken up, if any.
443func traceReader() *g {
444	if trace.reader == 0 || (trace.fullHead == 0 && !trace.shutdown) {
445		return nil
446	}
447	lock(&trace.lock)
448	if trace.reader == 0 || (trace.fullHead == 0 && !trace.shutdown) {
449		unlock(&trace.lock)
450		return nil
451	}
452	gp := trace.reader.ptr()
453	trace.reader.set(nil)
454	unlock(&trace.lock)
455	return gp
456}
457
458// traceProcFree frees trace buffer associated with pp.
459func traceProcFree(pp *p) {
460	buf := pp.tracebuf
461	pp.tracebuf = 0
462	if buf == 0 {
463		return
464	}
465	lock(&trace.lock)
466	traceFullQueue(buf)
467	unlock(&trace.lock)
468}
469
470// traceFullQueue queues buf into queue of full buffers.
471func traceFullQueue(buf traceBufPtr) {
472	buf.ptr().link = 0
473	if trace.fullHead == 0 {
474		trace.fullHead = buf
475	} else {
476		trace.fullTail.ptr().link = buf
477	}
478	trace.fullTail = buf
479}
480
481// traceFullDequeue dequeues from queue of full buffers.
482func traceFullDequeue() traceBufPtr {
483	buf := trace.fullHead
484	if buf == 0 {
485		return 0
486	}
487	trace.fullHead = buf.ptr().link
488	if trace.fullHead == 0 {
489		trace.fullTail = 0
490	}
491	buf.ptr().link = 0
492	return buf
493}
494
495// traceEvent writes a single event to trace buffer, flushing the buffer if necessary.
496// ev is event type.
497// If skip > 0, write current stack id as the last argument (skipping skip top frames).
498// If skip = 0, this event type should contain a stack, but we don't want
499// to collect and remember it for this particular call.
500func traceEvent(ev byte, skip int, args ...uint64) {
501	mp, pid, bufp := traceAcquireBuffer()
502	// Double-check trace.enabled now that we've done m.locks++ and acquired bufLock.
503	// This protects from races between traceEvent and StartTrace/StopTrace.
504
505	// The caller checked that trace.enabled == true, but trace.enabled might have been
506	// turned off between the check and now. Check again. traceLockBuffer did mp.locks++,
507	// StopTrace does stopTheWorld, and stopTheWorld waits for mp.locks to go back to zero,
508	// so if we see trace.enabled == true now, we know it's true for the rest of the function.
509	// Exitsyscall can run even during stopTheWorld. The race with StartTrace/StopTrace
510	// during tracing in exitsyscall is resolved by locking trace.bufLock in traceLockBuffer.
511	//
512	// Note trace_userTaskCreate runs the same check.
513	if !trace.enabled && !mp.startingtrace {
514		traceReleaseBuffer(pid)
515		return
516	}
517
518	if skip > 0 {
519		if getg() == mp.curg {
520			skip++ // +1 because stack is captured in traceEventLocked.
521		}
522	}
523	traceEventLocked(0, mp, pid, bufp, ev, skip, args...)
524	traceReleaseBuffer(pid)
525}
526
527func traceEventLocked(extraBytes int, mp *m, pid int32, bufp *traceBufPtr, ev byte, skip int, args ...uint64) {
528	buf := bufp.ptr()
529	// TODO: test on non-zero extraBytes param.
530	maxSize := 2 + 5*traceBytesPerNumber + extraBytes // event type, length, sequence, timestamp, stack id and two add params
531	if buf == nil || len(buf.arr)-buf.pos < maxSize {
532		buf = traceFlush(traceBufPtrOf(buf), pid).ptr()
533		bufp.set(buf)
534	}
535
536	ticks := uint64(cputicks()) / traceTickDiv
537	tickDiff := ticks - buf.lastTicks
538	buf.lastTicks = ticks
539	narg := byte(len(args))
540	if skip >= 0 {
541		narg++
542	}
543	// We have only 2 bits for number of arguments.
544	// If number is >= 3, then the event type is followed by event length in bytes.
545	if narg > 3 {
546		narg = 3
547	}
548	startPos := buf.pos
549	buf.byte(ev | narg<<traceArgCountShift)
550	var lenp *byte
551	if narg == 3 {
552		// Reserve the byte for length assuming that length < 128.
553		buf.varint(0)
554		lenp = &buf.arr[buf.pos-1]
555	}
556	buf.varint(tickDiff)
557	for _, a := range args {
558		buf.varint(a)
559	}
560	if skip == 0 {
561		buf.varint(0)
562	} else if skip > 0 {
563		buf.varint(traceStackID(mp, buf.stk[:], skip))
564	}
565	evSize := buf.pos - startPos
566	if evSize > maxSize {
567		throw("invalid length of trace event")
568	}
569	if lenp != nil {
570		// Fill in actual length.
571		*lenp = byte(evSize - 2)
572	}
573}
574
575func traceStackID(mp *m, buf []uintptr, skip int) uint64 {
576	_g_ := getg()
577	gp := mp.curg
578	var nstk int
579	if gp == _g_ {
580		nstk = callers(skip+1, buf)
581	} else if gp != nil {
582		gp = mp.curg
583		nstk = gcallers(gp, skip, buf)
584	}
585	if nstk > 0 {
586		nstk-- // skip runtime.goexit
587	}
588	if nstk > 0 && gp.goid == 1 {
589		nstk-- // skip runtime.main
590	}
591	id := trace.stackTab.put(buf[:nstk])
592	return uint64(id)
593}
594
595// traceAcquireBuffer returns trace buffer to use and, if necessary, locks it.
596func traceAcquireBuffer() (mp *m, pid int32, bufp *traceBufPtr) {
597	mp = acquirem()
598	if p := mp.p.ptr(); p != nil {
599		return mp, p.id, &p.tracebuf
600	}
601	lock(&trace.bufLock)
602	return mp, traceGlobProc, &trace.buf
603}
604
605// traceReleaseBuffer releases a buffer previously acquired with traceAcquireBuffer.
606func traceReleaseBuffer(pid int32) {
607	if pid == traceGlobProc {
608		unlock(&trace.bufLock)
609	}
610	releasem(getg().m)
611}
612
613// traceFlush puts buf onto stack of full buffers and returns an empty buffer.
614func traceFlush(buf traceBufPtr, pid int32) traceBufPtr {
615	owner := trace.lockOwner
616	dolock := owner == nil || owner != getg().m.curg
617	if dolock {
618		lock(&trace.lock)
619	}
620	if buf != 0 {
621		traceFullQueue(buf)
622	}
623	if trace.empty != 0 {
624		buf = trace.empty
625		trace.empty = buf.ptr().link
626	} else {
627		buf = traceBufPtr(sysAlloc(unsafe.Sizeof(traceBuf{}), &memstats.other_sys))
628		if buf == 0 {
629			throw("trace: out of memory")
630		}
631	}
632	bufp := buf.ptr()
633	bufp.link.set(nil)
634	bufp.pos = 0
635
636	// initialize the buffer for a new batch
637	ticks := uint64(cputicks()) / traceTickDiv
638	bufp.lastTicks = ticks
639	bufp.byte(traceEvBatch | 1<<traceArgCountShift)
640	bufp.varint(uint64(pid))
641	bufp.varint(ticks)
642
643	if dolock {
644		unlock(&trace.lock)
645	}
646	return buf
647}
648
649// traceString adds a string to the trace.strings and returns the id.
650func traceString(bufp *traceBufPtr, pid int32, s string) (uint64, *traceBufPtr) {
651	if s == "" {
652		return 0, bufp
653	}
654
655	lock(&trace.stringsLock)
656	if raceenabled {
657		// raceacquire is necessary because the map access
658		// below is race annotated.
659		raceacquire(unsafe.Pointer(&trace.stringsLock))
660	}
661
662	if id, ok := trace.strings[s]; ok {
663		if raceenabled {
664			racerelease(unsafe.Pointer(&trace.stringsLock))
665		}
666		unlock(&trace.stringsLock)
667
668		return id, bufp
669	}
670
671	trace.stringSeq++
672	id := trace.stringSeq
673	trace.strings[s] = id
674
675	if raceenabled {
676		racerelease(unsafe.Pointer(&trace.stringsLock))
677	}
678	unlock(&trace.stringsLock)
679
680	// memory allocation in above may trigger tracing and
681	// cause *bufp changes. Following code now works with *bufp,
682	// so there must be no memory allocation or any activities
683	// that causes tracing after this point.
684
685	buf := bufp.ptr()
686	size := 1 + 2*traceBytesPerNumber + len(s)
687	if buf == nil || len(buf.arr)-buf.pos < size {
688		buf = traceFlush(traceBufPtrOf(buf), pid).ptr()
689		bufp.set(buf)
690	}
691	buf.byte(traceEvString)
692	buf.varint(id)
693
694	// double-check the string and the length can fit.
695	// Otherwise, truncate the string.
696	slen := len(s)
697	if room := len(buf.arr) - buf.pos; room < slen+traceBytesPerNumber {
698		slen = room
699	}
700
701	buf.varint(uint64(slen))
702	buf.pos += copy(buf.arr[buf.pos:], s[:slen])
703
704	bufp.set(buf)
705	return id, bufp
706}
707
708// traceAppend appends v to buf in little-endian-base-128 encoding.
709func traceAppend(buf []byte, v uint64) []byte {
710	for ; v >= 0x80; v >>= 7 {
711		buf = append(buf, 0x80|byte(v))
712	}
713	buf = append(buf, byte(v))
714	return buf
715}
716
717// varint appends v to buf in little-endian-base-128 encoding.
718func (buf *traceBuf) varint(v uint64) {
719	pos := buf.pos
720	for ; v >= 0x80; v >>= 7 {
721		buf.arr[pos] = 0x80 | byte(v)
722		pos++
723	}
724	buf.arr[pos] = byte(v)
725	pos++
726	buf.pos = pos
727}
728
729// byte appends v to buf.
730func (buf *traceBuf) byte(v byte) {
731	buf.arr[buf.pos] = v
732	buf.pos++
733}
734
735// traceStackTable maps stack traces (arrays of PC's) to unique uint32 ids.
736// It is lock-free for reading.
737type traceStackTable struct {
738	lock mutex
739	seq  uint32
740	mem  traceAlloc
741	tab  [1 << 13]traceStackPtr
742}
743
744// traceStack is a single stack in traceStackTable.
745type traceStack struct {
746	link traceStackPtr
747	hash uintptr
748	id   uint32
749	n    int
750	stk  [0]uintptr // real type [n]uintptr
751}
752
753type traceStackPtr uintptr
754
755func (tp traceStackPtr) ptr() *traceStack { return (*traceStack)(unsafe.Pointer(tp)) }
756
757// stack returns slice of PCs.
758func (ts *traceStack) stack() []uintptr {
759	return (*[traceStackSize]uintptr)(unsafe.Pointer(&ts.stk))[:ts.n]
760}
761
762// put returns a unique id for the stack trace pcs and caches it in the table,
763// if it sees the trace for the first time.
764func (tab *traceStackTable) put(pcs []uintptr) uint32 {
765	if len(pcs) == 0 {
766		return 0
767	}
768	hash := memhash(unsafe.Pointer(&pcs[0]), 0, uintptr(len(pcs))*unsafe.Sizeof(pcs[0]))
769	// First, search the hashtable w/o the mutex.
770	if id := tab.find(pcs, hash); id != 0 {
771		return id
772	}
773	// Now, double check under the mutex.
774	lock(&tab.lock)
775	if id := tab.find(pcs, hash); id != 0 {
776		unlock(&tab.lock)
777		return id
778	}
779	// Create new record.
780	tab.seq++
781	stk := tab.newStack(len(pcs))
782	stk.hash = hash
783	stk.id = tab.seq
784	stk.n = len(pcs)
785	stkpc := stk.stack()
786	for i, pc := range pcs {
787		stkpc[i] = pc
788	}
789	part := int(hash % uintptr(len(tab.tab)))
790	stk.link = tab.tab[part]
791	atomicstorep(unsafe.Pointer(&tab.tab[part]), unsafe.Pointer(stk))
792	unlock(&tab.lock)
793	return stk.id
794}
795
796// find checks if the stack trace pcs is already present in the table.
797func (tab *traceStackTable) find(pcs []uintptr, hash uintptr) uint32 {
798	part := int(hash % uintptr(len(tab.tab)))
799Search:
800	for stk := tab.tab[part].ptr(); stk != nil; stk = stk.link.ptr() {
801		if stk.hash == hash && stk.n == len(pcs) {
802			for i, stkpc := range stk.stack() {
803				if stkpc != pcs[i] {
804					continue Search
805				}
806			}
807			return stk.id
808		}
809	}
810	return 0
811}
812
813// newStack allocates a new stack of size n.
814func (tab *traceStackTable) newStack(n int) *traceStack {
815	return (*traceStack)(tab.mem.alloc(unsafe.Sizeof(traceStack{}) + uintptr(n)*sys.PtrSize))
816}
817
818// allFrames returns all of the Frames corresponding to pcs.
819func allFrames(pcs []uintptr) []Frame {
820	frames := make([]Frame, 0, len(pcs))
821	ci := CallersFrames(pcs)
822	for {
823		f, more := ci.Next()
824		frames = append(frames, f)
825		if !more {
826			return frames
827		}
828	}
829}
830
831// dump writes all previously cached stacks to trace buffers,
832// releases all memory and resets state.
833func (tab *traceStackTable) dump() {
834	var tmp [(2 + 4*traceStackSize) * traceBytesPerNumber]byte
835	bufp := traceFlush(0, 0)
836	for _, stk := range tab.tab {
837		stk := stk.ptr()
838		for ; stk != nil; stk = stk.link.ptr() {
839			tmpbuf := tmp[:0]
840			tmpbuf = traceAppend(tmpbuf, uint64(stk.id))
841			frames := allFrames(stk.stack())
842			tmpbuf = traceAppend(tmpbuf, uint64(len(frames)))
843			for _, f := range frames {
844				var frame traceFrame
845				frame, bufp = traceFrameForPC(bufp, 0, f)
846				tmpbuf = traceAppend(tmpbuf, uint64(f.PC))
847				tmpbuf = traceAppend(tmpbuf, uint64(frame.funcID))
848				tmpbuf = traceAppend(tmpbuf, uint64(frame.fileID))
849				tmpbuf = traceAppend(tmpbuf, uint64(frame.line))
850			}
851			// Now copy to the buffer.
852			size := 1 + traceBytesPerNumber + len(tmpbuf)
853			if buf := bufp.ptr(); len(buf.arr)-buf.pos < size {
854				bufp = traceFlush(bufp, 0)
855			}
856			buf := bufp.ptr()
857			buf.byte(traceEvStack | 3<<traceArgCountShift)
858			buf.varint(uint64(len(tmpbuf)))
859			buf.pos += copy(buf.arr[buf.pos:], tmpbuf)
860		}
861	}
862
863	lock(&trace.lock)
864	traceFullQueue(bufp)
865	unlock(&trace.lock)
866
867	tab.mem.drop()
868	*tab = traceStackTable{}
869}
870
871type traceFrame struct {
872	funcID uint64
873	fileID uint64
874	line   uint64
875}
876
877// traceFrameForPC records the frame information.
878// It may allocate memory.
879func traceFrameForPC(buf traceBufPtr, pid int32, f Frame) (traceFrame, traceBufPtr) {
880	bufp := &buf
881	var frame traceFrame
882
883	fn := f.Function
884	const maxLen = 1 << 10
885	if len(fn) > maxLen {
886		fn = fn[len(fn)-maxLen:]
887	}
888	frame.funcID, bufp = traceString(bufp, pid, fn)
889	frame.line = uint64(f.Line)
890	file := f.File
891	if len(file) > maxLen {
892		file = file[len(file)-maxLen:]
893	}
894	frame.fileID, bufp = traceString(bufp, pid, file)
895	return frame, (*bufp)
896}
897
898// traceAlloc is a non-thread-safe region allocator.
899// It holds a linked list of traceAllocBlock.
900type traceAlloc struct {
901	head traceAllocBlockPtr
902	off  uintptr
903}
904
905// traceAllocBlock is a block in traceAlloc.
906//
907// traceAllocBlock is allocated from non-GC'd memory, so it must not
908// contain heap pointers. Writes to pointers to traceAllocBlocks do
909// not need write barriers.
910//
911//go:notinheap
912type traceAllocBlock struct {
913	next traceAllocBlockPtr
914	data [64<<10 - sys.PtrSize]byte
915}
916
917// TODO: Since traceAllocBlock is now go:notinheap, this isn't necessary.
918type traceAllocBlockPtr uintptr
919
920func (p traceAllocBlockPtr) ptr() *traceAllocBlock   { return (*traceAllocBlock)(unsafe.Pointer(p)) }
921func (p *traceAllocBlockPtr) set(x *traceAllocBlock) { *p = traceAllocBlockPtr(unsafe.Pointer(x)) }
922
923// alloc allocates n-byte block.
924func (a *traceAlloc) alloc(n uintptr) unsafe.Pointer {
925	n = alignUp(n, sys.PtrSize)
926	if a.head == 0 || a.off+n > uintptr(len(a.head.ptr().data)) {
927		if n > uintptr(len(a.head.ptr().data)) {
928			throw("trace: alloc too large")
929		}
930		block := (*traceAllocBlock)(sysAlloc(unsafe.Sizeof(traceAllocBlock{}), &memstats.other_sys))
931		if block == nil {
932			throw("trace: out of memory")
933		}
934		block.next.set(a.head.ptr())
935		a.head.set(block)
936		a.off = 0
937	}
938	p := &a.head.ptr().data[a.off]
939	a.off += n
940	return unsafe.Pointer(p)
941}
942
943// drop frees all previously allocated memory and resets the allocator.
944func (a *traceAlloc) drop() {
945	for a.head != 0 {
946		block := a.head.ptr()
947		a.head.set(block.next.ptr())
948		sysFree(unsafe.Pointer(block), unsafe.Sizeof(traceAllocBlock{}), &memstats.other_sys)
949	}
950}
951
952// The following functions write specific events to trace.
953
954func traceGomaxprocs(procs int32) {
955	traceEvent(traceEvGomaxprocs, 1, uint64(procs))
956}
957
958func traceProcStart() {
959	traceEvent(traceEvProcStart, -1, uint64(getg().m.id))
960}
961
962func traceProcStop(pp *p) {
963	// Sysmon and stopTheWorld can stop Ps blocked in syscalls,
964	// to handle this we temporary employ the P.
965	mp := acquirem()
966	oldp := mp.p
967	mp.p.set(pp)
968	traceEvent(traceEvProcStop, -1)
969	mp.p = oldp
970	releasem(mp)
971}
972
973func traceGCStart() {
974	traceEvent(traceEvGCStart, 3, trace.seqGC)
975	trace.seqGC++
976}
977
978func traceGCDone() {
979	traceEvent(traceEvGCDone, -1)
980}
981
982func traceGCSTWStart(kind int) {
983	traceEvent(traceEvGCSTWStart, -1, uint64(kind))
984}
985
986func traceGCSTWDone() {
987	traceEvent(traceEvGCSTWDone, -1)
988}
989
990// traceGCSweepStart prepares to trace a sweep loop. This does not
991// emit any events until traceGCSweepSpan is called.
992//
993// traceGCSweepStart must be paired with traceGCSweepDone and there
994// must be no preemption points between these two calls.
995func traceGCSweepStart() {
996	// Delay the actual GCSweepStart event until the first span
997	// sweep. If we don't sweep anything, don't emit any events.
998	_p_ := getg().m.p.ptr()
999	if _p_.traceSweep {
1000		throw("double traceGCSweepStart")
1001	}
1002	_p_.traceSweep, _p_.traceSwept, _p_.traceReclaimed = true, 0, 0
1003}
1004
1005// traceGCSweepSpan traces the sweep of a single page.
1006//
1007// This may be called outside a traceGCSweepStart/traceGCSweepDone
1008// pair; however, it will not emit any trace events in this case.
1009func traceGCSweepSpan(bytesSwept uintptr) {
1010	_p_ := getg().m.p.ptr()
1011	if _p_.traceSweep {
1012		if _p_.traceSwept == 0 {
1013			traceEvent(traceEvGCSweepStart, 1)
1014		}
1015		_p_.traceSwept += bytesSwept
1016	}
1017}
1018
1019func traceGCSweepDone() {
1020	_p_ := getg().m.p.ptr()
1021	if !_p_.traceSweep {
1022		throw("missing traceGCSweepStart")
1023	}
1024	if _p_.traceSwept != 0 {
1025		traceEvent(traceEvGCSweepDone, -1, uint64(_p_.traceSwept), uint64(_p_.traceReclaimed))
1026	}
1027	_p_.traceSweep = false
1028}
1029
1030func traceGCMarkAssistStart() {
1031	traceEvent(traceEvGCMarkAssistStart, 1)
1032}
1033
1034func traceGCMarkAssistDone() {
1035	traceEvent(traceEvGCMarkAssistDone, -1)
1036}
1037
1038func traceGoCreate(newg *g, pc uintptr) {
1039	newg.traceseq = 0
1040	newg.tracelastp = getg().m.p
1041	// +PCQuantum because traceFrameForPC expects return PCs and subtracts PCQuantum.
1042	id := trace.stackTab.put([]uintptr{pc + sys.PCQuantum})
1043	traceEvent(traceEvGoCreate, 2, uint64(newg.goid), uint64(id))
1044}
1045
1046func traceGoStart() {
1047	_g_ := getg().m.curg
1048	_p_ := _g_.m.p
1049	_g_.traceseq++
1050	if _g_ == _p_.ptr().gcBgMarkWorker.ptr() {
1051		traceEvent(traceEvGoStartLabel, -1, uint64(_g_.goid), _g_.traceseq, trace.markWorkerLabels[_p_.ptr().gcMarkWorkerMode])
1052	} else if _g_.tracelastp == _p_ {
1053		traceEvent(traceEvGoStartLocal, -1, uint64(_g_.goid))
1054	} else {
1055		_g_.tracelastp = _p_
1056		traceEvent(traceEvGoStart, -1, uint64(_g_.goid), _g_.traceseq)
1057	}
1058}
1059
1060func traceGoEnd() {
1061	traceEvent(traceEvGoEnd, -1)
1062}
1063
1064func traceGoSched() {
1065	_g_ := getg()
1066	_g_.tracelastp = _g_.m.p
1067	traceEvent(traceEvGoSched, 1)
1068}
1069
1070func traceGoPreempt() {
1071	_g_ := getg()
1072	_g_.tracelastp = _g_.m.p
1073	traceEvent(traceEvGoPreempt, 1)
1074}
1075
1076func traceGoPark(traceEv byte, skip int) {
1077	if traceEv&traceFutileWakeup != 0 {
1078		traceEvent(traceEvFutileWakeup, -1)
1079	}
1080	traceEvent(traceEv & ^traceFutileWakeup, skip)
1081}
1082
1083func traceGoUnpark(gp *g, skip int) {
1084	_p_ := getg().m.p
1085	gp.traceseq++
1086	if gp.tracelastp == _p_ {
1087		traceEvent(traceEvGoUnblockLocal, skip, uint64(gp.goid))
1088	} else {
1089		gp.tracelastp = _p_
1090		traceEvent(traceEvGoUnblock, skip, uint64(gp.goid), gp.traceseq)
1091	}
1092}
1093
1094func traceGoSysCall() {
1095	traceEvent(traceEvGoSysCall, 1)
1096}
1097
1098func traceGoSysExit(ts int64) {
1099	if ts != 0 && ts < trace.ticksStart {
1100		// There is a race between the code that initializes sysexitticks
1101		// (in exitsyscall, which runs without a P, and therefore is not
1102		// stopped with the rest of the world) and the code that initializes
1103		// a new trace. The recorded sysexitticks must therefore be treated
1104		// as "best effort". If they are valid for this trace, then great,
1105		// use them for greater accuracy. But if they're not valid for this
1106		// trace, assume that the trace was started after the actual syscall
1107		// exit (but before we actually managed to start the goroutine,
1108		// aka right now), and assign a fresh time stamp to keep the log consistent.
1109		ts = 0
1110	}
1111	_g_ := getg().m.curg
1112	_g_.traceseq++
1113	_g_.tracelastp = _g_.m.p
1114	traceEvent(traceEvGoSysExit, -1, uint64(_g_.goid), _g_.traceseq, uint64(ts)/traceTickDiv)
1115}
1116
1117func traceGoSysBlock(pp *p) {
1118	// Sysmon and stopTheWorld can declare syscalls running on remote Ps as blocked,
1119	// to handle this we temporary employ the P.
1120	mp := acquirem()
1121	oldp := mp.p
1122	mp.p.set(pp)
1123	traceEvent(traceEvGoSysBlock, -1)
1124	mp.p = oldp
1125	releasem(mp)
1126}
1127
1128func traceHeapAlloc() {
1129	traceEvent(traceEvHeapAlloc, -1, memstats.heap_live)
1130}
1131
1132func traceNextGC() {
1133	if memstats.next_gc == ^uint64(0) {
1134		// Heap-based triggering is disabled.
1135		traceEvent(traceEvNextGC, -1, 0)
1136	} else {
1137		traceEvent(traceEvNextGC, -1, memstats.next_gc)
1138	}
1139}
1140
1141// To access runtime functions from runtime/trace.
1142// See runtime/trace/annotation.go
1143
1144//go:linkname trace_userTaskCreate runtime/trace.userTaskCreate
1145func trace_userTaskCreate(id, parentID uint64, taskType string) {
1146	if !trace.enabled {
1147		return
1148	}
1149
1150	// Same as in traceEvent.
1151	mp, pid, bufp := traceAcquireBuffer()
1152	if !trace.enabled && !mp.startingtrace {
1153		traceReleaseBuffer(pid)
1154		return
1155	}
1156
1157	typeStringID, bufp := traceString(bufp, pid, taskType)
1158	traceEventLocked(0, mp, pid, bufp, traceEvUserTaskCreate, 3, id, parentID, typeStringID)
1159	traceReleaseBuffer(pid)
1160}
1161
1162//go:linkname trace_userTaskEnd runtime/trace.userTaskEnd
1163func trace_userTaskEnd(id uint64) {
1164	traceEvent(traceEvUserTaskEnd, 2, id)
1165}
1166
1167//go:linkname trace_userRegion runtime/trace.userRegion
1168func trace_userRegion(id, mode uint64, name string) {
1169	if !trace.enabled {
1170		return
1171	}
1172
1173	mp, pid, bufp := traceAcquireBuffer()
1174	if !trace.enabled && !mp.startingtrace {
1175		traceReleaseBuffer(pid)
1176		return
1177	}
1178
1179	nameStringID, bufp := traceString(bufp, pid, name)
1180	traceEventLocked(0, mp, pid, bufp, traceEvUserRegion, 3, id, mode, nameStringID)
1181	traceReleaseBuffer(pid)
1182}
1183
1184//go:linkname trace_userLog runtime/trace.userLog
1185func trace_userLog(id uint64, category, message string) {
1186	if !trace.enabled {
1187		return
1188	}
1189
1190	mp, pid, bufp := traceAcquireBuffer()
1191	if !trace.enabled && !mp.startingtrace {
1192		traceReleaseBuffer(pid)
1193		return
1194	}
1195
1196	categoryID, bufp := traceString(bufp, pid, category)
1197
1198	extraSpace := traceBytesPerNumber + len(message) // extraSpace for the value string
1199	traceEventLocked(extraSpace, mp, pid, bufp, traceEvUserLog, 3, id, categoryID)
1200	// traceEventLocked reserved extra space for val and len(val)
1201	// in buf, so buf now has room for the following.
1202	buf := bufp.ptr()
1203
1204	// double-check the message and its length can fit.
1205	// Otherwise, truncate the message.
1206	slen := len(message)
1207	if room := len(buf.arr) - buf.pos; room < slen+traceBytesPerNumber {
1208		slen = room
1209	}
1210	buf.varint(uint64(slen))
1211	buf.pos += copy(buf.arr[buf.pos:], message[:slen])
1212
1213	traceReleaseBuffer(pid)
1214}
1215