Debian Codegraph @

trace/internal/testgen/trace.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 testgen
10
11 import (
12 "bytes"
13 "encoding/binary"
14 "fmt"
15 "os"
16 "regexp"
17 "strings"
18 "time"
19
20 "golang.org/x/exp/trace"
21 "golang.org/x/exp/trace/internal/raw"
22 "golang.org/x/exp/trace/internal/tracev2"
23 "golang.org/x/exp/trace/internal/version"
24 "golang.org/x/tools/txtar"
25 )
26
27 func Main(ver version.Version, f func(*Trace)) {
28 // Create an output file.
29 out, err := os.Create(os.Args[1])
30 if err != nil {
31 panic(err.Error())
32 }
33 defer out.Close()
34
35 // Create a new trace.
36 trace := NewTrace(ver)
37
38 // Call the generator.
39 f(trace)
40
41 // Write out the generator's state.
42 if _, err := out.Write(trace.Generate()); err != nil {
43 panic(err.Error())
44 }
45 }
46
47 // Trace represents an execution trace for testing.
48 //
49 // It does a little bit of work to ensure that the produced trace is valid,
50 // just for convenience. It mainly tracks batches and batch sizes (so they're
51 // trivially correct), tracks strings and stacks, and makes sure emitted string
52 // and stack batches are valid. That last part can be controlled by a few options.
53 //
54 // Otherwise, it performs no validation on the trace at all.
55 type Trace struct {
56 // Trace data state.
57 ver version.Version
58 names map[string]tracev2.EventType
59 specs []tracev2.EventSpec
60 events []raw.Event
61 gens []*Generation
62 validTimestamps bool
63 lastTs Time
64
65 // Expectation state.
66 bad bool
67 badMatch *regexp.Regexp
68 }
69
70 // NewTrace creates a new trace.
71 func NewTrace(ver version.Version) *Trace {
72 return &Trace{
73 names: tracev2.EventNames(ver.Specs()),
74 specs: ver.Specs(),
75 ver: ver,
76 validTimestamps: true,
77 }
78 }
79
80 // ExpectFailure writes down that the trace should be broken. The caller
81 // must provide a pattern matching the expected error produced by the parser.
82 func (t *Trace) ExpectFailure(pattern string) {
83 t.bad = true
84 t.badMatch = regexp.MustCompile(pattern)
85 }
86
87 // ExpectSuccess writes down that the trace should successfully parse.
88 func (t *Trace) ExpectSuccess() {
89 t.bad = false
90 }
91
92 // RawEvent emits an event into the trace. name must correspond to one
93 // of the names in Specs() result for the version that was passed to
94 // this trace.
95 func (t *Trace) RawEvent(typ tracev2.EventType, data []byte, args ...uint64) {
96 t.events = append(t.events, t.createEvent(typ, data, args...))
97 }
98
99 // DisableTimestamps makes the timestamps for all events generated after
100 // this call zero. Raw events are exempted from this because the caller
101 // has to pass their own timestamp into those events anyway.
102 func (t *Trace) DisableTimestamps() {
103 t.validTimestamps = false
104 }
105
106 // Generation creates a new trace generation.
107 //
108 // This provides more structure than Event to allow for more easily
109 // creating complex traces that are mostly or completely correct.
110 func (t *Trace) Generation(gen uint64) *Generation {
111 g := &Generation{
112 trace: t,
113 gen: gen,
114 strings: make(map[string]uint64),
115 stacks: make(map[stack]uint64),
116 sync: sync{freq: 15625000},
117 }
118 t.gens = append(t.gens, g)
119 return g
120 }
121
122 // Generate creates a test file for the trace.
123 func (t *Trace) Generate() []byte {
124 // Trace file contents.
125 var buf bytes.Buffer
126 tw, err := raw.NewTextWriter(&buf, t.ver)
127 if err != nil {
128 panic(err.Error())
129 }
130
131 // Write raw top-level events.
132 for _, e := range t.events {
133 tw.WriteEvent(e)
134 }
135
136 // Write generations.
137 for _, g := range t.gens {
138 g.writeEventsTo(tw)
139 }
140
141 // Expectation file contents.
142 expect := []byte("SUCCESS\n")
143 if t.bad {
144 expect = []byte(fmt.Sprintf("FAILURE %q\n", t.badMatch))
145 }
146
147 // Create the test file's contents.
148 return txtar.Format(&txtar.Archive{
149 Files: []txtar.File{
150 {Name: "expect", Data: expect},
151 {Name: "trace", Data: buf.Bytes()},
152 },
153 })
154 }
155
156 func (t *Trace) createEvent(ev tracev2.EventType, data []byte, args ...uint64) raw.Event {
157 spec := t.specs[ev]
158 if ev != tracev2.EvStack {
159 if arity := len(spec.Args); len(args) != arity {
160 panic(fmt.Sprintf("expected %d args for %s, got %d", arity, spec.Name, len(args)))
161 }
162 }
163 return raw.Event{
164 Version: t.ver,
165 Ev: ev,
166 Args: args,
167 Data: data,
168 }
169 }
170
171 type stack struct {
172 stk [32]trace.StackFrame
173 len int
174 }
175
176 var (
177 NoString = ""
178 NoStack = []trace.StackFrame{}
179 )
180
181 // Generation represents a single generation in the trace.
182 type Generation struct {
183 trace *Trace
184 gen uint64
185 batches []*Batch
186 strings map[string]uint64
187 stacks map[stack]uint64
188 sync sync
189
190 // Options applied when Trace.Generate is called.
191 ignoreStringBatchSizeLimit bool
192 ignoreStackBatchSizeLimit bool
193 }
194
195 // Batch starts a new event batch in the trace data.
196 //
197 // This is convenience function for generating correct batches.
198 func (g *Generation) Batch(thread trace.ThreadID, time Time) *Batch {
199 b := &Batch{
200 gen: g,
201 thread: thread,
202 }
203 b.setTimestamp(time)
204 g.batches = append(g.batches, b)
205 return b
206 }
207
208 // String registers a string with the trace.
209 //
210 // This is a convenience function for easily adding correct
211 // strings to traces.
212 func (g *Generation) String(s string) uint64 {
213 if len(s) == 0 {
214 return 0
215 }
216 if id, ok := g.strings[s]; ok {
217 return id
218 }
219 id := uint64(len(g.strings) + 1)
220 g.strings[s] = id
221 return id
222 }
223
224 // Stack registers a stack with the trace.
225 //
226 // This is a convenience function for easily adding correct
227 // stacks to traces.
228 func (g *Generation) Stack(stk []trace.StackFrame) uint64 {
229 if len(stk) == 0 {
230 return 0
231 }
232 if len(stk) > 32 {
233 panic("stack too big for test")
234 }
235 var stkc stack
236 copy(stkc.stk[:], stk)
237 stkc.len = len(stk)
238 if id, ok := g.stacks[stkc]; ok {
239 return id
240 }
241 id := uint64(len(g.stacks) + 1)
242 g.stacks[stkc] = id
243 return id
244 }
245
246 // Sync configures the sync batch for the generation. For go1.25 and later,
247 // the time value is the timestamp of the EvClockSnapshot event. For earlier
248 // version, the time value is the timestamp of the batch containing a lone
249 // EvFrequency event.
250 func (g *Generation) Sync(freq uint64, time Time, mono uint64, wall time.Time) {
251 if g.trace.ver < version.Go125 && (mono != 0 || !wall.IsZero()) {
252 panic(fmt.Sprintf("mono and wall args are not supported in go1.%d traces", g.trace.ver))
253 }
254 g.sync = sync{
255 freq: freq,
256 time: time,
257 mono: mono,
258 walltime: wall,
259 }
260 }
261
262 type sync struct {
263 freq uint64
264 time Time
265 mono uint64
266 walltime time.Time
267 }
268
269 // writeEventsTo emits event batches in the generation to tw.
270 func (g *Generation) writeEventsTo(tw *raw.TextWriter) {
271 // go1.25+ sync batches are emitted at the start of the generation.
272 if g.trace.ver >= version.Go125 {
273 b := g.newStructuralBatch()
274 // Arrange for EvClockSnapshot's ts to be exactly g.sync.time.
275 b.setTimestamp(g.sync.time - 1)
276 b.RawEvent(tracev2.EvSync, nil)
277 b.RawEvent(tracev2.EvFrequency, nil, g.sync.freq)
278 sec := uint64(g.sync.walltime.Unix())
279 nsec := uint64(g.sync.walltime.Nanosecond())
280 b.Event("ClockSnapshot", g.sync.mono, sec, nsec)
281 b.writeEventsTo(tw)
282 }
283
284 // Write event batches for the generation.
285 for _, b := range g.batches {
286 b.writeEventsTo(tw)
287 }
288
289 // Write lone EvFrequency sync batch for older traces.
290 if g.trace.ver < version.Go125 {
291 b := g.newStructuralBatch()
292 b.setTimestamp(g.sync.time)
293 b.RawEvent(tracev2.EvFrequency, nil, g.sync.freq)
294 b.writeEventsTo(tw)
295 }
296
297 // Write stacks.
298 b := g.newStructuralBatch()
299 b.RawEvent(tracev2.EvStacks, nil)
300 for stk, id := range g.stacks {
301 stk := stk.stk[:stk.len]
302 args := []uint64{id, uint64(len(stk))}
303 for _, f := range stk {
304 args = append(args, f.PC, g.String(f.Func), g.String(f.File), f.Line)
305 }
306 b.RawEvent(tracev2.EvStack, nil, args...)
307
308 // Flush the batch if necessary.
309 if !g.ignoreStackBatchSizeLimit && b.size > tracev2.MaxBatchSize/2 {
310 b.writeEventsTo(tw)
311 b = g.newStructuralBatch()
312 }
313 }
314 b.writeEventsTo(tw)
315
316 // Write strings.
317 b = g.newStructuralBatch()
318 b.RawEvent(tracev2.EvStrings, nil)
319 for s, id := range g.strings {
320 b.RawEvent(tracev2.EvString, []byte(s), id)
321
322 // Flush the batch if necessary.
323 if !g.ignoreStringBatchSizeLimit && b.size > tracev2.MaxBatchSize/2 {
324 b.writeEventsTo(tw)
325 b = g.newStructuralBatch()
326 }
327 }
328 b.writeEventsTo(tw)
329
330 // Write end-of-generation event if necessary.
331 if g.trace.ver >= version.Go126 {
332 tw.WriteEvent(raw.Event{
333 Version: g.trace.ver,
334 Ev: tracev2.EvEndOfGeneration,
335 })
336 }
337 }
338
339 func (g *Generation) newStructuralBatch() *Batch {
340 b := &Batch{gen: g, thread: trace.NoThread}
341 b.setTimestamp(g.trace.lastTs + 1)
342 return b
343 }
344
345 // Batch represents an event batch.
346 type Batch struct {
347 gen *Generation
348 thread trace.ThreadID
349 timestamp Time
350 size uint64
351 events []raw.Event
352 }
353
354 // Event emits an event into a batch. name must correspond to one
355 // of the names in Specs() result for the version that was passed to
356 // this trace. Callers must omit the timestamp delta.
357 func (b *Batch) Event(name string, args ...any) {
358 ev, ok := b.gen.trace.names[name]
359 if !ok {
360 panic(fmt.Sprintf("invalid or unknown event %s", name))
361 }
362 var uintArgs []uint64
363 argOff := 0
364 if b.gen.trace.specs[ev].IsTimedEvent {
365 if b.gen.trace.validTimestamps {
366 uintArgs = []uint64{1}
367 b.gen.trace.lastTs += 1
368 } else {
369 uintArgs = []uint64{0}
370 }
371 argOff = 1
372 }
373 spec := b.gen.trace.specs[ev]
374 if arity := len(spec.Args) - argOff; len(args) != arity {
375 panic(fmt.Sprintf("expected %d args for %s, got %d", arity, spec.Name, len(args)))
376 }
377 for i, arg := range args {
378 uintArgs = append(uintArgs, b.uintArgFor(arg, spec.Args[i+argOff]))
379 }
380 b.RawEvent(ev, nil, uintArgs...)
381 }
382
383 func (b *Batch) uintArgFor(arg any, argSpec string) uint64 {
384 components := strings.SplitN(argSpec, "_", 2)
385 typStr := components[0]
386 if len(components) == 2 {
387 typStr = components[1]
388 }
389 var u uint64
390 switch typStr {
391 case "value", "mono", "sec", "nsec":
392 u = arg.(uint64)
393 case "stack":
394 u = b.gen.Stack(arg.([]trace.StackFrame))
395 case "seq":
396 u = uint64(arg.(Seq))
397 case "pstatus":
398 u = uint64(arg.(tracev2.ProcStatus))
399 case "gstatus":
400 u = uint64(arg.(tracev2.GoStatus))
401 case "g":
402 u = uint64(arg.(trace.GoID))
403 case "m":
404 u = uint64(arg.(trace.ThreadID))
405 case "p":
406 u = uint64(arg.(trace.ProcID))
407 case "string":
408 u = b.gen.String(arg.(string))
409 case "task":
410 u = uint64(arg.(trace.TaskID))
411 default:
412 panic(fmt.Sprintf("unsupported arg type %q for spec %q", typStr, argSpec))
413 }
414 return u
415 }
416
417 // RawEvent emits an event into a batch. name must correspond to one
418 // of the names in Specs() result for the version that was passed to
419 // this trace.
420 func (b *Batch) RawEvent(typ tracev2.EventType, data []byte, args ...uint64) {
421 ev := b.gen.trace.createEvent(typ, data, args...)
422
423 // Compute the size of the event and add it to the batch.
424 b.size += 1 // One byte for the event header.
425 var buf [binary.MaxVarintLen64]byte
426 for _, arg := range args {
427 b.size += uint64(binary.PutUvarint(buf[:], arg))
428 }
429 if len(data) != 0 {
430 b.size += uint64(binary.PutUvarint(buf[:], uint64(len(data))))
431 b.size += uint64(len(data))
432 }
433
434 // Add the event.
435 b.events = append(b.events, ev)
436 }
437
438 // writeEventsTo emits events in the batch, including the batch header, to tw.
439 func (b *Batch) writeEventsTo(tw *raw.TextWriter) {
440 tw.WriteEvent(raw.Event{
441 Version: b.gen.trace.ver,
442 Ev: tracev2.EvEventBatch,
443 Args: []uint64{b.gen.gen, uint64(b.thread), uint64(b.timestamp), b.size},
444 })
445 for _, e := range b.events {
446 tw.WriteEvent(e)
447 }
448 }
449
450 // setTimestamp sets the timestamp for the batch.
451 func (b *Batch) setTimestamp(t Time) {
452 if b.gen.trace.validTimestamps {
453 b.timestamp = t
454 b.gen.trace.lastTs = t
455 }
456 }
457
458 // Seq represents a sequence counter.
459 type Seq uint64
460
461 // Time represents a low-level trace timestamp (which does not necessarily
462 // correspond to nanoseconds, like trace.Time does).
463 type Time uint64