Debian Codegraph @

stack/context.go

raw
1 // Copyright 2018 Marc-Antoine Ruel. All rights reserved.
2 // Use of this source code is governed under the Apache License, Version 2.0
3 // that can be found in the LICENSE file.
4
5 //go:generate go install golang.org/x/tools/cmd/[email protected]
6 //go:generate stringer -type state
7 //go:generate stringer -type Location
8
9 package stack
10
11 import (
12 "bytes"
13 "errors"
14 "fmt"
15 "io"
16 "os"
17 "os/user"
18 "path"
19 "path/filepath"
20 "regexp"
21 "runtime"
22 "sort"
23 "strconv"
24 "strings"
25 "unsafe"
26 )
27
28 // Opts represents options to process the snapshot.
29 type Opts struct {
30 // LocalGOROOT is GOROOT with "/" as path separator. No trailing "/". Can be
31 // unset.
32 LocalGOROOT string
33 // LocalGOPATHs is GOPATH with "/" as path separator. No trailing "/". Can be
34 // unset.
35 LocalGOPATHs []string
36
37 // NameArguments tells panicparse to find the recurring pointer values and
38 // give them pseudo 'names'.
39 //
40 // Since the algorithm is O(n²), this can be worth disabling on live servers.
41 NameArguments bool
42
43 // GuessPaths tells panicparse to guess local RemoteGOROOT and GOPATH for
44 // what was found in the snapshot.
45 //
46 // Initializes in Snapshot the following members: RemoteGOROOT,
47 // RemoteGOPATHs, LocalGomoduleRoot and GomodImportPath.
48 //
49 // This is done by scanning the local disk, so be warned of performance
50 // impact.
51 GuessPaths bool
52
53 // AnalyzeSources tells panicparse to processes source files to improve calls
54 // to be more descriptive.
55 //
56 // Requires GuessPaths to be true.
57 AnalyzeSources bool
58
59 // Disallow initialization with unnamed parameters.
60 _ struct{}
61 }
62
63 // DefaultOpts returns default options to process the snapshot.
64 func DefaultOpts() *Opts {
65 p := runtime.GOROOT()
66 if runtime.GOOS == "windows" {
67 p = strings.Replace(p, pathSeparator, "/", -1)
68 }
69 return &Opts{
70 LocalGOROOT: p,
71 LocalGOPATHs: getGOPATHs(),
72 NameArguments: true,
73 GuessPaths: true,
74 AnalyzeSources: true,
75 }
76 }
77
78 func (o *Opts) isValid() bool {
79 if !o.GuessPaths && o.AnalyzeSources {
80 return false
81 }
82 if strings.Contains(o.LocalGOROOT, "\\") {
83 return false
84 }
85 for _, p := range o.LocalGOPATHs {
86 if strings.Contains(p, "\\") {
87 return false
88 }
89 }
90 return true
91 }
92
93 // Snapshot is a parsed runtime.Stack() or race detector dump.
94 type Snapshot struct {
95 // Goroutines is the Goroutines found.
96 //
97 // They are in the order that they were printed.
98 Goroutines []*Goroutine
99
100 // LocalGOROOT is copied from Opts.
101 LocalGOROOT string
102 // LocalGOPATHs is copied from Opts.
103 LocalGOPATHs []string
104
105 // The following members are initialized when Opts.GuessPaths is true.
106
107 // RemoteGOROOT is the GOROOT as detected in the traceback, not the on the
108 // host.
109 //
110 // It can be empty if no root was determined, for example the traceback
111 // contains only non-stdlib source references.
112 RemoteGOROOT string
113 // RemoteGOPATHs is the GOPATH as detected in the traceback, with the value
114 // being the corresponding path mapped to the host if found.
115 //
116 // It can be empty if only stdlib code is in the traceback or if no local
117 // sources were matched up. In the general case there is only one entry in
118 // the map.
119 RemoteGOPATHs map[string]string
120
121 // LocalGomods are the root directories containing go.mod or that directly
122 // contained source code as detected in the traceback, with the value being
123 // the corresponding import path found in the go.mod file.
124 //
125 // Uses "/" as path separator. No trailing "/".
126 //
127 // Because of the "replace" statement in go.mod, there can be multiple root
128 // directories. A file run by "go run" is also considered a go module to (a
129 // certain extent).
130 //
131 // It is initialized by findRoots().
132 //
133 // Unlike GOROOT and GOPATH, it only works with stack traces created in the
134 // local file system, hence "Local" prefix.
135 LocalGomods map[string]string
136
137 // Disallow initialization with unnamed parameters.
138 _ struct{}
139 }
140
141 // ScanSnapshot scans the Reader for the output from runtime.Stack() in br.
142 //
143 // Returns nil *Snapshot if no stack trace was detected.
144 //
145 // If a Snapshot is returned, you can call the function again to find another
146 // trace, or do io.Copy(br, out) to flush the rest of the stream.
147 //
148 // ParseSnapshot processes the output from runtime.Stack() or the race detector.
149 //
150 // Returns a nil *Snapshot if no stack trace was detected and SearchSnapshot()
151 // was a false positive.
152 //
153 // Returns io.EOF if all of reader was read.
154 //
155 // The suffix of the stack trace is returned as []byte.
156 //
157 // It pipes anything not detected as a panic stack trace from r into out. It
158 // assumes there is junk before the actual stack trace. The junk is streamed to
159 // out.
160 func ScanSnapshot(in io.Reader, prefix io.Writer, opts *Opts) (*Snapshot, []byte, error) {
161 if opts == nil || !opts.isValid() {
162 return nil, nil, errors.New("invalid Opts")
163 }
164 // TODO(maruel): Validate opts.
165 s := scanningState{
166 Snapshot: &Snapshot{
167 LocalGOROOT: opts.LocalGOROOT,
168 LocalGOPATHs: opts.LocalGOPATHs,
169 },
170 state: looking,
171 }
172 r := reader{rd: in}
173 var err error
174 var suffix []byte
175 for err == nil && s.state != done {
176 var d []byte
177 if d, err = r.readLine(); len(d) != 0 {
178 l, err1 := s.scan(d)
179 if err1 != nil && (err == nil || err == io.EOF) {
180 err = err1
181 }
182 if !l {
183 if s.state != looking {
184 suffix = append([]byte{}, d...)
185 suffix = append(suffix, r.buffered()...)
186 break
187 }
188 if _, err1 = prefix.Write(d); err1 != nil && (err == nil || err == io.EOF) {
189 err = err1
190 break
191 }
192 }
193 }
194 }
195 if s.Goroutines != nil {
196 if opts.NameArguments {
197 nameArguments(s.Goroutines)
198 }
199 if opts.GuessPaths {
200 _ = s.guessPaths()
201 }
202 if opts.AnalyzeSources {
203 _ = s.augment()
204 }
205 return s.Snapshot, suffix, err
206 }
207 return nil, suffix, err
208 }
209
210 // IsRace returns true if a race detector stack trace was found.
211 //
212 // Otherwise, it is a normal goroutines snapshot.
213 //
214 // When a race condition was detected, it is preferable to not call Aggregate().
215 func (s *Snapshot) IsRace() bool {
216 return s.Goroutines[0].RaceAddr != 0
217 }
218
219 func (s *Snapshot) guessPaths() bool {
220 b := s.findRoots() == 0
221 for _, r := range s.Goroutines {
222 // Note that this is important to call it even if
223 // s.RemoteGOROOT == s.LocalGOROOT.
224 b = r.updateLocations(s.RemoteGOROOT, s.LocalGOROOT, s.LocalGomods, s.RemoteGOPATHs) && b
225 }
226 return b
227 }
228
229 // augment processes source files to improve calls to be more descriptive.
230 //
231 // It modifies goroutines in place. It requires calling guessPaths() to work
232 // properly.
233 //
234 // Returns the last error that occurred while processing files.
235 func (s *Snapshot) augment() error {
236 c := cacheAST{
237 files: map[string][]byte{},
238 parsed: map[string]*parsedFile{},
239 }
240 var err error
241 for _, g := range s.Goroutines {
242 if err1 := c.augmentGoroutine(g); err1 != nil {
243 err = err1
244 }
245 }
246 return err
247 }
248
249 // Private stuff.
250
251 const pathSeparator = string(filepath.Separator)
252
253 var (
254 lockedToThread = []byte("locked to thread")
255 // gotRaceHeader1, done
256 raceHeaderFooter = []byte("==================")
257 // gotRaceHeader2
258 raceHeader = []byte("WARNING: DATA RACE")
259 crlf = []byte("\r\n")
260 lf = []byte("\n")
261 commaSpace = []byte(", ")
262 writeCap = []byte("Write")
263 writeLow = []byte("write")
264 threeDots = []byte("...")
265 underscore = []byte("_")
266 inaccurateQuestionMark = []byte("?")
267 )
268
269 // These are effectively constants.
270 var (
271 // gotRoutineHeader
272 reRoutineHeader = regexp.MustCompile("^([ \t]*)goroutine (\\d+)(?: gp=[^ ]+ m=[^ ]+(?: mp=[^ ]+)?)? \\[([^\\]]+)\\]\\:$")
273 reMinutes = regexp.MustCompile(`^(\d+) minutes$`)
274
275 // gotUnavail
276 reUnavail = regexp.MustCompile("^(?:\t| +)goroutine running on other thread; stack unavailable")
277
278 // gotFileFunc, gotRaceOperationFile, gotRaceGoroutineFile
279 // See gentraceback() in src/runtime/traceback.go for more information.
280 // - Sometimes the source file comes up as "<autogenerated>". It is the
281 // compiler than generated these, not the runtime.
282 // - The tab may be replaced with spaces when a user copy-paste it, handle
283 // this transparently.
284 // - "runtime.gopanic" is explicitly replaced with "panic" by gentraceback().
285 // - The +0x123 byte offset is printed when frame.pc > _func.entry. _func is
286 // generated by the linker.
287 // - The +0x123 byte offset is not included with generated code, e.g. unnamed
288 // functions "func·006()" which is generally go func() { ... }()
289 // statements. Since the _func is generated at runtime, it's probably why
290 // _func.entry is not set.
291 // - C calls may have fp=0x123 sp=0x123 appended. I think it normally happens
292 // when a signal is not correctly handled. It is printed with m.throwing>0.
293 // These are discarded.
294 // - For cgo, the source file may be "??".
295 reFile = regexp.MustCompile("^(?:\t| +)(\\?\\?|\\<autogenerated\\>|.+\\.(?:c|go|s))\\:(\\d+)(?:| \\+0x[0-9a-f]+)(?:| fp=0x[0-9a-f]+ sp=0x[0-9a-f]+(?:| pc=0x[0-9a-f]+))$")
296
297 // gotCreated
298 // Sadly, it doesn't note the goroutine number so we could cascade them per
299 // parenthood.
300 reCreated = regexp.MustCompile("^created by (.+)$")
301
302 // gotFunc, gotRaceOperationFunc, gotRaceGoroutineFunc
303 reFunc = regexp.MustCompile(`^(.+)\((.*)\)$`)
304
305 // Race:
306 // See https://github.com/llvm/llvm-project/blob/HEAD/compiler-rt/lib/tsan/rtl/tsan_report.cpp
307 // for the code generating these messages. Please note only the block in
308 // #else // #if !SANITIZER_GO
309 // is used.
310 // TODO(maruel): " [failed to restore the stack]\n\n"
311 // TODO(maruel): "Global var %s of size %zu at %p declared at %s:%zu\n"
312
313 // gotRaceOperationHeader
314 reRaceOperationHeader = regexp.MustCompile(`^(Read|Write) at (0x[0-9a-f]+) by goroutine (\d+):$`)
315
316 // gotRaceOperationHeader
317 reRacePreviousOperationHeader = regexp.MustCompile(`^Previous (read|write) at (0x[0-9a-f]+) by goroutine (\d+):$`)
318
319 // gotRaceGoroutineHeader
320 reRaceGoroutine = regexp.MustCompile(`^Goroutine (\d+) \((running|finished)\) created at:$`)
321
322 // TODO(maruel): Use it.
323 //reRacePreviousOperationMainHeader = regexp.MustCompile("^Previous (read|write) at (0x[0-9a-f]+) by main goroutine:$")
324 )
325
326 // state is the state of the scan to detect and process a stack trace.
327 type state int
328
329 // Initial state is looking. Other states are when a stack trace is detected.
330 const (
331 // Haven't found a stack trace yet.
332 // to: gotRoutineHeader, raceHeader1
333 looking state = iota
334
335 // Done processing a stack trace.
336 done
337
338 // Panic stack trace:
339
340 // Signature: ""
341 // An empty line between goroutines.
342 // from: gotFileCreated, gotFileFunc
343 // to: gotRoutineHeader, done
344 betweenRoutine
345 // Regexp: reRoutineHeader
346 // Signature: "goroutine 1 [running]:"
347 // Goroutine header was found.
348 // from: looking
349 // to: gotUnavail, gotFunc
350 gotRoutineHeader
351 // Regexp: reFunc
352 // Signature: "main.main()"
353 // Function call line was found.
354 // from: gotRoutineHeader
355 // to: gotFileFunc
356 gotFunc
357 // Regexp: reCreated
358 // Signature: "created by main.init.func4"
359 // Goroutine creation line was found.
360 // from: gotFileFunc
361 // to: gotFileCreated
362 gotCreated
363 // Regexp: reFile
364 // Signature: "\t/foo/bar/baz.go:116 +0x35"
365 // File header was found.
366 // from: gotFunc
367 // to: gotFunc, gotCreated, betweenRoutine, done
368 gotFileFunc
369 // Regexp: reFile
370 // Signature: "\t/foo/bar/baz.go:116 +0x35"
371 // File header was found.
372 // from: gotCreated
373 // to: betweenRoutine, done
374 gotFileCreated
375 // Regexp: reUnavail
376 // Signature: "goroutine running on other thread; stack unavailable"
377 // State when the goroutine stack is instead is reUnavail.
378 // from: gotRoutineHeader
379 // to: betweenRoutine, gotCreated
380 gotUnavail
381
382 // Race detector:
383
384 // Constant: raceHeaderFooter
385 // Signature: "=================="
386 // from: looking
387 // to: done, gotRaceHeader2
388 gotRaceHeader1
389 // Constant: raceHeader
390 // Signature: "WARNING: DATA RACE"
391 // from: gotRaceHeader1
392 // to: done, gotRaceOperationHeader
393 gotRaceHeader2
394 // Regexp: reRaceOperationHeader, reRacePreviousOperationHeader
395 // Signature: "Read at 0x00c0000e4030 by goroutine 7:"
396 // A race operation was found.
397 // from: gotRaceHeader2
398 // to: done, gotRaceOperationFunc
399 gotRaceOperationHeader
400 // Regexp: reFunc
401 // Signature: " main.panicRace.func1()"
402 // Function that caused the race.
403 // from: gotRaceOperationHeader
404 // to: done, gotRaceOperationFile
405 gotRaceOperationFunc
406 // Regexp: reFile
407 // Signature: "\t/foo/bar/baz.go:116 +0x35"
408 // File header that caused the race.
409 // from: gotRaceOperationFunc
410 // to: done, betweenRaceOperations, gotRaceOperationFunc
411 gotRaceOperationFile
412 // Signature: ""
413 // Empty line between race operations or just after.
414 // from: gotRaceOperationFile
415 // to: done, gotRaceOperationHeader, gotRaceGoroutineHeader
416 betweenRaceOperations
417
418 // Regexp: reRaceGoroutine
419 // Signature: "Goroutine 7 (running) created at:"
420 // Goroutine header.
421 // from: betweenRaceOperations, betweenRaceGoroutines
422 // to: done, gotRaceOperationHeader
423 gotRaceGoroutineHeader
424 // Regexp: reFunc
425 // Signature: " main.panicRace.func1()"
426 // Function that caused the race.
427 // from: gotRaceGoroutineHeader
428 // to: done, gotRaceGoroutineFile
429 gotRaceGoroutineFunc
430 // Regexp: reFile
431 // Signature: "\t/foo/bar/baz.go:116 +0x35"
432 // File header that caused the race.
433 // from: gotRaceGoroutineFunc
434 // to: done, betweenRaceGoroutines
435 gotRaceGoroutineFile
436 // Signature: ""
437 // Empty line between race stack traces.
438 // from: gotRaceGoroutineFile
439 // to: done, gotRaceGoroutineHeader
440 betweenRaceGoroutines
441 )
442
443 // scanningState is the state of the scan to detect and process a stack trace
444 // and stores the traces found.
445 type scanningState struct {
446 *Snapshot
447 state state
448 prefix []byte
449 goroutineIndex int
450 }
451
452 func isFramesElidedLine(line []byte) bool {
453 // before go1.21:
454 // ...additional frames elided...
455 //
456 // go1.21 and newer:
457 // print("...", elide, " frames elided...\n")
458 framesElided := []byte("...additional frames elided...")
459 return bytes.Equal(line, framesElided) ||
460 bytes.HasPrefix(line, []byte("...")) &&
461 bytes.HasSuffix(line, []byte(" frames elided..."))
462 }
463
464 // scan scans one line, updates goroutines and move to the next state.
465 //
466 // Returns true if the line was processed and thus should not be printed out.
467 //
468 // TODO(maruel): Handle corrupted stack cases:
469 // - missed stack barrier
470 // - found next stack barrier at 0x123; expected
471 // - runtime: unexpected return pc for FUNC_NAME called from 0x123
472 func (s *scanningState) scan(line []byte) (bool, error) {
473 /* This is very useful to debug issues in the state machine.
474 defer func() {
475 log.Printf("scan(%q) -> %s", line, s.state)
476 }()
477 //*/
478 var cur *Goroutine
479 if len(s.Goroutines) != 0 {
480 cur = s.Goroutines[len(s.Goroutines)-1]
481 }
482 trimmed := line
483 if bytes.HasSuffix(line, crlf) {
484 trimmed = line[:len(line)-2]
485 } else if bytes.HasSuffix(line, lf) {
486 trimmed = line[:len(line)-1]
487 } else {
488 // It's the end of the stream and it's not terminating with EOL character.
489 if s.state == looking || s.state == done {
490 return false, nil
491 }
492 // Let it flow. It's possible the last line was trimmed and we still want
493 // to parse it.
494 }
495
496 if len(trimmed) != 0 && len(s.prefix) != 0 {
497 // This can only be the case if s.state != looking | done or the line is
498 // empty.
499 if !bytes.HasPrefix(trimmed, s.prefix) {
500 prefix := s.prefix
501 s.state = done
502 s.prefix = nil
503 return false, fmt.Errorf("inconsistent indentation: %q, expected %q", trimmed, prefix)
504 }
505 trimmed = trimmed[len(s.prefix):]
506 }
507
508 switch s.state {
509 case done:
510 return false, nil
511
512 case looking:
513 // We could look for '^panic:' but this is more risky, there can be a lot
514 // of junk between this and the stack dump.
515 fallthrough
516
517 case betweenRoutine:
518 // Look for a goroutine header.
519 if match := reRoutineHeader.FindSubmatch(trimmed); match != nil {
520 if id, ok := atou(match[2]); ok {
521 // See runtime/traceback.go.
522 // "<state>, \d+ minutes, locked to thread"
523 items := bytes.Split(match[3], commaSpace)
524 sleep := 0
525 locked := false
526 for i := 1; i < len(items); i++ {
527 if bytes.Equal(items[i], lockedToThread) {
528 locked = true
529 continue
530 }
531 // Look for duration, if any.
532 if match2 := reMinutes.FindSubmatch(items[i]); match2 != nil {
533 sleep, _ = atou(match2[1])
534 }
535 }
536 g := &Goroutine{
537 Signature: Signature{
538 State: string(items[0]),
539 SleepMin: sleep,
540 SleepMax: sleep,
541 Locked: locked,
542 },
543 ID: id,
544 First: len(s.Goroutines) == 0,
545 }
546 // Increase performance by always allocating 4 goroutines minimally.
547 if s.Goroutines == nil {
548 s.Goroutines = make([]*Goroutine, 0, 4)
549 }
550 s.Goroutines = append(s.Goroutines, g)
551 s.state = gotRoutineHeader
552 s.prefix = append([]byte{}, match[1]...)
553 return true, nil
554 }
555 }
556 // Switch to race detection mode.
557 if bytes.Equal(trimmed, raceHeaderFooter) {
558 // TODO(maruel): We should buffer it in case the next line is not a
559 // WARNING so we can output it back.
560 s.state = gotRaceHeader1
561 return true, nil
562 }
563 if s.state != looking {
564 s.state = done
565 }
566 return false, nil
567
568 case gotRoutineHeader:
569 if reUnavail.Match(trimmed) {
570 // Generate a fake stack entry.
571 cur.Stack.Calls = []Call{{RemoteSrcPath: "<unavailable>"}}
572 // Next line is expected to be an empty line.
573 s.state = gotUnavail
574 return true, nil
575 }
576 c := Call{}
577 if found, err := parseFunc(&c, trimmed); found {
578 // Increase performance by always allocating 4 calls minimally.
579 if cur.Stack.Calls == nil {
580 cur.Stack.Calls = make([]Call, 0, 4)
581 }
582 cur.Stack.Calls = append(cur.Stack.Calls, c)
583 s.state = gotFunc
584 return err == nil, err
585 }
586 return false, fmt.Errorf("expected a function after a goroutine header, got: %q", bytes.TrimSpace(trimmed))
587
588 case gotFunc:
589 // cur.Stack.Calls is guaranteed to have at least one item.
590 if found, err := parseFile(&cur.Stack.Calls[len(cur.Stack.Calls)-1], trimmed); err != nil {
591 return false, err
592 } else if !found {
593 return false, fmt.Errorf("expected a file after a function, got: %q", bytes.TrimSpace(trimmed))
594 }
595 s.state = gotFileFunc
596 return true, nil
597
598 case gotCreated:
599 if found, err := parseFile(&cur.CreatedBy.Calls[0], trimmed); err != nil {
600 return false, err
601 } else if !found {
602 return false, fmt.Errorf("expected a file after a created line, got: %q", trimmed)
603 }
604 s.state = gotFileCreated
605 return true, nil
606
607 case gotFileFunc:
608 if match := reCreated.FindSubmatch(trimmed); match != nil {
609 cur.CreatedBy.Calls = make([]Call, 1)
610 if err := cur.CreatedBy.Calls[0].Func.Init(string(match[1])); err != nil {
611 cur.CreatedBy.Calls = nil
612 return false, err
613 }
614 // This initializes ImportPath.
615 cur.CreatedBy.Calls[0].init("", 0)
616 s.state = gotCreated
617 return true, nil
618 }
619 if isFramesElidedLine(trimmed) {
620 cur.Stack.Elided = true
621 // TODO(maruel): New state.
622 return true, nil
623 }
624 c := Call{}
625 if found, err := parseFunc(&c, trimmed); found {
626 // Increase performance by always allocating 4 calls minimally.
627 if cur.Stack.Calls == nil {
628 cur.Stack.Calls = make([]Call, 0, 4)
629 }
630 cur.Stack.Calls = append(cur.Stack.Calls, c)
631 s.state = gotFunc
632 return err == nil, err
633 }
634 if len(trimmed) == 0 {
635 s.state = betweenRoutine
636 return true, nil
637 }
638 s.state = done
639 return false, nil
640
641 case gotFileCreated:
642 if len(trimmed) == 0 {
643 s.state = betweenRoutine
644 return true, nil
645 }
646 s.state = done
647 return false, nil
648
649 case gotUnavail:
650 if len(trimmed) == 0 {
651 s.state = betweenRoutine
652 return true, nil
653 }
654 if match := reCreated.FindSubmatch(trimmed); match != nil {
655 cur.CreatedBy.Calls = make([]Call, 1)
656 if err := cur.CreatedBy.Calls[0].Func.Init(string(match[1])); err != nil {
657 cur.CreatedBy.Calls = nil
658 return false, err
659 }
660 s.state = gotCreated
661 return true, nil
662 }
663 return false, fmt.Errorf("expected empty line after unavailable stack, got: %q", bytes.TrimSpace(trimmed))
664
665 // Race detector.
666
667 case gotRaceHeader1:
668 if bytes.Equal(trimmed, raceHeader) {
669 // TODO(maruel): We should buffer it in case the next line is not a
670 // WARNING so we can output it back.
671 s.state = gotRaceHeader2
672 return true, nil
673 }
674 // TODO(maruel): While this shouldn't error out, it should still force the
675 // output of raceHeaderFooter.
676 s.state = looking
677 s.prefix = nil
678 return false, nil
679
680 case gotRaceHeader2:
681 if match := reRaceOperationHeader.FindSubmatch(trimmed); match != nil {
682 w := bytes.Equal(match[1], writeCap)
683 addr, err := strconv.ParseUint(unsafeString(match[2]), 0, 64)
684 if err != nil {
685 return false, fmt.Errorf("failed to parse address on line: %q", bytes.TrimSpace(trimmed))
686 }
687 id, ok := atou(match[3])
688 if !ok {
689 return false, fmt.Errorf("failed to parse goroutine id on line: %q", bytes.TrimSpace(trimmed))
690 }
691 if s.Goroutines != nil {
692 panic("internal failure; expected s.Goroutines to be nil")
693 }
694 s.Goroutines = append(make([]*Goroutine, 0, 4), &Goroutine{ID: id, First: true, RaceWrite: w, RaceAddr: addr})
695 s.goroutineIndex = len(s.Goroutines) - 1
696 s.state = gotRaceOperationHeader
697 return true, nil
698 }
699 return false, fmt.Errorf("expected race condition, got: %q", bytes.TrimSpace(trimmed))
700
701 case gotRaceOperationHeader:
702 c := Call{}
703 if found, err := parseFunc(&c, trimLeftSpace(trimmed)); found {
704 // Increase performance by always allocating 4 calls minimally.
705 if cur.Stack.Calls == nil {
706 cur.Stack.Calls = make([]Call, 0, 4)
707 }
708 cur.Stack.Calls = append(cur.Stack.Calls, c)
709 s.state = gotRaceOperationFunc
710 return err == nil, err
711 }
712 return false, fmt.Errorf("expected a function after a race operation, got: %q", trimmed)
713
714 case gotRaceOperationFunc:
715 if found, err := parseFile(&cur.Stack.Calls[len(cur.Stack.Calls)-1], trimmed); err != nil {
716 return false, err
717 } else if !found {
718 return false, fmt.Errorf("expected a file after a race function, got: %q", trimmed)
719 }
720 s.state = gotRaceOperationFile
721 return true, nil
722
723 case gotRaceOperationFile:
724 if len(trimmed) == 0 {
725 s.state = betweenRaceOperations
726 return true, nil
727 }
728 c := Call{}
729 if found, err := parseFunc(&c, trimLeftSpace(trimmed)); found {
730 cur.Stack.Calls = append(cur.Stack.Calls, c)
731 s.state = gotRaceOperationFunc
732 return err == nil, err
733 }
734 return false, fmt.Errorf("expected an empty line after a race file, got: %q", trimmed)
735
736 case betweenRaceOperations:
737 // Look for other previous race data operations.
738 if match := reRacePreviousOperationHeader.FindSubmatch(trimmed); match != nil {
739 w := bytes.Equal(match[1], writeLow)
740 addr, err := strconv.ParseUint(unsafeString(match[2]), 0, 64)
741 if err != nil {
742 return false, fmt.Errorf("failed to parse address on line: %q", bytes.TrimSpace(trimmed))
743 }
744 id, ok := atou(match[3])
745 if !ok {
746 return false, fmt.Errorf("failed to parse goroutine id on line: %q", bytes.TrimSpace(trimmed))
747 }
748 s.Goroutines = append(s.Goroutines, &Goroutine{ID: id, RaceWrite: w, RaceAddr: addr})
749 s.goroutineIndex = len(s.Goroutines) - 1
750 s.state = gotRaceOperationHeader
751 return true, nil
752 }
753 fallthrough
754
755 case betweenRaceGoroutines:
756 if match := reRaceGoroutine.FindSubmatch(trimmed); match != nil {
757 id, ok := atou(match[1])
758 if !ok {
759 return false, fmt.Errorf("failed to parse goroutine id on line: %q", bytes.TrimSpace(trimmed))
760 }
761 found := false
762 for i, g := range s.Goroutines {
763 if g.ID == id {
764 g.State = string(match[2])
765 s.goroutineIndex = i
766 found = true
767 break
768 }
769 }
770 if !found {
771 return false, fmt.Errorf("unexpected goroutine ID on line: %q", bytes.TrimSpace(trimmed))
772 }
773 s.state = gotRaceGoroutineHeader
774 return true, nil
775 }
776 return false, fmt.Errorf("expected an operator or goroutine, got: %q", trimmed)
777
778 // Race stack traces
779
780 case gotRaceGoroutineFunc:
781 c := s.Goroutines[s.goroutineIndex].CreatedBy.Calls
782 if found, err := parseFile(&c[len(c)-1], trimmed); err != nil {
783 return false, err
784 } else if !found {
785 return false, fmt.Errorf("expected a file after a race function, got: %q", trimmed)
786 }
787 // TODO(maruel): Set s.Goroutines[].CreatedBy.
788 s.state = gotRaceGoroutineFile
789 return true, nil
790
791 case gotRaceGoroutineFile:
792 if len(trimmed) == 0 {
793 s.state = betweenRaceGoroutines
794 return true, nil
795 }
796 if bytes.Equal(trimmed, raceHeaderFooter) {
797 s.state = done
798 return true, nil
799 }
800 fallthrough
801
802 case gotRaceGoroutineHeader:
803 c := Call{}
804 if found, err := parseFunc(&c, trimLeftSpace(trimmed)); found {
805 s.Goroutines[s.goroutineIndex].CreatedBy.Calls = append(s.Goroutines[s.goroutineIndex].CreatedBy.Calls, c)
806 s.state = gotRaceGoroutineFunc
807 return err == nil, err
808 }
809 return false, fmt.Errorf("expected a function after a race operation or a race file, got: %q", trimmed)
810
811 default:
812 return false, errors.New("internal error")
813 }
814 }
815
816 // parseFunc only return an error if it also returns true.
817 //
818 // Uses reFunc.
819 func parseFunc(c *Call, line []byte) (bool, error) {
820 if match := reFunc.FindSubmatch(line); match != nil {
821 if err := c.Func.Init(string(match[1])); err != nil {
822 return true, err
823 }
824 // It is also done in c.init() but do it here in case of a corrupted trace
825 // for the file section.
826 c.ImportPath = c.Func.ImportPath
827
828 args, err := parseArgs(match[2])
829 if err != nil {
830 return true, fmt.Errorf("%s on line: %q", err, bytes.TrimSpace(line))
831 }
832 c.Args = args
833 return true, nil
834 }
835 return false, nil
836 }
837
838 // parseArgs parses a collection of comma-separated arguments into an Args
839 // struct.
840 func parseArgs(line []byte) (Args, error) {
841 const maxDepth = 6 // 5 from traceback.go, +1 for top level
842 var stack [maxDepth]*Args
843 var args Args
844 depth := 0
845 stack[depth] = &args
846 for _, s := range bytes.Split(line, commaSpace) {
847 opened, a, closed := trimCurlyBrackets(s)
848 for i := 0; i < opened; i++ {
849 cur := stack[depth]
850 cur.Values = append(cur.Values, Arg{})
851 next := &cur.Values[len(cur.Values)-1]
852 next.IsAggregate = true
853 depth++
854 if depth >= maxDepth {
855 return Args{}, fmt.Errorf("nested aggregate-typed arguments exceeded depth limit")
856 }
857 stack[depth] = &next.Fields
858 }
859 if len(a) > 0 {
860 cur := stack[depth]
861 switch {
862 case bytes.Equal(a, threeDots):
863 cur.Elided = true
864 case bytes.Equal(a, underscore):
865 arg := Arg{IsOffsetTooLarge: true}
866 cur.Values = append(cur.Values, arg)
867 default:
868 inaccurate := bytes.HasSuffix(a, inaccurateQuestionMark)
869 if inaccurate {
870 a = a[:len(a)-len(inaccurateQuestionMark)]
871 }
872
873 v, err := strconv.ParseUint(unsafeString(a), 0, 64)
874 if err != nil {
875 return Args{}, errors.New("failed to parse int")
876 }
877 // Assume the stack was generated with the same bitness (32 vs 64) as
878 // the code processing it.
879 arg := Arg{Value: v, IsPtr: v > pointerFloor && v < pointerCeiling, IsInaccurate: inaccurate}
880 cur.Values = append(cur.Values, arg)
881 }
882 }
883 for i := 0; i < closed; i++ {
884 stack[depth] = nil
885 depth--
886 if depth < 0 {
887 return Args{}, errors.New("unmatched closing curly bracket")
888 }
889 }
890 }
891 if depth != 0 {
892 return Args{}, errors.New("unmatched opening curly bracket")
893 }
894 return args, nil
895 }
896
897 // parseFile only return an error if also processing a Call.
898 //
899 // Uses reFile.
900 func parseFile(c *Call, line []byte) (bool, error) {
901 if match := reFile.FindSubmatch(line); match != nil {
902 num, ok := atou(match[2])
903 if !ok {
904 return true, fmt.Errorf("failed to parse int on line: %q", bytes.TrimSpace(line))
905 }
906 c.init(string(match[1]), num)
907 return true, nil
908 }
909 return false, nil
910 }
911
912 // hasPrefix returns true if any of s is the prefix of p.
913 func hasPrefix(p string, s map[string]string) bool {
914 lp := len(p)
915 for prefix := range s {
916 if l := len(prefix); lp > l+1 && p[:l] == prefix && p[l] == '/' {
917 return true
918 }
919 }
920 return false
921 }
922
923 // hasSrcPrefix returns true if any of s is the prefix of p with /src/ or
924 // /pkg/mod/.
925 func hasSrcPrefix(p string, s map[string]string) bool {
926 lp := len(p)
927 const src = "/src/"
928 const pkgmod = "/pkg/mod/"
929 for prefix := range s {
930 l := len(prefix)
931 if lp > l+len(src) && p[:l] == prefix && p[l:l+len(src)] == src {
932 return true
933 }
934 if lp > l+len(pkgmod) && p[:l] == prefix && p[l:l+len(pkgmod)] == pkgmod {
935 return true
936 }
937 }
938 return false
939 }
940
941 // getFiles returns all the source files deduped and ordered.
942 func getFiles(goroutines []*Goroutine) []string {
943 files := map[string]struct{}{}
944 for _, g := range goroutines {
945 for _, c := range g.Stack.Calls {
946 files[c.RemoteSrcPath] = struct{}{}
947 }
948 }
949 if len(files) == 0 {
950 return nil
951 }
952 out := make([]string, 0, len(files))
953 for f := range files {
954 out = append(out, f)
955 }
956 sort.Strings(out)
957 return out
958 }
959
960 // splitPath splits a path using "/" as separator into its components.
961 //
962 // The first item has its initial path separator kept.
963 func splitPath(p string) []string {
964 if p == "" {
965 return nil
966 }
967 var out []string
968 s := ""
969 for _, c := range p {
970 if c != '/' || (len(out) == 0 && strings.Count(s, "/") == len(s)) {
971 s += string(c)
972 } else if s != "" {
973 out = append(out, s)
974 s = ""
975 }
976 }
977 if s != "" {
978 out = append(out, s)
979 }
980 return out
981 }
982
983 // isFile returns true if the path is a valid file.
984 func isFile(p string) bool {
985 // TODO(maruel): Is it faster to open the file or to stat it? Worth a perf
986 // test on Windows.
987 i, err := os.Stat(p)
988 return err == nil && !i.IsDir()
989 }
990
991 // isRootedIn returns a root if the file split in parts exists under root.
992 //
993 // Uses "/" as path separator.
994 func isRootedIn(root string, parts []string) string {
995 for i := 1; i < len(parts); i++ {
996 suffix := pathJoin(parts[i:]...)
997 if isFile(pathJoin(root, suffix)) {
998 return pathJoin(parts[:i]...)
999 }
1000 }
1001 return ""
1002 }
1003
1004 // reModule find the module line in a go.mod file. It works even on CRLF file.
1005 var reModule = regexp.MustCompile(`(?m)^module\s+([^\n\r]+)\r?$`)
1006
1007 type gomodCache map[string]struct{}
1008
1009 // isGoModule returns the string to the directory containing a go.mod file, and
1010 // the go import path it represents, if found.
1011 func (g *gomodCache) isGoModule(parts []string) (string, string) {
1012 for i := len(parts); i > 0; i-- {
1013 prefix := pathJoin(parts[:i]...)
1014 // Was already looked up.
1015 if _, ok := (*g)[prefix]; ok {
1016 break
1017 }
1018 (*g)[prefix] = struct{}{}
1019 p := pathJoin(prefix, "go.mod")
1020 if runtime.GOOS == "windows" {
1021 p = strings.Replace(p, "/", pathSeparator, -1)
1022 }
1023 /* #nosec G304 */
1024 b, err := os.ReadFile(p)
1025 if err != nil {
1026 continue
1027 }
1028 if match := reModule.FindSubmatch(b); match != nil {
1029 return prefix, string(match[1])
1030 }
1031 }
1032 return "", ""
1033 }
1034
1035 // findRoots sets member RemoteGOROOT, RemoteGOPATHs and LocalGomods.
1036 //
1037 // This causes disk I/O as it checks for file presence.
1038 //
1039 // Returns the number of missing files.
1040 func (s *Snapshot) findRoots() int {
1041 // TODO(maruel): Reduce memory allocations in this function.
1042 s.RemoteGOPATHs = map[string]string{}
1043 s.LocalGomods = map[string]string{}
1044 missing := 0
1045 gmc := gomodCache{}
1046 for _, f := range getFiles(s.Goroutines) {
1047 // TODO(maruel): Could a stack dump have mixed cases? I think it's
1048 // possible, need to confirm and handle.
1049 //log.Printf(" Analyzing %s", f)
1050
1051 // First checks skip file I/O.
1052 if s.RemoteGOROOT != "" && strings.HasPrefix(f, s.RemoteGOROOT+"/src/") {
1053 // stdlib.
1054 continue
1055 }
1056 if hasSrcPrefix(f, s.RemoteGOPATHs) {
1057 // $GOPATH/src or go.mod dependency in $GOPATH/pkg/mod.
1058 continue
1059 }
1060 if hasPrefix(f, s.LocalGomods) {
1061 continue
1062 }
1063
1064 // At this point, disk will be looked up.
1065 parts := splitPath(f)
1066 // Initializes RemoteGOROOT.
1067 const src = "/src"
1068 if s.RemoteGOROOT == "" {
1069 if r := isRootedIn(s.LocalGOROOT+src, parts); r != "" {
1070 s.RemoteGOROOT = r[:len(r)-len(src)]
1071 //log.Printf("Found RemoteGOROOT=%s", s.RemoteGOROOT)
1072 continue
1073 }
1074 }
1075 // Initializes RemoteGOPATHs.
1076 found := false
1077 for _, l := range s.LocalGOPATHs {
1078 if r := isRootedIn(l+src, parts); r != "" {
1079 //log.Printf("Found RemoteGOPATHs[%s] = %s", r[:len(r)-len(src)], l)
1080 s.RemoteGOPATHs[r[:len(r)-len(src)]] = l
1081 found = true
1082 break
1083 }
1084 const pkgmod = "/pkg/mod"
1085 if r := isRootedIn(l+pkgmod, parts); r != "" {
1086 //log.Printf("Found RemoteGOPATHs[%s] = %s", r[:len(r)-len(pkgmod)], l)
1087 s.RemoteGOPATHs[r[:len(r)-len(pkgmod)]] = l
1088 found = true
1089 break
1090 }
1091 }
1092 if found {
1093 continue
1094 }
1095 // Initializes localGomods.
1096 if len(parts) > 1 {
1097 // Search upward looking for a go.mod.
1098 if root, path := gmc.isGoModule(parts[:len(parts)-1]); root != "" {
1099 s.LocalGomods[root] = path
1100 continue
1101 }
1102 }
1103 if isFile(f) {
1104 // Assumes "go run" was used, thus is package main. Still consider it a
1105 // "go module" but in the weakest sense.
1106 s.LocalGomods[path.Dir(f)] = "main"
1107 continue
1108 }
1109 // If the source is not found, just too bad.
1110 //log.Printf("Failed to find locally: %s", f)
1111 missing++
1112 }
1113 return missing
1114 }
1115
1116 // getGOPATHs returns parsed GOPATH or its default, using "/" as path separator.
1117 func getGOPATHs() []string {
1118 var out []string
1119 if gp := os.Getenv("GOPATH"); gp != "" {
1120 for _, v := range filepath.SplitList(gp) {
1121 // Disallow non-absolute paths?
1122 if v != "" {
1123 if runtime.GOOS == "windows" {
1124 v = strings.Replace(v, pathSeparator, "/", -1)
1125 }
1126 // Trim trailing "/".
1127 if l := len(v); v[l-1] == '/' {
1128 v = v[:l-1]
1129 }
1130 out = append(out, v)
1131 }
1132 }
1133 }
1134 if len(out) == 0 {
1135 homeDir := ""
1136 u, err := user.Current()
1137 if err != nil {
1138 homeDir = os.Getenv("HOME")
1139 if homeDir == "" {
1140 panic(fmt.Sprintf("Could not get current user or $HOME: %s\n", err.Error()))
1141 }
1142 } else {
1143 homeDir = u.HomeDir
1144 }
1145 p := homeDir + "/go"
1146 if runtime.GOOS == "windows" {
1147 p = strings.Replace(p, pathSeparator, "/", -1)
1148 }
1149 out = []string{p}
1150 }
1151 return out
1152 }
1153
1154 // atou is a fast Atoi() function.
1155 //
1156 // It is a very simplified version of strconv.Atoi() that it never go into the
1157 // slow path and it operates on []byte instead of string so it doesn't do
1158 // memory allocation. It will fail on edge cases like prefix of zeros and other
1159 // things that the panic stack trace generator never outputs.
1160 //
1161 // It doesn't handle negative values.
1162 func atou(s []byte) (int, bool) {
1163 if l := len(s); strconv.IntSize == 32 && (0 < l && l < 10) || strconv.IntSize == 64 && (0 < l && l < 19) {
1164 n := 0
1165 for _, ch := range s {
1166 if ch -= '0'; ch > 9 {
1167 return 0, false
1168 }
1169 n = n*10 + int(ch)
1170 }
1171 return n, true
1172 }
1173 return 0, false
1174 }
1175
1176 // trimLeftSpace is the faster equivalent of bytes.TrimLeft(s, "\t ").
1177 func trimLeftSpace(s []byte) []byte {
1178 for i, ch := range s {
1179 if ch != '\t' && ch != ' ' {
1180 return s[i:]
1181 }
1182 }
1183 return nil
1184 }
1185
1186 // trimCurlyBrackets is the faster equivalent of
1187 // bytes.TrimRight(bytes.TrimLeft(s, "{"), "}"). The function
1188 // also returns the number of curly brackets trimmed from the
1189 // left and the right.
1190 func trimCurlyBrackets(s []byte) (int, []byte, int) {
1191 i, j := 0, len(s)
1192 for ; i < j; i++ {
1193 if s[i] != '{' {
1194 break
1195 }
1196 }
1197 for ; i < j; j-- {
1198 if s[j-1] != '}' {
1199 break
1200 }
1201 }
1202 return i, s[i:j], len(s) - j
1203 }
1204
1205 // unsafeString performs an unsafe conversion from a []byte to a string. The
1206 // returned string will share the underlying memory with the []byte which thus
1207 // allows the string to be mutable through the []byte. We're careful to use
1208 // this method only in situations in which the []byte will not be modified.
1209 //
1210 // A workaround for the absence of https://github.com/golang/go/issues/2632.
1211 func unsafeString(b []byte) string {
1212 /* #nosec G103 */
1213 return *(*string)(unsafe.Pointer(&b))
1214 }