Debian Codegraph @

trace/tracev1.go

raw symbols SCIP
1 // Copyright 2024 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 // Code generated by "gen.bash" from internal/trace; DO NOT EDIT.
6
7 //go:build go1.23
8
9 // This file implements conversion from v1 (Go 1.11–Go 1.21) traces to the v2
10 // format (Go 1.22+).
11 //
12 // Most events have direct equivalents in v2, at worst requiring arguments to
13 // be reordered. Some events, such as GoWaiting need to look ahead for follow-up
14 // events to determine the correct translation. GoSyscall, which is an
15 // instantaneous event, gets turned into a 1 ns long pair of
16 // GoSyscallStart+GoSyscallEnd, unless we observe a GoSysBlock, in which case we
17 // emit a GoSyscallStart+GoSyscallEndBlocked pair with the correct duration
18 // (i.e. starting at the original GoSyscall).
19 //
20 // The resulting trace treats the trace v1 as a single, large generation,
21 // sharing a single evTable for all events.
22 //
23 // We use a new (compared to what was used for 'go tool trace' in earlier
24 // versions of Go) parser for v1 traces that is optimized for speed, low memory
25 // usage, and minimal GC pressure. It allocates events in batches so that even
26 // though we have to load the entire trace into memory, the conversion process
27 // shouldn't result in a doubling of memory usage, even if all converted events
28 // are kept alive, as we free batches once we're done with them.
29 //
30 // The conversion process is lossless.
31
32 package trace
33
34 import (
35 "errors"
36 "fmt"
37 "golang.org/x/exp/trace/internal/tracev1"
38 "golang.org/x/exp/trace/internal/tracev2"
39 "io"
40 )
41
42 type traceV1Converter struct {
43 trace tracev1.Trace
44 evt *evTable
45 preInit bool
46 createdPreInit map[GoID]struct{}
47 events tracev1.Events
48 extra []Event
49 extraArr [3]Event
50 tasks map[TaskID]taskState
51 seenProcs map[ProcID]struct{}
52 lastTs Time
53 procMs map[ProcID]ThreadID
54 lastStwReason uint64
55
56 inlineToStringID []uint64
57 builtinToStringID []uint64
58 }
59
60 const (
61 // Block reasons
62 sForever = iota
63 sPreempted
64 sGosched
65 sSleep
66 sChanSend
67 sChanRecv
68 sNetwork
69 sSync
70 sSyncCond
71 sSelect
72 sEmpty
73 sMarkAssistWait
74
75 // STW kinds
76 sSTWUnknown
77 sSTWGCMarkTermination
78 sSTWGCSweepTermination
79 sSTWWriteHeapDump
80 sSTWGoroutineProfile
81 sSTWGoroutineProfileCleanup
82 sSTWAllGoroutinesStackTrace
83 sSTWReadMemStats
84 sSTWAllThreadsSyscall
85 sSTWGOMAXPROCS
86 sSTWStartTrace
87 sSTWStopTrace
88 sSTWCountPagesInUse
89 sSTWReadMetricsSlow
90 sSTWReadMemStatsSlow
91 sSTWPageCachePagesLeaked
92 sSTWResetDebugLog
93
94 sLast
95 )
96
97 func (it *traceV1Converter) init(pr tracev1.Trace) error {
98 it.trace = pr
99 it.preInit = true
100 it.createdPreInit = make(map[GoID]struct{})
101 it.evt = &evTable{pcs: make(map[uint64]frame)}
102 it.events = pr.Events
103 it.extra = it.extraArr[:0]
104 it.tasks = make(map[TaskID]taskState)
105 it.seenProcs = make(map[ProcID]struct{})
106 it.procMs = make(map[ProcID]ThreadID)
107 it.lastTs = -1
108
109 evt := it.evt
110
111 // Convert from trace v1's Strings map to our dataTable.
112 var max uint64
113 for id, s := range pr.Strings {
114 evt.strings.insert(stringID(id), s)
115 if id > max {
116 max = id
117 }
118 }
119 pr.Strings = nil
120
121 // Add all strings used for UserLog. In the trace v1 format, these were
122 // stored inline and didn't have IDs. We generate IDs for them.
123 if max+uint64(len(pr.InlineStrings)) < max {
124 return errors.New("trace contains too many strings")
125 }
126 var addErr error
127 add := func(id stringID, s string) {
128 if err := evt.strings.insert(id, s); err != nil && addErr == nil {
129 addErr = err
130 }
131 }
132 for id, s := range pr.InlineStrings {
133 nid := max + 1 + uint64(id)
134 it.inlineToStringID = append(it.inlineToStringID, nid)
135 add(stringID(nid), s)
136 }
137 max += uint64(len(pr.InlineStrings))
138 pr.InlineStrings = nil
139
140 // Add strings that the converter emits explicitly.
141 if max+uint64(sLast) < max {
142 return errors.New("trace contains too many strings")
143 }
144 it.builtinToStringID = make([]uint64, sLast)
145 addBuiltin := func(c int, s string) {
146 nid := max + 1 + uint64(c)
147 it.builtinToStringID[c] = nid
148 add(stringID(nid), s)
149 }
150 addBuiltin(sForever, "forever")
151 addBuiltin(sPreempted, "preempted")
152 addBuiltin(sGosched, "runtime.Gosched")
153 addBuiltin(sSleep, "sleep")
154 addBuiltin(sChanSend, "chan send")
155 addBuiltin(sChanRecv, "chan receive")
156 addBuiltin(sNetwork, "network")
157 addBuiltin(sSync, "sync")
158 addBuiltin(sSyncCond, "sync.(*Cond).Wait")
159 addBuiltin(sSelect, "select")
160 addBuiltin(sEmpty, "")
161 addBuiltin(sMarkAssistWait, "GC mark assist wait for work")
162 addBuiltin(sSTWUnknown, "")
163 addBuiltin(sSTWGCMarkTermination, "GC mark termination")
164 addBuiltin(sSTWGCSweepTermination, "GC sweep termination")
165 addBuiltin(sSTWWriteHeapDump, "write heap dump")
166 addBuiltin(sSTWGoroutineProfile, "goroutine profile")
167 addBuiltin(sSTWGoroutineProfileCleanup, "goroutine profile cleanup")
168 addBuiltin(sSTWAllGoroutinesStackTrace, "all goroutine stack trace")
169 addBuiltin(sSTWReadMemStats, "read mem stats")
170 addBuiltin(sSTWAllThreadsSyscall, "AllThreadsSyscall")
171 addBuiltin(sSTWGOMAXPROCS, "GOMAXPROCS")
172 addBuiltin(sSTWStartTrace, "start trace")
173 addBuiltin(sSTWStopTrace, "stop trace")
174 addBuiltin(sSTWCountPagesInUse, "CountPagesInUse (test)")
175 addBuiltin(sSTWReadMetricsSlow, "ReadMetricsSlow (test)")
176 addBuiltin(sSTWReadMemStatsSlow, "ReadMemStatsSlow (test)")
177 addBuiltin(sSTWPageCachePagesLeaked, "PageCachePagesLeaked (test)")
178 addBuiltin(sSTWResetDebugLog, "ResetDebugLog (test)")
179
180 if addErr != nil {
181 // This should be impossible but let's be safe.
182 return fmt.Errorf("couldn't add strings: %w", addErr)
183 }
184
185 it.evt.strings.compactify()
186
187 // Convert stacks.
188 for id, stk := range pr.Stacks {
189 evt.stacks.insert(stackID(id), stack{pcs: stk})
190 }
191
192 // OPT(dh): if we could share the frame type between this package and
193 // tracev1 we wouldn't have to copy the map.
194 for pc, f := range pr.PCs {
195 evt.pcs[pc] = frame{
196 pc: pc,
197 funcID: stringID(f.Fn),
198 fileID: stringID(f.File),
199 line: uint64(f.Line),
200 }
201 }
202 pr.Stacks = nil
203 pr.PCs = nil
204 evt.stacks.compactify()
205 return nil
206 }
207
208 // next returns the next event, io.EOF if there are no more events, or a
209 // descriptive error for invalid events.
210 func (it *traceV1Converter) next() (Event, error) {
211 if len(it.extra) > 0 {
212 ev := it.extra[0]
213 it.extra = it.extra[1:]
214
215 if len(it.extra) == 0 {
216 it.extra = it.extraArr[:0]
217 }
218 // Two events aren't allowed to fall on the same timestamp in the new API,
219 // but this may happen when we produce EvGoStatus events
220 if ev.base.time <= it.lastTs {
221 ev.base.time = it.lastTs + 1
222 }
223 it.lastTs = ev.base.time
224 return ev, nil
225 }
226
227 oev, ok := it.events.Pop()
228 if !ok {
229 return Event{}, io.EOF
230 }
231
232 ev, err := it.convertEvent(oev)
233
234 if err == errSkip {
235 return it.next()
236 } else if err != nil {
237 return Event{}, err
238 }
239
240 // Two events aren't allowed to fall on the same timestamp in the new API,
241 // but this may happen when we produce EvGoStatus events
242 if ev.base.time <= it.lastTs {
243 ev.base.time = it.lastTs + 1
244 }
245 it.lastTs = ev.base.time
246 return ev, nil
247 }
248
249 var errSkip = errors.New("skip event")
250
251 // convertEvent converts an event from the trace v1 format to zero or more
252 // events in the new format. Most events translate 1 to 1. Some events don't
253 // result in an event right away, in which case convertEvent returns errSkip.
254 // Some events result in more than one new event; in this case, convertEvent
255 // returns the first event and stores additional events in it.extra. When
256 // encountering events that tracev1 shouldn't be able to emit, ocnvertEvent
257 // returns a descriptive error.
258 func (it *traceV1Converter) convertEvent(ev *tracev1.Event) (OUT Event, ERR error) {
259 var mappedType tracev2.EventType
260 var mappedArgs timedEventArgs
261 copy(mappedArgs[:], ev.Args[:])
262
263 switch ev.Type {
264 case tracev1.EvGomaxprocs:
265 mappedType = tracev2.EvProcsChange
266 if it.preInit {
267 // The first EvGomaxprocs signals the end of trace initialization. At this point we've seen
268 // all goroutines that already existed at trace begin.
269 it.preInit = false
270 for gid := range it.createdPreInit {
271 // These are goroutines that already existed when tracing started but for which we
272 // received neither GoWaiting, GoInSyscall, or GoStart. These are goroutines that are in
273 // the states _Gidle or _Grunnable.
274 it.extra = append(it.extra, Event{
275 ctx: schedCtx{
276 // G: GoID(gid),
277 G: NoGoroutine,
278 P: NoProc,
279 M: NoThread,
280 },
281 table: it.evt,
282 base: baseEvent{
283 typ: tracev2.EvGoStatus,
284 time: Time(ev.Ts),
285 args: timedEventArgs{uint64(gid), ^uint64(0), uint64(tracev2.GoRunnable)},
286 },
287 })
288 }
289 it.createdPreInit = nil
290 return Event{}, errSkip
291 }
292 case tracev1.EvProcStart:
293 it.procMs[ProcID(ev.P)] = ThreadID(ev.Args[0])
294 if _, ok := it.seenProcs[ProcID(ev.P)]; ok {
295 mappedType = tracev2.EvProcStart
296 mappedArgs = timedEventArgs{uint64(ev.P)}
297 } else {
298 it.seenProcs[ProcID(ev.P)] = struct{}{}
299 mappedType = tracev2.EvProcStatus
300 mappedArgs = timedEventArgs{uint64(ev.P), uint64(tracev2.ProcRunning)}
301 }
302 case tracev1.EvProcStop:
303 if _, ok := it.seenProcs[ProcID(ev.P)]; ok {
304 mappedType = tracev2.EvProcStop
305 mappedArgs = timedEventArgs{uint64(ev.P)}
306 } else {
307 it.seenProcs[ProcID(ev.P)] = struct{}{}
308 mappedType = tracev2.EvProcStatus
309 mappedArgs = timedEventArgs{uint64(ev.P), uint64(tracev2.ProcIdle)}
310 }
311 case tracev1.EvGCStart:
312 mappedType = tracev2.EvGCBegin
313 case tracev1.EvGCDone:
314 mappedType = tracev2.EvGCEnd
315 case tracev1.EvSTWStart:
316 sid := it.builtinToStringID[sSTWUnknown+it.trace.STWReason(ev.Args[0])]
317 it.lastStwReason = sid
318 mappedType = tracev2.EvSTWBegin
319 mappedArgs = timedEventArgs{uint64(sid)}
320 case tracev1.EvSTWDone:
321 mappedType = tracev2.EvSTWEnd
322 mappedArgs = timedEventArgs{it.lastStwReason}
323 case tracev1.EvGCSweepStart:
324 mappedType = tracev2.EvGCSweepBegin
325 case tracev1.EvGCSweepDone:
326 mappedType = tracev2.EvGCSweepEnd
327 case tracev1.EvGoCreate:
328 if it.preInit {
329 it.createdPreInit[GoID(ev.Args[0])] = struct{}{}
330 return Event{}, errSkip
331 }
332 mappedType = tracev2.EvGoCreate
333 case tracev1.EvGoStart:
334 if it.preInit {
335 mappedType = tracev2.EvGoStatus
336 mappedArgs = timedEventArgs{ev.Args[0], ^uint64(0), uint64(tracev2.GoRunning)}
337 delete(it.createdPreInit, GoID(ev.Args[0]))
338 } else {
339 mappedType = tracev2.EvGoStart
340 }
341 case tracev1.EvGoStartLabel:
342 it.extra = []Event{{
343 ctx: schedCtx{
344 G: GoID(ev.G),
345 P: ProcID(ev.P),
346 M: it.procMs[ProcID(ev.P)],
347 },
348 table: it.evt,
349 base: baseEvent{
350 typ: tracev2.EvGoLabel,
351 time: Time(ev.Ts),
352 args: timedEventArgs{ev.Args[2]},
353 },
354 }}
355 return Event{
356 ctx: schedCtx{
357 G: GoID(ev.G),
358 P: ProcID(ev.P),
359 M: it.procMs[ProcID(ev.P)],
360 },
361 table: it.evt,
362 base: baseEvent{
363 typ: tracev2.EvGoStart,
364 time: Time(ev.Ts),
365 args: mappedArgs,
366 },
367 }, nil
368 case tracev1.EvGoEnd:
369 mappedType = tracev2.EvGoDestroy
370 case tracev1.EvGoStop:
371 mappedType = tracev2.EvGoBlock
372 mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sForever]), uint64(ev.StkID)}
373 case tracev1.EvGoSched:
374 mappedType = tracev2.EvGoStop
375 mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sGosched]), uint64(ev.StkID)}
376 case tracev1.EvGoPreempt:
377 mappedType = tracev2.EvGoStop
378 mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sPreempted]), uint64(ev.StkID)}
379 case tracev1.EvGoSleep:
380 mappedType = tracev2.EvGoBlock
381 mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sSleep]), uint64(ev.StkID)}
382 case tracev1.EvGoBlock:
383 mappedType = tracev2.EvGoBlock
384 mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sEmpty]), uint64(ev.StkID)}
385 case tracev1.EvGoUnblock:
386 mappedType = tracev2.EvGoUnblock
387 case tracev1.EvGoBlockSend:
388 mappedType = tracev2.EvGoBlock
389 mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sChanSend]), uint64(ev.StkID)}
390 case tracev1.EvGoBlockRecv:
391 mappedType = tracev2.EvGoBlock
392 mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sChanRecv]), uint64(ev.StkID)}
393 case tracev1.EvGoBlockSelect:
394 mappedType = tracev2.EvGoBlock
395 mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sSelect]), uint64(ev.StkID)}
396 case tracev1.EvGoBlockSync:
397 mappedType = tracev2.EvGoBlock
398 mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sSync]), uint64(ev.StkID)}
399 case tracev1.EvGoBlockCond:
400 mappedType = tracev2.EvGoBlock
401 mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sSyncCond]), uint64(ev.StkID)}
402 case tracev1.EvGoBlockNet:
403 mappedType = tracev2.EvGoBlock
404 mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sNetwork]), uint64(ev.StkID)}
405 case tracev1.EvGoBlockGC:
406 mappedType = tracev2.EvGoBlock
407 mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sMarkAssistWait]), uint64(ev.StkID)}
408 case tracev1.EvGoSysCall:
409 // Look for the next event for the same G to determine if the syscall
410 // blocked.
411 blocked := false
412 it.events.All()(func(nev *tracev1.Event) bool {
413 if nev.G != ev.G {
414 return true
415 }
416 // After an EvGoSysCall, the next event on the same G will either be
417 // EvGoSysBlock to denote a blocking syscall, or some other event
418 // (or the end of the trace) if the syscall didn't block.
419 if nev.Type == tracev1.EvGoSysBlock {
420 blocked = true
421 }
422 return false
423 })
424 if blocked {
425 mappedType = tracev2.EvGoSyscallBegin
426 mappedArgs = timedEventArgs{1: uint64(ev.StkID)}
427 } else {
428 // Convert the old instantaneous syscall event to a pair of syscall
429 // begin and syscall end and give it the shortest possible duration,
430 // 1ns.
431 out1 := Event{
432 ctx: schedCtx{
433 G: GoID(ev.G),
434 P: ProcID(ev.P),
435 M: it.procMs[ProcID(ev.P)],
436 },
437 table: it.evt,
438 base: baseEvent{
439 typ: tracev2.EvGoSyscallBegin,
440 time: Time(ev.Ts),
441 args: timedEventArgs{1: uint64(ev.StkID)},
442 },
443 }
444
445 out2 := Event{
446 ctx: out1.ctx,
447 table: it.evt,
448 base: baseEvent{
449 typ: tracev2.EvGoSyscallEnd,
450 time: Time(ev.Ts + 1),
451 args: timedEventArgs{},
452 },
453 }
454
455 it.extra = append(it.extra, out2)
456 return out1, nil
457 }
458
459 case tracev1.EvGoSysExit:
460 mappedType = tracev2.EvGoSyscallEndBlocked
461 case tracev1.EvGoSysBlock:
462 return Event{}, errSkip
463 case tracev1.EvGoWaiting:
464 mappedType = tracev2.EvGoStatus
465 mappedArgs = timedEventArgs{ev.Args[0], ^uint64(0), uint64(tracev2.GoWaiting)}
466 delete(it.createdPreInit, GoID(ev.Args[0]))
467 case tracev1.EvGoInSyscall:
468 mappedType = tracev2.EvGoStatus
469 // In the new tracer, GoStatus with GoSyscall knows what thread the
470 // syscall is on. In trace v1, EvGoInSyscall doesn't contain that
471 // information and all we can do here is specify NoThread.
472 mappedArgs = timedEventArgs{ev.Args[0], ^uint64(0), uint64(tracev2.GoSyscall)}
473 delete(it.createdPreInit, GoID(ev.Args[0]))
474 case tracev1.EvHeapAlloc:
475 mappedType = tracev2.EvHeapAlloc
476 case tracev1.EvHeapGoal:
477 mappedType = tracev2.EvHeapGoal
478 case tracev1.EvGCMarkAssistStart:
479 mappedType = tracev2.EvGCMarkAssistBegin
480 case tracev1.EvGCMarkAssistDone:
481 mappedType = tracev2.EvGCMarkAssistEnd
482 case tracev1.EvUserTaskCreate:
483 mappedType = tracev2.EvUserTaskBegin
484 parent := ev.Args[1]
485 if parent == 0 {
486 parent = uint64(NoTask)
487 }
488 mappedArgs = timedEventArgs{ev.Args[0], parent, ev.Args[2], uint64(ev.StkID)}
489 name, _ := it.evt.strings.get(stringID(ev.Args[2]))
490 it.tasks[TaskID(ev.Args[0])] = taskState{name: name, parentID: TaskID(ev.Args[1])}
491 case tracev1.EvUserTaskEnd:
492 mappedType = tracev2.EvUserTaskEnd
493 // Event.Task expects the parent and name to be smuggled in extra args
494 // and as extra strings.
495 ts, ok := it.tasks[TaskID(ev.Args[0])]
496 if ok {
497 delete(it.tasks, TaskID(ev.Args[0]))
498 mappedArgs = timedEventArgs{
499 ev.Args[0],
500 ev.Args[1],
501 uint64(ts.parentID),
502 uint64(it.evt.addExtraString(ts.name)),
503 }
504 } else {
505 mappedArgs = timedEventArgs{ev.Args[0], ev.Args[1], uint64(NoTask), uint64(it.evt.addExtraString(""))}
506 }
507 case tracev1.EvUserRegion:
508 switch ev.Args[1] {
509 case 0: // start
510 mappedType = tracev2.EvUserRegionBegin
511 case 1: // end
512 mappedType = tracev2.EvUserRegionEnd
513 }
514 mappedArgs = timedEventArgs{ev.Args[0], ev.Args[2], uint64(ev.StkID)}
515 case tracev1.EvUserLog:
516 mappedType = tracev2.EvUserLog
517 mappedArgs = timedEventArgs{ev.Args[0], ev.Args[1], it.inlineToStringID[ev.Args[3]], uint64(ev.StkID)}
518 case tracev1.EvCPUSample:
519 mappedType = tracev2.EvCPUSample
520 // When emitted by the Go 1.22 tracer, CPU samples have 5 arguments:
521 // timestamp, M, P, G, stack. However, after they get turned into Event,
522 // they have the arguments stack, M, P, G.
523 //
524 // In Go 1.21, CPU samples did not have Ms.
525 mappedArgs = timedEventArgs{uint64(ev.StkID), ^uint64(0), uint64(ev.P), ev.G}
526 default:
527 return Event{}, fmt.Errorf("unexpected event type %v", ev.Type)
528 }
529
530 if tracev1.EventDescriptions[ev.Type].Stack {
531 if stackIDs := tracev2.Specs()[mappedType].StackIDs; len(stackIDs) > 0 {
532 mappedArgs[stackIDs[0]-1] = uint64(ev.StkID)
533 }
534 }
535
536 m := NoThread
537 if ev.P != -1 && ev.Type != tracev1.EvCPUSample {
538 if t, ok := it.procMs[ProcID(ev.P)]; ok {
539 m = ThreadID(t)
540 }
541 }
542 if ev.Type == tracev1.EvProcStop {
543 delete(it.procMs, ProcID(ev.P))
544 }
545 g := GoID(ev.G)
546 if g == 0 {
547 g = NoGoroutine
548 }
549 out := Event{
550 ctx: schedCtx{
551 G: GoID(g),
552 P: ProcID(ev.P),
553 M: m,
554 },
555 table: it.evt,
556 base: baseEvent{
557 typ: mappedType,
558 time: Time(ev.Ts),
559 args: mappedArgs,
560 },
561 }
562 return out, nil
563 }
564
565 // convertV1Trace takes a fully loaded trace in the v1 trace format and
566 // returns an iterator over events in the new format.
567 func convertV1Trace(pr tracev1.Trace) *traceV1Converter {
568 it := &traceV1Converter{}
569 it.init(pr)
570 return it
571 }