Debian Codegraph @

trace/generation.go

raw symbols SCIP
1 // Copyright 2023 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 package trace
10
11 import (
12 "bufio"
13 "bytes"
14 "cmp"
15 "encoding/binary"
16 "errors"
17 "fmt"
18 "io"
19 "slices"
20 "strings"
21 "time"
22
23 "golang.org/x/exp/trace/internal/tracev2"
24 "golang.org/x/exp/trace/internal/version"
25 )
26
27 // generation contains all the trace data for a single
28 // trace generation. It is purely data: it does not
29 // track any parse state nor does it contain a cursor
30 // into the generation.
31 type generation struct {
32 gen uint64
33 batches map[ThreadID][]batch
34 batchMs []ThreadID
35 cpuSamples []cpuSample
36 minTs timestamp
37 *evTable
38 }
39
40 // readGeneration buffers and decodes the structural elements of a trace generation
41 // out of r.
42 func readGeneration(r *bufio.Reader, ver version.Version) (*generation, error) {
43 if ver < version.Go126 {
44 return nil, errors.New("internal error: readGeneration called for <1.26 trace")
45 }
46 g := &generation{
47 evTable: &evTable{
48 pcs: make(map[uint64]frame),
49 },
50 batches: make(map[ThreadID][]batch),
51 }
52
53 // Read batches one at a time until we either hit the next generation.
54 for {
55 b, gen, err := readBatch(r)
56 if err == io.EOF {
57 if len(g.batches) != 0 {
58 return nil, errors.New("incomplete generation found; trace likely truncated")
59 }
60 return nil, nil // All done.
61 }
62 if err != nil {
63 return nil, err
64 }
65 if g.gen == 0 {
66 // Initialize gen.
67 g.gen = gen
68 }
69 if b.isEndOfGeneration() {
70 break
71 }
72 if gen == 0 {
73 // 0 is a sentinel used by the runtime, so we'll never see it.
74 return nil, fmt.Errorf("invalid generation number %d", gen)
75 }
76 if gen != g.gen {
77 return nil, fmt.Errorf("broken trace: missing end-of-generation event, or generations are interleaved")
78 }
79 if g.minTs == 0 || b.time < g.minTs {
80 g.minTs = b.time
81 }
82 if err := processBatch(g, b, ver); err != nil {
83 return nil, err
84 }
85 }
86
87 // Check some invariants.
88 if g.freq == 0 {
89 return nil, fmt.Errorf("no frequency event found")
90 }
91 if !g.hasClockSnapshot {
92 return nil, fmt.Errorf("no clock snapshot event found")
93 }
94
95 // N.B. Trust that the batch order is correct. We can't validate the batch order
96 // by timestamp because the timestamps could just be plain wrong. The source of
97 // truth is the order things appear in the trace and the partial order sequence
98 // numbers on certain events. If it turns out the batch order is actually incorrect
99 // we'll very likely fail to advance a partial order from the frontier.
100
101 // Compactify stacks and strings for better lookup performance later.
102 g.stacks.compactify()
103 g.strings.compactify()
104
105 // Validate stacks.
106 if err := validateStackStrings(&g.stacks, &g.strings, g.pcs); err != nil {
107 return nil, err
108 }
109
110 // Now that we have the frequency, fix up CPU samples.
111 fixUpCPUSamples(g.cpuSamples, g.freq)
112 return g, nil
113 }
114
115 // spilledBatch represents a batch that was read out for the next generation,
116 // while reading the previous one. It's passed on when parsing the next
117 // generation.
118 //
119 // Used only for trace versions < Go126.
120 type spilledBatch struct {
121 gen uint64
122 *batch
123 }
124
125 // readGenerationWithSpill buffers and decodes the structural elements of a trace generation
126 // out of r. spill is the first batch of the new generation (already buffered and
127 // parsed from reading the last generation). Returns the generation and the first
128 // batch read of the next generation, if any.
129 //
130 // If gen is non-nil, it is valid and must be processed before handling the returned
131 // error.
132 func readGenerationWithSpill(r *bufio.Reader, spill *spilledBatch, ver version.Version) (*generation, *spilledBatch, error) {
133 if ver >= version.Go126 {
134 return nil, nil, errors.New("internal error: readGenerationWithSpill called for Go 1.26+ trace")
135 }
136 g := &generation{
137 evTable: &evTable{
138 pcs: make(map[uint64]frame),
139 },
140 batches: make(map[ThreadID][]batch),
141 }
142 // Process the spilled batch.
143 if spill != nil {
144 // Process the spilled batch, which contains real data.
145 g.gen = spill.gen
146 g.minTs = spill.batch.time
147 if err := processBatch(g, *spill.batch, ver); err != nil {
148 return nil, nil, err
149 }
150 spill = nil
151 }
152 // Read batches one at a time until we either hit the next generation.
153 var spillErr error
154 for {
155 b, gen, err := readBatch(r)
156 if err == io.EOF {
157 break
158 }
159 if err != nil {
160 if g.gen != 0 {
161 // This may be an error reading the first batch of the next generation.
162 // This is fine. Let's forge ahead assuming that what we've got so
163 // far is fine.
164 spillErr = err
165 break
166 }
167 return nil, nil, err
168 }
169 if gen == 0 {
170 // 0 is a sentinel used by the runtime, so we'll never see it.
171 return nil, nil, fmt.Errorf("invalid generation number %d", gen)
172 }
173 if g.gen == 0 {
174 // Initialize gen.
175 g.gen = gen
176 }
177 if gen == g.gen+1 {
178 // TODO: Increment the generation with wraparound the same way the runtime does.
179 spill = &spilledBatch{gen: gen, batch: &b}
180 break
181 }
182 if gen != g.gen {
183 // N.B. Fail as fast as possible if we see this. At first it
184 // may seem prudent to be fault-tolerant and assume we have a
185 // complete generation, parsing and returning that first. However,
186 // if the batches are mixed across generations then it's likely
187 // we won't be able to parse this generation correctly at all.
188 // Rather than return a cryptic error in that case, indicate the
189 // problem as soon as we see it.
190 return nil, nil, fmt.Errorf("generations out of order")
191 }
192 if g.minTs == 0 || b.time < g.minTs {
193 g.minTs = b.time
194 }
195 if err := processBatch(g, b, ver); err != nil {
196 return nil, nil, err
197 }
198 }
199
200 // Check some invariants.
201 if g.freq == 0 {
202 return nil, nil, fmt.Errorf("no frequency event found")
203 }
204 if ver >= version.Go125 && !g.hasClockSnapshot {
205 return nil, nil, fmt.Errorf("no clock snapshot event found")
206 }
207
208 // N.B. Trust that the batch order is correct. We can't validate the batch order
209 // by timestamp because the timestamps could just be plain wrong. The source of
210 // truth is the order things appear in the trace and the partial order sequence
211 // numbers on certain events. If it turns out the batch order is actually incorrect
212 // we'll very likely fail to advance a partial order from the frontier.
213
214 // Compactify stacks and strings for better lookup performance later.
215 g.stacks.compactify()
216 g.strings.compactify()
217
218 // Validate stacks.
219 if err := validateStackStrings(&g.stacks, &g.strings, g.pcs); err != nil {
220 return nil, nil, err
221 }
222
223 // Now that we have the frequency, fix up CPU samples.
224 fixUpCPUSamples(g.cpuSamples, g.freq)
225 return g, spill, spillErr
226 }
227
228 // processBatch adds the batch to the generation.
229 func processBatch(g *generation, b batch, ver version.Version) error {
230 switch {
231 case b.isStringsBatch():
232 if err := addStrings(&g.strings, b); err != nil {
233 return err
234 }
235 case b.isStacksBatch():
236 if err := addStacks(&g.stacks, g.pcs, b); err != nil {
237 return err
238 }
239 case b.isCPUSamplesBatch():
240 samples, err := addCPUSamples(g.cpuSamples, b)
241 if err != nil {
242 return err
243 }
244 g.cpuSamples = samples
245 case b.isSyncBatch(ver):
246 if err := setSyncBatch(&g.sync, b, ver); err != nil {
247 return err
248 }
249 case b.exp != tracev2.NoExperiment:
250 if g.expBatches == nil {
251 g.expBatches = make(map[tracev2.Experiment][]ExperimentalBatch)
252 }
253 if err := addExperimentalBatch(g.expBatches, b); err != nil {
254 return err
255 }
256 case b.isEndOfGeneration():
257 return errors.New("internal error: unexpectedly processing EndOfGeneration; broken trace?")
258 default:
259 if _, ok := g.batches[b.m]; !ok {
260 g.batchMs = append(g.batchMs, b.m)
261 }
262 g.batches[b.m] = append(g.batches[b.m], b)
263 }
264 return nil
265 }
266
267 // validateStackStrings makes sure all the string references in
268 // the stack table are present in the string table.
269 func validateStackStrings(
270 stacks *dataTable[stackID, stack],
271 strings *dataTable[stringID, string],
272 frames map[uint64]frame,
273 ) error {
274 var err error
275 stacks.forEach(func(id stackID, stk stack) bool {
276 for _, pc := range stk.pcs {
277 frame, ok := frames[pc]
278 if !ok {
279 err = fmt.Errorf("found unknown pc %x for stack %d", pc, id)
280 return false
281 }
282 _, ok = strings.get(frame.funcID)
283 if !ok {
284 err = fmt.Errorf("found invalid func string ID %d for stack %d", frame.funcID, id)
285 return false
286 }
287 _, ok = strings.get(frame.fileID)
288 if !ok {
289 err = fmt.Errorf("found invalid file string ID %d for stack %d", frame.fileID, id)
290 return false
291 }
292 }
293 return true
294 })
295 return err
296 }
297
298 // addStrings takes a batch whose first byte is an EvStrings event
299 // (indicating that the batch contains only strings) and adds each
300 // string contained therein to the provided strings map.
301 func addStrings(stringTable *dataTable[stringID, string], b batch) error {
302 if !b.isStringsBatch() {
303 return fmt.Errorf("internal error: addStrings called on non-string batch")
304 }
305 r := bytes.NewReader(b.data)
306 hdr, err := r.ReadByte() // Consume the EvStrings byte.
307 if err != nil || tracev2.EventType(hdr) != tracev2.EvStrings {
308 return fmt.Errorf("missing strings batch header")
309 }
310
311 var sb strings.Builder
312 for r.Len() != 0 {
313 // Read the header.
314 ev, err := r.ReadByte()
315 if err != nil {
316 return err
317 }
318 if tracev2.EventType(ev) != tracev2.EvString {
319 return fmt.Errorf("expected string event, got %d", ev)
320 }
321
322 // Read the string's ID.
323 id, err := binary.ReadUvarint(r)
324 if err != nil {
325 return err
326 }
327
328 // Read the string's length.
329 len, err := binary.ReadUvarint(r)
330 if err != nil {
331 return err
332 }
333 if len > tracev2.MaxEventTrailerDataSize {
334 return fmt.Errorf("invalid string size %d, maximum is %d", len, tracev2.MaxEventTrailerDataSize)
335 }
336
337 // Copy out the string.
338 n, err := io.CopyN(&sb, r, int64(len))
339 if n != int64(len) {
340 return fmt.Errorf("failed to read full string: read %d but wanted %d", n, len)
341 }
342 if err != nil {
343 return fmt.Errorf("copying string data: %w", err)
344 }
345
346 // Add the string to the map.
347 s := sb.String()
348 sb.Reset()
349 if err := stringTable.insert(stringID(id), s); err != nil {
350 return err
351 }
352 }
353 return nil
354 }
355
356 // addStacks takes a batch whose first byte is an EvStacks event
357 // (indicating that the batch contains only stacks) and adds each
358 // string contained therein to the provided stacks map.
359 func addStacks(stackTable *dataTable[stackID, stack], pcs map[uint64]frame, b batch) error {
360 if !b.isStacksBatch() {
361 return fmt.Errorf("internal error: addStacks called on non-stacks batch")
362 }
363 r := bytes.NewReader(b.data)
364 hdr, err := r.ReadByte() // Consume the EvStacks byte.
365 if err != nil || tracev2.EventType(hdr) != tracev2.EvStacks {
366 return fmt.Errorf("missing stacks batch header")
367 }
368
369 for r.Len() != 0 {
370 // Read the header.
371 ev, err := r.ReadByte()
372 if err != nil {
373 return err
374 }
375 if tracev2.EventType(ev) != tracev2.EvStack {
376 return fmt.Errorf("expected stack event, got %d", ev)
377 }
378
379 // Read the stack's ID.
380 id, err := binary.ReadUvarint(r)
381 if err != nil {
382 return err
383 }
384
385 // Read how many frames are in each stack.
386 nFrames, err := binary.ReadUvarint(r)
387 if err != nil {
388 return err
389 }
390 if nFrames > tracev2.MaxFramesPerStack {
391 return fmt.Errorf("invalid stack size %d, maximum is %d", nFrames, tracev2.MaxFramesPerStack)
392 }
393
394 // Each frame consists of 4 fields: pc, funcID (string), fileID (string), line.
395 frames := make([]uint64, 0, nFrames)
396 for i := uint64(0); i < nFrames; i++ {
397 // Read the frame data.
398 pc, err := binary.ReadUvarint(r)
399 if err != nil {
400 return fmt.Errorf("reading frame %d's PC for stack %d: %w", i+1, id, err)
401 }
402 funcID, err := binary.ReadUvarint(r)
403 if err != nil {
404 return fmt.Errorf("reading frame %d's funcID for stack %d: %w", i+1, id, err)
405 }
406 fileID, err := binary.ReadUvarint(r)
407 if err != nil {
408 return fmt.Errorf("reading frame %d's fileID for stack %d: %w", i+1, id, err)
409 }
410 line, err := binary.ReadUvarint(r)
411 if err != nil {
412 return fmt.Errorf("reading frame %d's line for stack %d: %w", i+1, id, err)
413 }
414 frames = append(frames, pc)
415
416 if _, ok := pcs[pc]; !ok {
417 pcs[pc] = frame{
418 pc: pc,
419 funcID: stringID(funcID),
420 fileID: stringID(fileID),
421 line: line,
422 }
423 }
424 }
425
426 // Add the stack to the map.
427 if err := stackTable.insert(stackID(id), stack{pcs: frames}); err != nil {
428 return err
429 }
430 }
431 return nil
432 }
433
434 // addCPUSamples takes a batch whose first byte is an EvCPUSamples event
435 // (indicating that the batch contains only CPU samples) and adds each
436 // sample contained therein to the provided samples list.
437 func addCPUSamples(samples []cpuSample, b batch) ([]cpuSample, error) {
438 if !b.isCPUSamplesBatch() {
439 return nil, fmt.Errorf("internal error: addCPUSamples called on non-CPU-sample batch")
440 }
441 r := bytes.NewReader(b.data)
442 hdr, err := r.ReadByte() // Consume the EvCPUSamples byte.
443 if err != nil || tracev2.EventType(hdr) != tracev2.EvCPUSamples {
444 return nil, fmt.Errorf("missing CPU samples batch header")
445 }
446
447 for r.Len() != 0 {
448 // Read the header.
449 ev, err := r.ReadByte()
450 if err != nil {
451 return nil, err
452 }
453 if tracev2.EventType(ev) != tracev2.EvCPUSample {
454 return nil, fmt.Errorf("expected CPU sample event, got %d", ev)
455 }
456
457 // Read the sample's timestamp.
458 ts, err := binary.ReadUvarint(r)
459 if err != nil {
460 return nil, err
461 }
462
463 // Read the sample's M.
464 m, err := binary.ReadUvarint(r)
465 if err != nil {
466 return nil, err
467 }
468 mid := ThreadID(m)
469
470 // Read the sample's P.
471 p, err := binary.ReadUvarint(r)
472 if err != nil {
473 return nil, err
474 }
475 pid := ProcID(p)
476
477 // Read the sample's G.
478 g, err := binary.ReadUvarint(r)
479 if err != nil {
480 return nil, err
481 }
482 goid := GoID(g)
483 if g == 0 {
484 goid = NoGoroutine
485 }
486
487 // Read the sample's stack.
488 s, err := binary.ReadUvarint(r)
489 if err != nil {
490 return nil, err
491 }
492
493 // Add the sample to the slice.
494 samples = append(samples, cpuSample{
495 schedCtx: schedCtx{
496 M: mid,
497 P: pid,
498 G: goid,
499 },
500 time: Time(ts), // N.B. this is really a "timestamp," not a Time.
501 stack: stackID(s),
502 })
503 }
504 return samples, nil
505 }
506
507 // sync holds the per-generation sync data.
508 type sync struct {
509 freq frequency
510 hasClockSnapshot bool
511 snapTime timestamp
512 snapMono uint64
513 snapWall time.Time
514 }
515
516 func setSyncBatch(s *sync, b batch, ver version.Version) error {
517 if !b.isSyncBatch(ver) {
518 return fmt.Errorf("internal error: setSyncBatch called on non-sync batch")
519 }
520 r := bytes.NewReader(b.data)
521 if ver >= version.Go125 {
522 hdr, err := r.ReadByte() // Consume the EvSync byte.
523 if err != nil || tracev2.EventType(hdr) != tracev2.EvSync {
524 return fmt.Errorf("missing sync batch header")
525 }
526 }
527
528 lastTs := b.time
529 for r.Len() != 0 {
530 // Read the header
531 ev, err := r.ReadByte()
532 if err != nil {
533 return err
534 }
535 et := tracev2.EventType(ev)
536 switch {
537 case et == tracev2.EvFrequency:
538 if s.freq != 0 {
539 return fmt.Errorf("found multiple frequency events")
540 }
541 // Read the frequency. It'll come out as timestamp units per second.
542 f, err := binary.ReadUvarint(r)
543 if err != nil {
544 return err
545 }
546 // Convert to nanoseconds per timestamp unit.
547 s.freq = frequency(1.0 / (float64(f) / 1e9))
548 case et == tracev2.EvClockSnapshot && ver >= version.Go125:
549 if s.hasClockSnapshot {
550 return fmt.Errorf("found multiple clock snapshot events")
551 }
552 s.hasClockSnapshot = true
553 // Read the EvClockSnapshot arguments.
554 tdiff, err := binary.ReadUvarint(r)
555 if err != nil {
556 return err
557 }
558 lastTs += timestamp(tdiff)
559 s.snapTime = lastTs
560 mono, err := binary.ReadUvarint(r)
561 if err != nil {
562 return err
563 }
564 s.snapMono = mono
565 sec, err := binary.ReadUvarint(r)
566 if err != nil {
567 return err
568 }
569 nsec, err := binary.ReadUvarint(r)
570 if err != nil {
571 return err
572 }
573 // TODO(felixge): In theory we could inject s.snapMono into the time
574 // value below to make it comparable. But there is no API for this
575 // in the time package right now.
576 s.snapWall = time.Unix(int64(sec), int64(nsec))
577 default:
578 return fmt.Errorf("expected frequency or clock snapshot event, got %d", ev)
579 }
580 }
581 return nil
582 }
583
584 // addExperimentalBatch takes an experimental batch and adds it to the list of experimental
585 // batches for the experiment its a part of.
586 func addExperimentalBatch(expBatches map[tracev2.Experiment][]ExperimentalBatch, b batch) error {
587 if b.exp == tracev2.NoExperiment {
588 return fmt.Errorf("internal error: addExperimentalBatch called on non-experimental batch")
589 }
590 expBatches[b.exp] = append(expBatches[b.exp], ExperimentalBatch{
591 Thread: b.m,
592 Data: b.data,
593 })
594 return nil
595 }
596
597 func fixUpCPUSamples(samples []cpuSample, freq frequency) {
598 // Fix up the CPU sample timestamps.
599 for i := range samples {
600 s := &samples[i]
601 s.time = freq.mul(timestamp(s.time))
602 }
603 // Sort the CPU samples.
604 slices.SortFunc(samples, func(a, b cpuSample) int {
605 return cmp.Compare(a.time, b.time)
606 })
607 }