Debian Codegraph @

stack/context_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
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 package stack
6
7 import (
8 "bufio"
9 "bytes"
10 "errors"
11 "fmt"
12 "io"
13 "os"
14 "os/exec"
15 "path"
16 "path/filepath"
17 "regexp"
18 "runtime"
19 "strings"
20 "testing"
21
22 "github.com/google/go-cmp/cmp"
23 "github.com/maruel/panicparse/v2/internal/internaltest"
24 )
25
26 func TestScanSnapshotErr(t *testing.T) {
27 t.Parallel()
28 data := []*Opts{
29 nil,
30 {LocalGOROOT: "\\"},
31 {LocalGOPATHs: []string{"\\"}},
32 }
33 for _, opts := range data {
34 if _, _, err := ScanSnapshot(&bytes.Buffer{}, io.Discard, opts); err == nil {
35 t.Fatal("expected error")
36 }
37 }
38 }
39
40 func TestScanSnapshotSynthetic(t *testing.T) {
41 t.Parallel()
42 data := []struct {
43 name string
44 in []string
45 prefix string
46 suffix string
47 err error
48 want []*Goroutine
49 }{
50 {
51 name: "Nothing",
52 err: io.EOF,
53 },
54 {
55 name: "NothingEmpty",
56 in: make([]string, 111),
57 prefix: strings.Repeat("\n", 110),
58 err: io.EOF,
59 },
60 {
61 name: "NothingLong",
62 in: []string{strings.Repeat("a", bufio.MaxScanTokenSize+10)},
63 prefix: strings.Repeat("a", bufio.MaxScanTokenSize+10),
64 err: io.EOF,
65 },
66
67 // One call from main, one from stdlib, one from third party.
68 // Create a long first line that will be ignored. It is to guard against
69 // https://github.com/maruel/panicparse/issues/17.
70 {
71 name: "long,main,stdlib,third",
72 in: []string{
73 strings.Repeat("a", bufio.MaxScanTokenSize+1),
74 "panic: reflect.Set: value of type",
75 "",
76 "goroutine 1 [running]:",
77 "github.com/cockroachdb/cockroach/storage/engine._Cfunc_DBIterSeek()",
78 " ??:0 +0x6d",
79 "gopkg.in/yaml%2ev2.handleErr(0x433b20)",
80 "\t/gopath/src/gopkg.in/yaml.v2/yaml.go:153 +0xc6",
81 "reflect.Value.assignTo(0x570860, 0x803f3e0, 0x15)",
82 "\t/goroot/src/reflect/value.go:2125 +0x368",
83 "main.main()",
84 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:428 +0x27",
85 "",
86 },
87 prefix: strings.Repeat("a", bufio.MaxScanTokenSize+1) + "\npanic: reflect.Set: value of type\n\n",
88 err: io.EOF,
89 want: []*Goroutine{
90 {
91 Signature: Signature{
92 State: "running",
93 Stack: Stack{
94 Calls: []Call{
95 newCall(
96 "github.com/cockroachdb/cockroach/storage/engine._Cfunc_DBIterSeek",
97 Args{}, "??", 0),
98 newCall(
99 "gopkg.in/yaml%2ev2.handleErr",
100 Args{Values: []Arg{{Value: 0x433b20, IsPtr: true}}},
101 "/gopath/src/gopkg.in/yaml.v2/yaml.go",
102 153),
103 newCall(
104 "reflect.Value.assignTo",
105 Args{Values: []Arg{{Value: 0x570860, IsPtr: true}, {Value: 0x803f3e0, IsPtr: true}, {Value: 0x15}}},
106 "/goroot/src/reflect/value.go",
107 2125),
108 newCall(
109 "main.main",
110 Args{},
111 "/gopath/src/github.com/maruel/panicparse/stack/stack.go",
112 428),
113 },
114 },
115 },
116 ID: 1,
117 First: true,
118 },
119 },
120 },
121
122 {
123 name: "LongWait",
124 in: []string{
125 "panic: bleh",
126 "",
127 "goroutine 1 [chan send, 100 minutes]:",
128 "gopkg.in/yaml%2ev2.handleErr(0x433b20)",
129 "\t/gopath/src/gopkg.in/yaml.v2/yaml.go:153 +0xc6",
130 "",
131 "goroutine 2 [chan send, locked to thread]:",
132 "gopkg.in/yaml%2ev2.handleErr(0x8033b21)",
133 "\t/gopath/src/gopkg.in/yaml.v2/yaml.go:153 +0xc6",
134 "",
135 "goroutine 3 [chan send, 101 minutes, locked to thread]:",
136 "gopkg.in/yaml%2ev2.handleErr(0x8033b22)",
137 "\t/gopath/src/gopkg.in/yaml.v2/yaml.go:153 +0xc6",
138 "",
139 },
140 prefix: "panic: bleh\n\n",
141 err: io.EOF,
142 want: []*Goroutine{
143 {
144 Signature: Signature{
145 State: "chan send",
146 SleepMin: 100,
147 SleepMax: 100,
148 Stack: Stack{
149 Calls: []Call{
150 newCall(
151 "gopkg.in/yaml%2ev2.handleErr",
152 Args{Values: []Arg{{Value: 0x433b20, IsPtr: true}}},
153 "/gopath/src/gopkg.in/yaml.v2/yaml.go",
154 153),
155 },
156 },
157 },
158 ID: 1,
159 First: true,
160 },
161 {
162 Signature: Signature{
163 State: "chan send",
164 Locked: true,
165 Stack: Stack{
166 Calls: []Call{
167 newCall(
168 "gopkg.in/yaml%2ev2.handleErr",
169 Args{Values: []Arg{{Value: 0x8033b21, Name: "#1", IsPtr: true}}},
170 "/gopath/src/gopkg.in/yaml.v2/yaml.go",
171 153),
172 },
173 },
174 },
175 ID: 2,
176 },
177 {
178 Signature: Signature{
179 State: "chan send",
180 SleepMin: 101,
181 SleepMax: 101,
182 Stack: Stack{
183 Calls: []Call{
184 newCall(
185 "gopkg.in/yaml%2ev2.handleErr",
186 Args{Values: []Arg{{Value: 0x8033b22, Name: "#2", IsPtr: true}}},
187 "/gopath/src/gopkg.in/yaml.v2/yaml.go",
188 153),
189 },
190 },
191 Locked: true,
192 },
193 ID: 3,
194 },
195 },
196 },
197
198 {
199 name: "Assembly",
200 in: []string{
201 "panic: reflect.Set: value of type",
202 "",
203 "goroutine 16 [garbage collection]:",
204 "runtime.switchtoM()",
205 "\t/goroot/src/runtime/asm_amd64.s:198 fp=0xc20cfb80d8 sp=0xc20cfb80d0",
206 "",
207 },
208 prefix: "panic: reflect.Set: value of type\n\n",
209 err: io.EOF,
210 want: []*Goroutine{
211 {
212 Signature: Signature{
213 State: "garbage collection",
214 Stack: Stack{
215 Calls: []Call{
216 newCall(
217 "runtime.switchtoM",
218 Args{},
219 "/goroot/src/runtime/asm_amd64.s",
220 198),
221 },
222 },
223 },
224 ID: 16,
225 First: true,
226 },
227 },
228 },
229
230 {
231 name: "Assembly1.3",
232 in: []string{
233 "panic: reflect.Set: value of type",
234 "",
235 "goroutine 16 [garbage collection]:",
236 "runtime.switchtoM()",
237 "\t/goroot/src/runtime/asm_amd64.s:198 fp=0xc20cfb80d8 sp=0xc20cfb80d0 pc=0x5007be",
238 "",
239 },
240 prefix: "panic: reflect.Set: value of type\n\n",
241 err: io.EOF,
242 want: []*Goroutine{
243 {
244 Signature: Signature{
245 State: "garbage collection",
246 Stack: Stack{
247 Calls: []Call{
248 newCall(
249 "runtime.switchtoM",
250 Args{},
251 "/goroot/src/runtime/asm_amd64.s",
252 198),
253 },
254 },
255 },
256 ID: 16,
257 First: true,
258 },
259 },
260 },
261
262 {
263 name: "LineErr",
264 in: []string{
265 "panic: reflect.Set: value of type",
266 "",
267 "goroutine 1 [running]:",
268 "github.com/maruel/panicparse/stack/stack.recurseType()",
269 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:12345678901234567890",
270 "",
271 },
272 prefix: "panic: reflect.Set: value of type\n\n",
273 suffix: "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:12345678901234567890\n",
274 err: errors.New("failed to parse int on line: \"/gopath/src/github.com/maruel/panicparse/stack/stack.go:12345678901234567890\""),
275 want: []*Goroutine{
276 {
277 Signature: Signature{
278 State: "running",
279 Stack: Stack{
280 Calls: []Call{
281 newCall("github.com/maruel/panicparse/stack/stack.recurseType", Args{}, "", 0),
282 },
283 },
284 },
285 ID: 1,
286 First: true,
287 },
288 },
289 },
290
291 {
292 name: "CreatedErr",
293 in: []string{
294 "panic: reflect.Set: value of type",
295 "",
296 "goroutine 1 [running]:",
297 "github.com/maruel/panicparse/stack/stack.recurseType()",
298 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:1",
299 "created by testing.RunTests",
300 "\t/goroot/src/testing/testing.go:123456789012345678901 +0xa8b",
301 "",
302 },
303 prefix: "panic: reflect.Set: value of type\n\n",
304 suffix: "\t/goroot/src/testing/testing.go:123456789012345678901 +0xa8b\n",
305 err: errors.New("failed to parse int on line: \"/goroot/src/testing/testing.go:123456789012345678901 +0xa8b\""),
306 want: []*Goroutine{
307 {
308 Signature: Signature{
309 State: "running",
310 CreatedBy: Stack{Calls: []Call{newCall("testing.RunTests", Args{}, "", 0)}},
311 Stack: Stack{
312 Calls: []Call{
313 newCall(
314 "github.com/maruel/panicparse/stack/stack.recurseType",
315 Args{},
316 "/gopath/src/github.com/maruel/panicparse/stack/stack.go",
317 1),
318 },
319 },
320 },
321 ID: 1,
322 First: true,
323 },
324 },
325 },
326
327 {
328 name: "ValueErr",
329 in: []string{
330 "panic: reflect.Set: value of type",
331 "",
332 "goroutine 1 [running]:",
333 "github.com/maruel/panicparse/stack/stack.recurseType(123456789012345678901)",
334 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:9",
335 "",
336 },
337 prefix: "panic: reflect.Set: value of type\n\n",
338 suffix: "github.com/maruel/panicparse/stack/stack.recurseType(123456789012345678901)\n" +
339 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:9\n",
340 err: errors.New("failed to parse int on line: \"github.com/maruel/panicparse/stack/stack.recurseType(123456789012345678901)\""),
341 want: []*Goroutine{
342 {
343 Signature: Signature{
344 State: "running",
345 Stack: Stack{
346 Calls: []Call{
347 newCall("github.com/maruel/panicparse/stack/stack.recurseType", Args{}, "", 0),
348 },
349 },
350 },
351 ID: 1,
352 First: true,
353 },
354 },
355 },
356
357 {
358 name: "MaxNestingDepth",
359 in: []string{
360 "panic: reflect.Set: value of type",
361 "",
362 "goroutine 1 [running]:",
363 "github.com/maruel/panicparse/stack/stack.recurseType({{{{{...}}}}})",
364 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:9",
365 "",
366 },
367 prefix: "panic: reflect.Set: value of type\n\n",
368 err: io.EOF,
369 want: []*Goroutine{
370 {
371 Signature: Signature{
372 State: "running",
373 Stack: Stack{
374 Calls: []Call{
375 newCall(
376 "github.com/maruel/panicparse/stack/stack.recurseType",
377 Args{
378 Values: []Arg{{IsAggregate: true, Fields: Args{
379 Values: []Arg{{IsAggregate: true, Fields: Args{
380 Values: []Arg{{IsAggregate: true, Fields: Args{
381 Values: []Arg{{IsAggregate: true, Fields: Args{
382 Values: []Arg{{IsAggregate: true, Fields: Args{
383 Elided: true,
384 }}},
385 }}},
386 }}},
387 }}},
388 }}},
389 },
390 "/gopath/src/github.com/maruel/panicparse/stack/stack.go",
391 9),
392 },
393 },
394 },
395 ID: 1,
396 First: true,
397 },
398 },
399 },
400
401 {
402 name: "MaxNestingDepthExceededErr",
403 in: []string{
404 "panic: reflect.Set: value of type",
405 "",
406 "goroutine 1 [running]:",
407 "github.com/maruel/panicparse/stack/stack.recurseType({{{{{{...}}}}}})",
408 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:9",
409 "",
410 },
411 prefix: "panic: reflect.Set: value of type\n\n",
412 suffix: "github.com/maruel/panicparse/stack/stack.recurseType({{{{{{...}}}}}})\n" +
413 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:9\n",
414 err: errors.New("nested aggregate-typed arguments exceeded depth limit on line: \"github.com/maruel/panicparse/stack/stack.recurseType({{{{{{...}}}}}})\""),
415 want: []*Goroutine{
416 {
417 Signature: Signature{
418 State: "running",
419 Stack: Stack{
420 Calls: []Call{
421 newCall("github.com/maruel/panicparse/stack/stack.recurseType", Args{}, "", 0),
422 },
423 },
424 },
425 ID: 1,
426 First: true,
427 },
428 },
429 },
430
431 {
432 name: "UnmatchedOpeningCurlyBracketErr",
433 in: []string{
434 "panic: reflect.Set: value of type",
435 "",
436 "goroutine 1 [running]:",
437 "github.com/maruel/panicparse/stack/stack.recurseType({{{{{...}}}})",
438 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:9",
439 "",
440 },
441 prefix: "panic: reflect.Set: value of type\n\n",
442 suffix: "github.com/maruel/panicparse/stack/stack.recurseType({{{{{...}}}})\n" +
443 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:9\n",
444 err: errors.New("unmatched opening curly bracket on line: \"github.com/maruel/panicparse/stack/stack.recurseType({{{{{...}}}})\""),
445 want: []*Goroutine{
446 {
447 Signature: Signature{
448 State: "running",
449 Stack: Stack{
450 Calls: []Call{
451 newCall("github.com/maruel/panicparse/stack/stack.recurseType", Args{}, "", 0),
452 },
453 },
454 },
455 ID: 1,
456 First: true,
457 },
458 },
459 },
460
461 {
462 name: "UnmatchedClosingCurlyBracketErr",
463 in: []string{
464 "panic: reflect.Set: value of type",
465 "",
466 "goroutine 1 [running]:",
467 "github.com/maruel/panicparse/stack/stack.recurseType({{{{...}}}}})",
468 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:9",
469 "",
470 },
471 prefix: "panic: reflect.Set: value of type\n\n",
472 suffix: "github.com/maruel/panicparse/stack/stack.recurseType({{{{...}}}}})\n" +
473 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:9\n",
474 err: errors.New("unmatched closing curly bracket on line: \"github.com/maruel/panicparse/stack/stack.recurseType({{{{...}}}}})\""),
475 want: []*Goroutine{
476 {
477 Signature: Signature{
478 State: "running",
479 Stack: Stack{
480 Calls: []Call{
481 newCall("github.com/maruel/panicparse/stack/stack.recurseType", Args{}, "", 0),
482 },
483 },
484 },
485 ID: 1,
486 First: true,
487 },
488 },
489 },
490
491 {
492 name: "InconsistentIndent",
493 in: []string{
494 " goroutine 1 [running]:",
495 " github.com/maruel/panicparse/stack/stack.recurseType()",
496 " \t/gopath/src/github.com/maruel/panicparse/stack/stack.go:1",
497 "",
498 },
499 suffix: " \t/gopath/src/github.com/maruel/panicparse/stack/stack.go:1\n",
500 err: errors.New(`inconsistent indentation: " \t/gopath/src/github.com/maruel/panicparse/stack/stack.go:1", expected " "`),
501 want: []*Goroutine{
502 {
503 Signature: Signature{
504 State: "running",
505 Stack: Stack{
506 Calls: []Call{
507 newCall("github.com/maruel/panicparse/stack/stack.recurseType", Args{}, "", 0),
508 },
509 },
510 },
511 ID: 1,
512 First: true,
513 },
514 },
515 },
516
517 {
518 name: "OrderErr",
519 in: []string{
520 "panic: reflect.Set: value of type",
521 "",
522 "goroutine 16 [garbage collection]:",
523 "\t/gopath/src/gopkg.in/yaml.v2/yaml.go:153 +0xc6",
524 "runtime.switchtoM()",
525 "\t/goroot/src/runtime/asm_amd64.s:198 fp=0xc20cfb80d8 sp=0xc20cfb80d0",
526 "",
527 },
528 prefix: "panic: reflect.Set: value of type\n\n",
529 suffix: "\t/gopath/src/gopkg.in/yaml.v2/yaml.go:153 +0xc6\n" +
530 "runtime.switchtoM()\n" +
531 "\t/goroot/src/runtime/asm_amd64.s:198 fp=0xc20cfb80d8 sp=0xc20cfb80d0\n",
532 err: errors.New("expected a function after a goroutine header, got: \"/gopath/src/gopkg.in/yaml.v2/yaml.go:153 +0xc6\""),
533 want: []*Goroutine{
534 {
535 Signature: Signature{State: "garbage collection"},
536 ID: 16,
537 First: true,
538 },
539 },
540 },
541
542 {
543 name: "Elided",
544 in: []string{
545 "panic: reflect.Set: value of type",
546 "",
547 "goroutine 16 [garbage collection]:",
548 "github.com/maruel/panicparse/stack/stack.recurseType(0x9a3ec70, 0x8062580, 0x9a3e818, 0x50a820, 0x803a8a0)",
549 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:53 +0x845 fp=0xc20cfc66d8 sp=0xc20cfc6470",
550 "...additional frames elided...",
551 "created by testing.RunTests",
552 "\t/goroot/src/testing/testing.go:555 +0xa8b",
553 "",
554 },
555 prefix: "panic: reflect.Set: value of type\n\n",
556 err: io.EOF,
557 want: []*Goroutine{
558 {
559 Signature: Signature{
560 State: "garbage collection",
561 CreatedBy: Stack{
562 Calls: []Call{
563 newCall(
564 "testing.RunTests",
565 Args{},
566 "/goroot/src/testing/testing.go",
567 555),
568 },
569 },
570 Stack: Stack{
571 Calls: []Call{
572 newCall(
573 "github.com/maruel/panicparse/stack/stack.recurseType",
574 Args{
575 Values: []Arg{
576 {Value: 0x9a3ec70, IsPtr: true},
577 {Value: 0x8062580, IsPtr: true},
578 {Value: 0x9a3e818, IsPtr: true},
579 {Value: 0x50a820, IsPtr: true},
580 {Value: 0x803a8a0, IsPtr: true},
581 },
582 },
583 "/gopath/src/github.com/maruel/panicparse/stack/stack.go",
584 53),
585 },
586 Elided: true,
587 },
588 },
589 ID: 16,
590 First: true,
591 },
592 },
593 },
594
595 {
596 name: "Syscall",
597 in: []string{
598 "panic: reflect.Set: value of type",
599 "",
600 "goroutine 5 [syscall]:",
601 "runtime.notetsleepg(0x918100, 0xffffffffffffffff, 0x1)",
602 "\t/goroot/src/runtime/lock_futex.go:201 +0x52 fp=0xc208018f68 sp=0xc208018f40",
603 "runtime.signal_recv(0x0)",
604 "\t/goroot/src/runtime/sigqueue.go:109 +0x135 fp=0xc208018fa0 sp=0xc208018f68",
605 "os/signal.loop()",
606 "\t/goroot/src/os/signal/signal_unix.go:21 +0x1f fp=0xc208018fe0 sp=0xc208018fa0",
607 "runtime.goexit()",
608 "\t/goroot/src/runtime/asm_amd64.s:2232 +0x1 fp=0xc208018fe8 sp=0xc208018fe0",
609 "created by os/signal.init·1",
610 "\t/goroot/src/os/signal/signal_unix.go:27 +0x35",
611 "",
612 },
613 prefix: "panic: reflect.Set: value of type\n\n",
614 err: io.EOF,
615 want: []*Goroutine{
616 {
617 Signature: Signature{
618 State: "syscall",
619 CreatedBy: Stack{
620 Calls: []Call{
621 newCall(
622 "os/signal.init·1",
623 Args{},
624 "/goroot/src/os/signal/signal_unix.go",
625 27),
626 },
627 },
628 Stack: Stack{
629 Calls: []Call{
630 newCall(
631 "runtime.notetsleepg",
632 Args{
633 Values: []Arg{
634 {Value: 0x918100, IsPtr: true},
635 {Value: 0xffffffffffffffff},
636 {Value: 0x1},
637 },
638 },
639 "/goroot/src/runtime/lock_futex.go",
640 201),
641 newCall(
642 "runtime.signal_recv",
643 Args{Values: []Arg{{}}},
644 "/goroot/src/runtime/sigqueue.go",
645 109),
646 newCall(
647 "os/signal.loop",
648 Args{},
649 "/goroot/src/os/signal/signal_unix.go",
650 21),
651 newCall(
652 "runtime.goexit",
653 Args{},
654 "/goroot/src/runtime/asm_amd64.s",
655 2232),
656 },
657 },
658 },
659 ID: 5,
660 First: true,
661 },
662 },
663 },
664
665 {
666 name: "UnavailCreated",
667 in: []string{
668 "panic: reflect.Set: value of type",
669 "",
670 "goroutine 24 [running]:",
671 "\tgoroutine running on other thread; stack unavailable",
672 "created by github.com/maruel/panicparse/stack.New",
673 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:131 +0x381",
674 "",
675 },
676 prefix: "panic: reflect.Set: value of type\n\n",
677 err: io.EOF,
678 want: []*Goroutine{
679 {
680 Signature: Signature{
681 State: "running",
682 CreatedBy: Stack{
683 Calls: []Call{
684 newCall(
685 "github.com/maruel/panicparse/stack.New",
686 Args{},
687 "/gopath/src/github.com/maruel/panicparse/stack/stack.go",
688 131),
689 },
690 },
691 Stack: Stack{
692 Calls: []Call{newCall("", Args{}, "<unavailable>", 0)},
693 },
694 },
695 ID: 24,
696 First: true,
697 },
698 },
699 },
700
701 {
702 name: "Unavail",
703 in: []string{
704 "panic: reflect.Set: value of type",
705 "",
706 "goroutine 24 [running]:",
707 "\tgoroutine running on other thread; stack unavailable",
708 "",
709 "",
710 },
711 prefix: "panic: reflect.Set: value of type\n\n",
712 err: io.EOF,
713 want: []*Goroutine{
714 {
715 Signature: Signature{
716 State: "running",
717 Stack: Stack{
718 Calls: []Call{newCall("", Args{}, "<unavailable>", 0)},
719 },
720 },
721 ID: 24,
722 First: true,
723 },
724 },
725 },
726
727 {
728 name: "UnavailError",
729 in: []string{
730 "panic: reflect.Set: value of type",
731 "",
732 "goroutine 24 [running]:",
733 "\tgoroutine running on other thread; stack unavailable",
734 "junk",
735 },
736 prefix: "panic: reflect.Set: value of type\n\n",
737 suffix: "junk",
738 err: errors.New("expected empty line after unavailable stack, got: \"junk\""),
739 want: []*Goroutine{
740 {
741 Signature: Signature{
742 State: "running",
743 Stack: Stack{
744 Calls: []Call{newCall("", Args{}, "<unavailable>", 0)},
745 },
746 },
747 ID: 24,
748 First: true,
749 },
750 },
751 },
752
753 {
754 name: "NoOffset",
755 in: []string{
756 "panic: runtime error: index out of range",
757 "",
758 "goroutine 37 [runnable]:",
759 "github.com/maruel/panicparse/stack.func·002()",
760 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:110",
761 "created by github.com/maruel/panicparse/stack.New",
762 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:113 +0x43b",
763 "",
764 },
765 prefix: "panic: runtime error: index out of range\n\n",
766 err: io.EOF,
767 want: []*Goroutine{
768 {
769 Signature: Signature{
770 State: "runnable",
771 CreatedBy: Stack{
772 Calls: []Call{
773 newCall(
774 "github.com/maruel/panicparse/stack.New",
775 Args{},
776 "/gopath/src/github.com/maruel/panicparse/stack/stack.go",
777 113),
778 },
779 },
780 Stack: Stack{
781 Calls: []Call{
782 newCall(
783 "github.com/maruel/panicparse/stack.func·002",
784 Args{},
785 "/gopath/src/github.com/maruel/panicparse/stack/stack.go",
786 110),
787 },
788 },
789 },
790 ID: 37,
791 First: true,
792 },
793 },
794 },
795
796 // For coverage of scanLines.
797 {
798 name: "HeaderError",
799 in: []string{
800 "panic: reflect.Set: value of type",
801 "",
802 "goroutine 1 [running]:",
803 "junk",
804 },
805 prefix: "panic: reflect.Set: value of type\n\n",
806 suffix: "junk",
807 err: errors.New("expected a function after a goroutine header, got: \"junk\""),
808 want: []*Goroutine{
809 {
810 Signature: Signature{State: "running"},
811 ID: 1,
812 First: true,
813 },
814 },
815 },
816
817 // For coverage of scanLines.
818 {
819 name: "FileError",
820 in: []string{
821 "panic: reflect.Set: value of type",
822 "",
823 "goroutine 1 [running]:",
824 "github.com/maruel/panicparse/stack.func·002()",
825 "junk",
826 },
827 prefix: "panic: reflect.Set: value of type\n\n",
828 suffix: "junk",
829 err: errors.New("expected a file after a function, got: \"junk\""),
830 want: []*Goroutine{
831 {
832 Signature: Signature{
833 State: "running",
834 Stack: Stack{
835 Calls: []Call{
836 newCall("github.com/maruel/panicparse/stack.func·002", Args{}, "", 0),
837 },
838 },
839 },
840 ID: 1,
841 First: true,
842 },
843 },
844 },
845
846 // For coverage of scanLines.
847 {
848 name: "Created",
849 in: []string{
850 "panic: reflect.Set: value of type",
851 "",
852 "goroutine 1 [running]:",
853 "github.com/maruel/panicparse/stack.func·002()",
854 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:110",
855 "created by github.com/maruel/panicparse/stack.New",
856 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:131 +0x381",
857 "exit status 2",
858 },
859 prefix: "panic: reflect.Set: value of type\n\n",
860 suffix: "exit status 2",
861 err: io.EOF,
862 want: []*Goroutine{
863 {
864 Signature: Signature{
865 State: "running",
866 CreatedBy: Stack{
867 Calls: []Call{
868 newCall(
869 "github.com/maruel/panicparse/stack.New",
870 Args{},
871 "/gopath/src/github.com/maruel/panicparse/stack/stack.go",
872 131),
873 },
874 },
875 Stack: Stack{
876 Calls: []Call{
877 newCall(
878 "github.com/maruel/panicparse/stack.func·002",
879 Args{},
880 "/gopath/src/github.com/maruel/panicparse/stack/stack.go",
881 110),
882 },
883 },
884 },
885 ID: 1,
886 First: true,
887 },
888 },
889 },
890
891 // For coverage of scanLines.
892 {
893 name: "CreatedError",
894 in: []string{
895 "panic: reflect.Set: value of type",
896 "",
897 "goroutine 1 [running]:",
898 "github.com/maruel/panicparse/stack.func·002()",
899 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:110",
900 "created by github.com/maruel/panicparse/stack.New",
901 "junk",
902 },
903 prefix: "panic: reflect.Set: value of type\n\n",
904 suffix: "junk",
905 err: errors.New("expected a file after a created line, got: \"junk\""),
906 want: []*Goroutine{
907 {
908 Signature: Signature{
909 State: "running",
910 CreatedBy: Stack{
911 Calls: []Call{
912 newCall("github.com/maruel/panicparse/stack.New", Args{}, "", 0),
913 },
914 },
915 Stack: Stack{
916 Calls: []Call{
917 newCall(
918 "github.com/maruel/panicparse/stack.func·002",
919 Args{},
920 "/gopath/src/github.com/maruel/panicparse/stack/stack.go",
921 110),
922 },
923 },
924 },
925 ID: 1,
926 First: true,
927 },
928 },
929 },
930
931 {
932 name: "CCode",
933 in: []string{
934 "SIGQUIT: quit",
935 "PC=0x43f349",
936 "",
937 "goroutine 0 [idle]:",
938 "runtime.epollwait(0x4, 0x71c7118, 0xffffffff00000080, 0x0, 0xffffffff0028c1be, 0x0, 0x0, 0x0, 0x0, 0x0, ...)",
939 " /goroot/src/runtime/sys_linux_amd64.s:400 +0x19",
940 "runtime.netpoll(0x901b01, 0x0)",
941 " /goroot/src/runtime/netpoll_epoll.go:68 +0xa3",
942 "findrunnable(0x8012000)",
943 " /goroot/src/runtime/proc.c:1472 +0x485",
944 "schedule()",
945 " /goroot/src/runtime/proc.c:1575 +0x151",
946 "runtime.park_m(0x80017a0)",
947 " /goroot/src/runtime/proc.c:1654 +0x113",
948 "runtime.mcall(0x432684)",
949 " /goroot/src/runtime/asm_amd64.s:186 +0x5a",
950 "",
951 },
952 prefix: "SIGQUIT: quit\nPC=0x43f349\n\n",
953 err: io.EOF,
954 want: []*Goroutine{
955 {
956 Signature: Signature{
957 State: "idle",
958 Stack: Stack{
959 Calls: []Call{
960 newCall(
961 "runtime.epollwait",
962 Args{
963 Values: []Arg{
964 {Value: 0x4},
965 {Value: 0x71c7118, IsPtr: true},
966 {Value: 0xffffffff00000080},
967 {},
968 {Value: 0xffffffff0028c1be},
969 {},
970 {},
971 {},
972 {},
973 {},
974 },
975 Elided: true,
976 },
977 "/goroot/src/runtime/sys_linux_amd64.s",
978 400),
979 newCall(
980 "runtime.netpoll",
981 Args{Values: []Arg{{Value: 0x901b01, IsPtr: true}, {}}},
982 "/goroot/src/runtime/netpoll_epoll.go",
983 68),
984 newCall(
985 "findrunnable",
986 Args{Values: []Arg{{Value: 0x8012000, IsPtr: true}}},
987 "/goroot/src/runtime/proc.c",
988 1472),
989 newCall("schedule", Args{}, "/goroot/src/runtime/proc.c", 1575),
990 newCall(
991 "runtime.park_m",
992 Args{Values: []Arg{{Value: 0x80017a0, IsPtr: true}}},
993 "/goroot/src/runtime/proc.c",
994 1654),
995 newCall(
996 "runtime.mcall",
997 Args{Values: []Arg{{Value: 0x432684, IsPtr: true}}},
998 "/goroot/src/runtime/asm_amd64.s",
999 186),
1000 },
1001 },
1002 },
1003 ID: 0,
1004 First: true,
1005 },
1006 },
1007 },
1008
1009 {
1010 name: "WithCarriageReturn",
1011 in: []string{
1012 "goroutine 1 [running]:",
1013 "github.com/cockroachdb/cockroach/storage/engine._Cfunc_DBIterSeek()",
1014 " ??:0 +0x6d",
1015 "gopkg.in/yaml%2ev2.handleErr(0x433b20)",
1016 "\t/gopath/src/gopkg.in/yaml.v2/yaml.go:153 +0xc6",
1017 "reflect.Value.assignTo(0x570860, 0x803f3e0, 0x15)",
1018 "\t/goroot/src/reflect/value.go:2125 +0x368",
1019 "main.main()",
1020 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:428 +0x27",
1021 "",
1022 },
1023 err: io.EOF,
1024 want: []*Goroutine{
1025 {
1026 Signature: Signature{
1027 State: "running",
1028 Stack: Stack{
1029 Calls: []Call{
1030 newCall(
1031 "github.com/cockroachdb/cockroach/storage/engine._Cfunc_DBIterSeek",
1032 Args{},
1033 "??",
1034 0),
1035 newCall(
1036 "gopkg.in/yaml%2ev2.handleErr",
1037 Args{Values: []Arg{{Value: 0x433b20, IsPtr: true}}},
1038 "/gopath/src/gopkg.in/yaml.v2/yaml.go",
1039 153),
1040 newCall(
1041 "reflect.Value.assignTo",
1042 Args{Values: []Arg{{Value: 0x570860, IsPtr: true}, {Value: 0x803f3e0, IsPtr: true}, {Value: 0x15}}},
1043 "/goroot/src/reflect/value.go",
1044 2125),
1045 newCall(
1046 "main.main",
1047 Args{},
1048 "/gopath/src/github.com/maruel/panicparse/stack/stack.go",
1049 428),
1050 },
1051 },
1052 },
1053 ID: 1,
1054 First: true,
1055 },
1056 },
1057 },
1058
1059 {
1060 name: "WithCarriageReturn1.18Inaccurate",
1061 in: []string{
1062 "goroutine 1 [running]:",
1063 "github.com/cockroachdb/cockroach/storage/engine._Cfunc_DBIterSeek()",
1064 " ??:0 +0x6d",
1065 "gopkg.in/yaml%2ev2.handleErr(0x433b20?)",
1066 "\t/gopath/src/gopkg.in/yaml.v2/yaml.go:153 +0xc6",
1067 "reflect.Value.assignTo(0x570860, 0x803f3e0, 0x15)",
1068 "\t/goroot/src/reflect/value.go:2125 +0x368",
1069 "main.main()",
1070 "\t/gopath/src/github.com/maruel/panicparse/stack/stack.go:428 +0x27",
1071 "",
1072 },
1073 err: io.EOF,
1074 want: []*Goroutine{
1075 {
1076 Signature: Signature{
1077 State: "running",
1078 Stack: Stack{
1079 Calls: []Call{
1080 newCall(
1081 "github.com/cockroachdb/cockroach/storage/engine._Cfunc_DBIterSeek",
1082 Args{},
1083 "??",
1084 0),
1085 newCall(
1086 "gopkg.in/yaml%2ev2.handleErr",
1087 Args{Values: []Arg{{Value: 0x433b20, IsPtr: true, IsInaccurate: true}}},
1088 "/gopath/src/gopkg.in/yaml.v2/yaml.go",
1089 153),
1090 newCall(
1091 "reflect.Value.assignTo",
1092 Args{Values: []Arg{{Value: 0x570860, IsPtr: true}, {Value: 0x803f3e0, IsPtr: true}, {Value: 0x15}}},
1093 "/goroot/src/reflect/value.go",
1094 2125),
1095 newCall(
1096 "main.main",
1097 Args{},
1098 "/gopath/src/github.com/maruel/panicparse/stack/stack.go",
1099 428),
1100 },
1101 },
1102 },
1103 ID: 1,
1104 First: true,
1105 },
1106 },
1107 },
1108
1109 // goconvey is culprit of this.
1110 {
1111 name: "Indented",
1112 in: []string{
1113 "Failures:",
1114 "",
1115 " * /home/maruel/go/src/foo/bar_test.go",
1116 " Line 209:",
1117 " Expected: '(*errors.errorString){s:\"context canceled\"}'",
1118 " Actual: 'nil'",
1119 " (Should resemble)!",
1120 " goroutine 8 [running]:",
1121 " foo/bar.TestArchiveFail.func1.2()",
1122 " /home/maruel/go/foo/bar_test.go:209 +0x469",
1123 " foo/bar.TestArchiveFail(0x3382000)",
1124 " /home/maruel/go/src/foo/bar_test.go:155 +0xf1",
1125 " testing.tRunner(0x3382000, 0x1615bf8)",
1126 " /home/maruel/golang/go/src/testing/testing.go:865 +0xc0",
1127 " created by testing.(*T).Run",
1128 " /home/maruel/golang/go/src/testing/testing.go:916 +0x35a",
1129 "",
1130 "",
1131 },
1132 prefix: strings.Join([]string{
1133 "Failures:",
1134 "",
1135 " * /home/maruel/go/src/foo/bar_test.go",
1136 " Line 209:",
1137 " Expected: '(*errors.errorString){s:\"context canceled\"}'",
1138 " Actual: 'nil'",
1139 " (Should resemble)!",
1140 "",
1141 }, "\n"),
1142 err: io.EOF,
1143 want: []*Goroutine{
1144 {
1145 Signature: Signature{
1146 State: "running",
1147 CreatedBy: Stack{
1148 Calls: []Call{
1149 newCall(
1150 "testing.(*T).Run",
1151 Args{},
1152 "/home/maruel/golang/go/src/testing/testing.go",
1153 916),
1154 },
1155 },
1156 Stack: Stack{
1157 Calls: []Call{
1158 newCall(
1159 "foo/bar.TestArchiveFail.func1.2",
1160 Args{},
1161 "/home/maruel/go/foo/bar_test.go",
1162 209),
1163 newCall(
1164 "foo/bar.TestArchiveFail",
1165 Args{Values: []Arg{{Value: 0x3382000, Name: "#1", IsPtr: true}}},
1166 "/home/maruel/go/src/foo/bar_test.go",
1167 155),
1168 newCall(
1169 "testing.tRunner",
1170 Args{Values: []Arg{{Value: 0x3382000, Name: "#1", IsPtr: true}, {Value: 0x1615bf8, IsPtr: true}}},
1171 "/home/maruel/golang/go/src/testing/testing.go",
1172 865),
1173 },
1174 },
1175 },
1176 ID: 8,
1177 First: true,
1178 },
1179 },
1180 },
1181
1182 {
1183 name: "Race",
1184 in: []string{string(internaltest.StaticPanicRaceOutput())},
1185 prefix: "\nGOTRACEBACK=all\n",
1186 want: []*Goroutine{
1187 {
1188 Signature: Signature{
1189 State: "running",
1190 CreatedBy: Stack{
1191 Calls: []Call{
1192 newCall(
1193 "main.panicRace",
1194 Args{},
1195 "/go/src/github.com/maruel/panicparse/cmd/panic/main.go",
1196 153,
1197 ),
1198 newCall(
1199 "main.main",
1200 Args{},
1201 "/go/src/github.com/maruel/panicparse/cmd/panic/main.go",
1202 54,
1203 ),
1204 },
1205 },
1206 Stack: Stack{
1207 Calls: []Call{
1208 newCall(
1209 "main.panicDoRaceRead",
1210 Args{},
1211 "/go/src/github.com/maruel/panicparse/cmd/panic/main.go",
1212 137,
1213 ),
1214 newCall(
1215 "main.panicRace.func2",
1216 Args{},
1217 "/go/src/github.com/maruel/panicparse/cmd/panic/main.go",
1218 154),
1219 },
1220 },
1221 },
1222 ID: 8,
1223 First: true,
1224 RaceAddr: 0xc000014100,
1225 },
1226 {
1227 Signature: Signature{
1228 State: "running",
1229 CreatedBy: Stack{
1230 Calls: []Call{
1231 newCall(
1232 "main.panicRace",
1233 Args{},
1234 "/go/src/github.com/maruel/panicparse/cmd/panic/main.go",
1235 150,
1236 ),
1237 newCall(
1238 "main.main",
1239 Args{},
1240 "/go/src/github.com/maruel/panicparse/cmd/panic/main.go",
1241 54,
1242 ),
1243 },
1244 },
1245 Stack: Stack{
1246 Calls: []Call{
1247 newCall(
1248 "main.panicDoRaceWrite",
1249 Args{},
1250 "/go/src/github.com/maruel/panicparse/cmd/panic/main.go",
1251 132),
1252 newCall(
1253 "main.panicRace.func1",
1254 Args{},
1255 "/go/src/github.com/maruel/panicparse/cmd/panic/main.go",
1256 151),
1257 },
1258 },
1259 },
1260 ID: 7,
1261 RaceWrite: true,
1262 RaceAddr: 0xc000014100,
1263 },
1264 },
1265 },
1266
1267 {
1268 name: "RaceHdr1Err",
1269 in: []string{
1270 string(raceHeaderFooter),
1271 },
1272 prefix: string(raceHeaderFooter),
1273 err: io.EOF,
1274 },
1275
1276 {
1277 name: "RaceHdr2Err",
1278 in: []string{
1279 string(raceHeaderFooter),
1280 "",
1281 },
1282 // TODO(maruel): This is incorrect.
1283 prefix: "",
1284 err: io.EOF,
1285 },
1286
1287 {
1288 name: "RaceHdr3Err",
1289 in: []string{
1290 string(raceHeaderFooter),
1291 string(raceHeader),
1292 },
1293 // TODO(maruel): This is incorrect.
1294 prefix: "",
1295 err: io.EOF,
1296 },
1297
1298 {
1299 name: "RaceHdr4Err",
1300 in: []string{
1301 string(raceHeaderFooter),
1302 string(raceHeader),
1303 "",
1304 },
1305 // TODO(maruel): This is incorrect.
1306 prefix: "",
1307 err: io.EOF,
1308 },
1309 }
1310 for i, line := range data {
1311 line := line
1312 t.Run(fmt.Sprintf("%d-%s", i, line.name), func(t *testing.T) {
1313 t.Parallel()
1314 prefix := bytes.Buffer{}
1315 r := bytes.NewBufferString(strings.Join(line.in, "\n"))
1316 s, suffix, err := ScanSnapshot(r, &prefix, defaultOpts())
1317 compareErr(t, line.err, err)
1318 if line.want == nil {
1319 if s != nil {
1320 t.Fatalf("unexpected %v", s)
1321 }
1322 } else {
1323 if s == nil {
1324 t.Fatalf("expected snapshot")
1325 }
1326 compareGoroutines(t, line.want, s.Goroutines)
1327 }
1328 compareString(t, line.prefix, prefix.String())
1329 rest, err := io.ReadAll(r)
1330 compareErr(t, nil, err)
1331 compareString(t, line.suffix, string(suffix)+string(rest))
1332 })
1333 }
1334 }
1335
1336 func TestScanSnapshotSyntheticTwoSnapshots(t *testing.T) {
1337 t.Parallel()
1338 in := bytes.Buffer{}
1339 in.WriteString("Ya\n")
1340 in.Write(internaltest.PanicOutputs()["simple"])
1341 in.WriteString("Ye\n")
1342 in.Write(internaltest.PanicOutputs()["int"])
1343 in.WriteString("Yo\n")
1344 panicParseDir := getPanicParseDir(t)
1345 ppDir := pathJoin(panicParseDir, "cmd", "panic")
1346
1347 // First stack:
1348 prefix := bytes.Buffer{}
1349 s, suffix, err := ScanSnapshot(&in, &prefix, defaultOpts())
1350 compareErr(t, nil, err)
1351 if !s.guessPaths() {
1352 t.Error("expected success")
1353 }
1354 want := []*Goroutine{
1355 {
1356 Signature: Signature{
1357 State: "running",
1358 Stack: Stack{
1359 Calls: []Call{
1360 newCallLocal(
1361 "main.main",
1362 Args{},
1363 pathJoin(ppDir, "main.go"),
1364 74,
1365 ),
1366 },
1367 },
1368 },
1369 ID: 1,
1370 First: true,
1371 },
1372 }
1373 compareGoroutines(t, want, s.Goroutines)
1374 compareString(t, "Ya\nGOTRACEBACK=all\npanic: simple\n\n", prefix.String())
1375
1376 prefix.Reset()
1377 r := io.MultiReader(bytes.NewReader(suffix), &in)
1378 s, suffix, err = ScanSnapshot(r, &prefix, defaultOpts())
1379 compareErr(t, nil, err)
1380 if !s.guessPaths() {
1381 t.Error("expected success")
1382 }
1383 // This is a change detector on internal/main.go.
1384 want = []*Goroutine{
1385 {
1386 Signature: Signature{
1387 State: "running",
1388 Stack: Stack{
1389 Calls: []Call{
1390 newCallLocal(
1391 "main.panicint",
1392 Args{Values: []Arg{{Value: 42}}},
1393 pathJoin(ppDir, "main.go"),
1394 93,
1395 ),
1396 newCallLocal(
1397 "main.init.func9",
1398 Args{},
1399 pathJoin(ppDir, "main.go"),
1400 315,
1401 ),
1402 newCallLocal(
1403 "main.main",
1404 Args{},
1405 pathJoin(ppDir, "main.go"),
1406 76,
1407 ),
1408 },
1409 },
1410 },
1411 ID: 1,
1412 First: true,
1413 },
1414 }
1415 compareGoroutines(t, want, s.Goroutines)
1416 compareString(t, "Ye\nGOTRACEBACK=all\npanic: 42\n\n", prefix.String())
1417 compareString(t, "Yo\n", string(suffix))
1418 }
1419
1420 func TestSplitPath(t *testing.T) {
1421 t.Parallel()
1422 if p := splitPath(""); p != nil {
1423 t.Fatalf("expected nil, got: %v", p)
1424 }
1425 }
1426
1427 func TestGetGOPATHs(t *testing.T) {
1428 // This test cannot run in parallel.
1429 old := os.Getenv("GOPATH")
1430 defer os.Setenv("GOPATH", old)
1431 os.Setenv("GOPATH", "")
1432 if p := getGOPATHs(); len(p) != 1 {
1433 // It's the home directory + /go.
1434 t.Fatalf("expected only one path: %v", p)
1435 }
1436
1437 root, err := os.MkdirTemp("", "stack")
1438 if err != nil {
1439 t.Fatal(err)
1440 }
1441 defer func() {
1442 if err = os.RemoveAll(root); err != nil {
1443 t.Error(err)
1444 }
1445 }()
1446 os.Setenv("GOPATH", filepath.Join(root, "a")+string(filepath.ListSeparator)+filepath.Join(root, "b")+string(filepath.Separator))
1447 if p := getGOPATHs(); len(p) != 2 {
1448 t.Fatalf("expected two paths: %v", p)
1449 }
1450 }
1451
1452 // TestGomoduleComplex is an integration test that creates a non-trivial tree
1453 // of go modules using the "replace" statement.
1454 func TestGomoduleComplex(t *testing.T) {
1455 // This test cannot run in parallel.
1456 if internaltest.GetGoMinorVersion() < 11 {
1457 t.Skip("requires go module support")
1458 }
1459 old := os.Getenv("GOPATH")
1460 defer os.Setenv("GOPATH", old)
1461 root, err := os.MkdirTemp("", "stack")
1462 if err != nil {
1463 t.Fatal(err)
1464 }
1465 defer func() {
1466 if err = os.RemoveAll(root); err != nil {
1467 t.Error(err)
1468 }
1469 }()
1470
1471 os.Setenv("GOPATH", filepath.Join(root, "go"))
1472 os.Setenv("GO111MODULE", "on")
1473 tree := map[string]string{
1474 "pkg1/go.mod": "module example.com/pkg1\n" +
1475 "require (\n" +
1476 "\texample.com/pkg2 v0.0.1\n" +
1477 "\texample.com/pkg3 v0.0.1\n" +
1478 ")\n" +
1479 "replace example.com/pkg2 => ../pkg2\n" +
1480 // This is kind of a hack to force testing with a package inside GOPATH,
1481 // since this won't normally work by default.
1482 "replace example.com/pkg3 => ../go/src/example.com/pkg3\n",
1483 "pkg1/cmd/main.go": "package main\n" +
1484 "import \"example.com/pkg1/internal\"\n" +
1485 "func main() {\n" +
1486 "\tinternal.CallCallDie()\n" +
1487 "}\n",
1488 "pkg1/internal/int.go": "package internal\n" +
1489 "import \"example.com/pkg2\"\n" +
1490 "func CallCallDie() {\n" +
1491 "\tpkg2.CallDie()\n" +
1492 "}\n",
1493
1494 "pkg2/go.mod": "module example.com/pkg2\n" +
1495 "require (\n" +
1496 "\texample.com/pkg3 v0.0.1\n" +
1497 ")\n" +
1498 // This is kind of a hack to force testing with a package inside GOPATH,
1499 // since this won't normally work by default.
1500 "replace example.com/pkg3 => ../go/src/example.com/pkg3\n",
1501 "pkg2/src2.go": "package pkg2\n" +
1502 "import \"example.com/pkg3\"\n" +
1503 "func CallDie() { pkg3.Die() }\n",
1504
1505 "go/src/example.com/pkg3/go.mod": "module example.com/pkg3\n",
1506 "go/src/example.com/pkg3/src3.go": "package pkg3\n" +
1507 "func Die() { panic(42) }\n",
1508 }
1509 createTree(t, root, tree)
1510
1511 exe := filepath.Join(root, "yo")
1512 if runtime.GOOS == "windows" {
1513 exe += ".exe"
1514 }
1515 if err = internaltest.Compile("./cmd", exe, filepath.Join(root, "pkg1"), true, false); err != nil {
1516 t.Fatal(err)
1517 }
1518
1519 out, err := exec.Command(exe).CombinedOutput()
1520 if err == nil {
1521 t.Error("expected failure")
1522 }
1523 prefix := bytes.Buffer{}
1524 s, suffix, err := ScanSnapshot(bytes.NewReader(out), &prefix, defaultOpts())
1525 compareErr(t, io.EOF, err)
1526 if !s.guessPaths() {
1527 t.Error("expected success")
1528 }
1529 if s == nil {
1530 t.Fatal("expected snapshot")
1531 }
1532 if s.IsRace() {
1533 t.Fatal("unexpected race")
1534 }
1535 compareString(t, "panic: 42\n\n", prefix.String())
1536 compareString(t, "", string(suffix))
1537 wantGOROOT := ""
1538 compareString(t, wantGOROOT, s.RemoteGOROOT)
1539 compareString(t, runtime.GOROOT(), strings.Replace(s.LocalGOROOT, "/", pathSeparator, -1))
1540
1541 rootRemote := root
1542 if runtime.GOOS == "windows" {
1543 // On Windows, we must make the path to be POSIX style.
1544 rootRemote = strings.Replace(root, pathSeparator, "/", -1)
1545 }
1546 rootLocal := rootRemote
1547 if runtime.GOOS == "darwin" {
1548 if ver := internaltest.GetGoMinorVersion(); ver > 0 && ver < 19 {
1549 // On MacOS, $TMPDIR path is a symlink /var -> /private/var.
1550 //
1551 // On versions before go1.19, it was somehow evaluated by exec.Cmd.Run().
1552 // This stopped being true on go1.19. I suspect it is a side-effect of
1553 // https://go.dev/doc/go1.19#os-exec-path
1554 //
1555 // This must NOT be run on Windows otherwise the path will be converted
1556 // to 8.3 format.
1557 if rootRemote, err = filepath.EvalSymlinks(rootLocal); err != nil {
1558 t.Fatal(err)
1559 }
1560 }
1561 }
1562
1563 // This part is a bit tricky. The symlink is evaluated on the left since,
1564 // since it's what is the "remote" path, but it is not on the right since,
1565 // which is the "local" path. This difference only exists on MacOS.
1566 wantGOPATHs := map[string]string{
1567 pathJoin(rootRemote, "go"): pathJoin(rootLocal, "go"),
1568 }
1569 if diff := cmp.Diff(s.RemoteGOPATHs, wantGOPATHs); diff != "" {
1570 t.Fatalf("+want/-got: %s", diff)
1571 }
1572
1573 // Local go module search is on the path with symlink evaluated on MacOS.
1574 // This is kind of confusing because it is the "remote" path.
1575 wantGomods := map[string]string{
1576 pathJoin(rootRemote, "pkg1"): "example.com/pkg1",
1577 pathJoin(rootRemote, "pkg2"): "example.com/pkg2",
1578 }
1579 if diff := cmp.Diff(s.LocalGomods, wantGomods); diff != "" {
1580 t.Fatalf("+want/-got: %s", diff)
1581 }
1582
1583 want := []*Goroutine{
1584 {
1585 Signature: Signature{
1586 State: "running",
1587 Stack: Stack{
1588 Calls: []Call{
1589 {
1590 Func: newFunc("example.com/pkg3.Die"),
1591 Args: Args{Elided: true},
1592 RemoteSrcPath: pathJoin(rootRemote, "go", "src", "example.com", "pkg3", "src3.go"),
1593 Line: 2,
1594 SrcName: "src3.go",
1595 DirSrc: "pkg3/src3.go",
1596 LocalSrcPath: pathJoin(rootLocal, "go", "src", "example.com", "pkg3", "src3.go"),
1597 RelSrcPath: "example.com/pkg3/src3.go",
1598 ImportPath: "example.com/pkg3",
1599 Location: GOPATH,
1600 },
1601 {
1602 Func: newFunc("example.com/pkg2.CallDie"),
1603 Args: Args{Elided: true},
1604 RemoteSrcPath: pathJoin(rootRemote, "pkg2", "src2.go"),
1605 Line: 3,
1606 SrcName: "src2.go",
1607 DirSrc: "pkg2/src2.go",
1608 // Since this was found locally as a go module using the remote
1609 // path, this is correct, even if confusing.
1610 LocalSrcPath: pathJoin(rootRemote, "pkg2", "src2.go"),
1611 RelSrcPath: "src2.go",
1612 ImportPath: "example.com/pkg2",
1613 Location: GoMod,
1614 },
1615 {
1616 Func: newFunc("example.com/pkg1/internal.CallCallDie"),
1617 RemoteSrcPath: pathJoin(rootRemote, "pkg1", "internal", "int.go"),
1618 Line: 2,
1619 SrcName: "int.go",
1620 DirSrc: "internal/int.go",
1621 // Since this was found locally as a go module using the remote
1622 // path, this is correct, even if confusing.
1623 LocalSrcPath: pathJoin(rootRemote, "pkg1", "internal", "int.go"),
1624 RelSrcPath: "internal/int.go",
1625 ImportPath: "example.com/pkg1/internal",
1626 Location: GoMod,
1627 },
1628 {
1629 Func: newFunc("main.main"),
1630 RemoteSrcPath: pathJoin(rootRemote, "pkg1", "cmd", "main.go"),
1631 Line: 4,
1632 SrcName: "main.go",
1633 DirSrc: "cmd/main.go",
1634 // Since this was found locally as a go module using the remote
1635 // path, this is correct, even if confusing.
1636 LocalSrcPath: pathJoin(rootRemote, "pkg1", "cmd", "main.go"),
1637 RelSrcPath: "cmd/main.go",
1638 ImportPath: "example.com/pkg1/cmd",
1639 Location: GoMod,
1640 },
1641 },
1642 },
1643 },
1644 ID: 1,
1645 First: true,
1646 },
1647 }
1648 similarGoroutines(t, want, s.Goroutines)
1649 }
1650
1651 func TestGoRun(t *testing.T) {
1652 t.Parallel()
1653 root, err := os.MkdirTemp("", "stack")
1654 if err != nil {
1655 t.Fatal(err)
1656 }
1657 defer func() {
1658 if err = os.RemoveAll(root); err != nil {
1659 t.Error(err)
1660 }
1661 }()
1662
1663 p := filepath.Join(root, "main.go")
1664 content := "package main\nfunc main() { panic(42) }\n"
1665 if err = os.WriteFile(p, []byte(content), 0600); err != nil {
1666 t.Fatal(err)
1667 }
1668 c := exec.Command("go", "run", p)
1669 out, err := c.CombinedOutput()
1670 if err == nil {
1671 t.Fatal("expected failure")
1672 }
1673 prefix := bytes.Buffer{}
1674 s, suffix, err := ScanSnapshot(bytes.NewReader(out), &prefix, defaultOpts())
1675 compareErr(t, nil, err)
1676 compareString(t, "panic: 42\n\n", prefix.String())
1677 compareString(t, "exit status 2\n", string(suffix))
1678 if s == nil {
1679 t.Fatal("expected snapshot")
1680 }
1681 if runtime.GOOS == "windows" {
1682 // On Windows, we must make the path to be POSIX style.
1683 p = strings.Replace(p, pathSeparator, "/", -1)
1684 }
1685
1686 want := []*Goroutine{
1687 {
1688 Signature: Signature{
1689 State: "running",
1690 Stack: Stack{
1691 Calls: []Call{
1692 {
1693 Func: Func{
1694 Complete: "main.main",
1695 ImportPath: "main",
1696 DirName: "main",
1697 Name: "main",
1698 IsExported: true,
1699 IsPkgMain: true,
1700 },
1701 RemoteSrcPath: p,
1702 Line: 2,
1703 SrcName: "main.go",
1704 DirSrc: path.Base(path.Dir(p)) + "/main.go",
1705 ImportPath: "main",
1706 Location: LocationUnknown,
1707 },
1708 },
1709 },
1710 },
1711 ID: 1,
1712 First: true,
1713 },
1714 }
1715 similarGoroutines(t, want, s.Goroutines)
1716
1717 if !s.guessPaths() {
1718 t.Error("expected success")
1719 }
1720 want[0].Stack.Calls[0].LocalSrcPath = p
1721 want[0].Stack.Calls[0].RelSrcPath = "main.go"
1722 // This is not technically true, when using go run there's no need for a
1723 // go.mod file, but I don't think it's worth handling specifically.
1724 want[0].Stack.Calls[0].Location = GoMod
1725 similarGoroutines(t, want, s.Goroutines)
1726 }
1727
1728 // TestPanic runs github.com/maruel/panicparse/v2/cmd/panic with every
1729 // supported panic modes.
1730 func TestPanic(t *testing.T) {
1731 t.Parallel()
1732 cmds := internaltest.PanicOutputs()
1733 want := map[string]int{
1734 "chan_receive": 2,
1735 "chan_send": 2,
1736 "goroutine_1": 2,
1737 "goroutine_dedupe_pointers": 101,
1738 "goroutine_100": 101,
1739 }
1740
1741 panicParseDir := getPanicParseDir(t)
1742 ppDir := pathJoin(panicParseDir, "cmd", "panic")
1743
1744 // Test runtime code. For those not in "custom", just assert that they
1745 // succeed.
1746 custom := map[string]func(*testing.T, *Snapshot, *bytes.Buffer, string){
1747 "args_elided": testPanicArgsElided,
1748 "mismatched": testPanicMismatched,
1749 "race": testPanicRace,
1750 "str": testPanicStr,
1751 "utf8": testPanicUTF8,
1752 }
1753 // Make sure all custom handlers are showing up in cmds.
1754 for n := range custom {
1755 if _, ok := cmds[n]; !ok {
1756 if n == "race" {
1757 t.Skip("race is unsupported")
1758 }
1759 t.Fatalf("untested mode %q:\n%v", n, cmds[n])
1760 }
1761 }
1762
1763 for cmd, data := range cmds {
1764 cmd := cmd
1765 data := data
1766 t.Run(cmd, func(t *testing.T) {
1767 t.Parallel()
1768 prefix := bytes.Buffer{}
1769 s, suffix, err := ScanSnapshot(bytes.NewReader(data), &prefix, defaultOpts())
1770 if err != nil && err != io.EOF {
1771 t.Fatal(err)
1772 }
1773 if s == nil {
1774 t.Fatal("context is nil")
1775 }
1776 if !s.guessPaths() {
1777 t.Fatal("expected GuessPaths to work")
1778 }
1779 if f := custom[cmd]; f != nil {
1780 f(t, s, &prefix, ppDir)
1781 return
1782 }
1783 e := want[cmd]
1784 if e == 0 {
1785 e = 1
1786 }
1787 if got := len(s.Goroutines); got != e {
1788 t.Fatalf("unexpected Goroutines; want %d, got %d", e, got)
1789 }
1790 compareString(t, "", string(suffix))
1791 })
1792 }
1793 }
1794
1795 func testPanicArgsElided(t *testing.T, s *Snapshot, b *bytes.Buffer, ppDir string) {
1796 if s.RemoteGOROOT != "" {
1797 t.Fatalf("RemoteGOROOT is %q", s.RemoteGOROOT)
1798 }
1799 if b.String() != "GOTRACEBACK=all\npanic: 1\n\n" {
1800 t.Fatalf("output: %q", b.String())
1801 }
1802 want := []*Goroutine{
1803 {
1804 Signature: Signature{
1805 State: "running",
1806 Stack: Stack{
1807 Calls: []Call{
1808 newCallLocal(
1809 "main.panicArgsElided",
1810 Args{
1811 Values: []Arg{{Value: 1}, {Value: 2}, {Value: 3}, {Value: 4}, {Value: 5}, {Value: 6}, {Value: 7}, {Value: 8}, {Value: 9}, {Value: 10}},
1812 Elided: true,
1813 },
1814 pathJoin(ppDir, "main.go"),
1815 58),
1816 newCallLocal("main.init.func1", Args{}, pathJoin(ppDir, "main.go"), 134),
1817 newCallLocal("main.main", Args{}, pathJoin(ppDir, "main.go"), 340),
1818 },
1819 },
1820 },
1821 ID: 1,
1822 First: true,
1823 },
1824 }
1825 similarGoroutines(t, want, s.Goroutines)
1826 }
1827
1828 func testPanicMismatched(t *testing.T, s *Snapshot, b *bytes.Buffer, ppDir string) {
1829 if s.RemoteGOROOT != "" {
1830 t.Fatalf("RemoteGOROOT is %q", s.RemoteGOROOT)
1831 }
1832 if b.String() != "GOTRACEBACK=all\npanic: 42\n\n" {
1833 t.Fatalf("output: %q", b.String())
1834 }
1835 ver := "/v2"
1836 if !internaltest.IsUsingModules() {
1837 ver = ""
1838 }
1839 want := []*Goroutine{
1840 {
1841 Signature: Signature{
1842 State: "running",
1843 Stack: Stack{
1844 Calls: []Call{
1845 newCallLocal(
1846 // This is important to note here that the Go runtime prints out
1847 // the package path, and not the package name.
1848 //
1849 // Here the package name is "correct". There is no way to deduce
1850 // this from the stack trace.
1851 "github.com/maruel/panicparse"+ver+"/cmd/panic/internal/incorrect.Panic",
1852 Args{},
1853 pathJoin(ppDir, "internal", "incorrect", "correct.go"),
1854 7),
1855 newCallLocal("main.init.func20", Args{}, pathJoin(ppDir, "main.go"), 314),
1856 newCallLocal("main.main", Args{}, pathJoin(ppDir, "main.go"), 340),
1857 },
1858 },
1859 },
1860 ID: 1,
1861 First: true,
1862 },
1863 }
1864 similarGoroutines(t, want, s.Goroutines)
1865 }
1866
1867 func testPanicRace(t *testing.T, s *Snapshot, b *bytes.Buffer, ppDir string) {
1868 if s.RemoteGOROOT != "" {
1869 t.Fatalf("RemoteGOROOT is %q", s.RemoteGOROOT)
1870 }
1871 if b.String() != "GOTRACEBACK=all\n" {
1872 t.Fatalf("output: %q", b.String())
1873 }
1874 want := []*Goroutine{
1875 {
1876 Signature: Signature{
1877 State: "running",
1878 CreatedBy: Stack{
1879 Calls: []Call{
1880 newCallLocal(
1881 "main.panicRace",
1882 Args{},
1883 pathJoin(ppDir, "main.go"),
1884 151,
1885 ),
1886 newCallLocal(
1887 "main.main",
1888 Args{},
1889 pathJoin(ppDir, "main.go"),
1890 76,
1891 ),
1892 },
1893 },
1894 Stack: Stack{
1895 Calls: []Call{
1896 newCallLocal(
1897 "main.panicDoRaceRead",
1898 Args{},
1899 pathJoin(ppDir, "main.go"),
1900 150),
1901 newCallLocal(
1902 "main.panicRace.func2",
1903 Args{},
1904 pathJoin(ppDir, "main.go"),
1905 135),
1906 },
1907 },
1908 },
1909 RaceAddr: pointer,
1910 },
1911 {
1912 Signature: Signature{
1913 State: "running",
1914 CreatedBy: Stack{
1915 Calls: []Call{
1916 newCallLocal(
1917 "main.panicRace",
1918 Args{},
1919 pathJoin(ppDir, "main.go"),
1920 151,
1921 ),
1922 newCallLocal(
1923 "main.main",
1924 Args{},
1925 pathJoin(ppDir, "main.go"),
1926 76,
1927 ),
1928 },
1929 },
1930 Stack: Stack{
1931 Calls: []Call{
1932 newCallLocal(
1933 "main.panicDoRaceWrite",
1934 Args{},
1935 pathJoin(ppDir, "main.go"),
1936 145),
1937 newCallLocal(
1938 "main.panicRace.func1",
1939 Args{},
1940 pathJoin(ppDir, "main.go"),
1941 132),
1942 },
1943 },
1944 },
1945 RaceWrite: true,
1946 RaceAddr: pointer,
1947 },
1948 }
1949 // IDs are not deterministic, so zap them too but take them for the race
1950 // detector first.
1951 for i, g := range s.Goroutines {
1952 g.ID = i + 1
1953 if g.RaceAddr > 4*1024*1024 {
1954 g.RaceAddr = pointer
1955 }
1956 }
1957 // Sometimes the read is detected first.
1958 if s.Goroutines[0].RaceWrite {
1959 want[0], want[1] = want[1], want[0]
1960 }
1961 // These fields are order-dependent, so set them last.
1962 want[0].ID = 1
1963 want[1].ID = 2
1964 want[0].First = true
1965 want[1].First = false
1966 similarGoroutines(t, want, s.Goroutines)
1967 }
1968
1969 func testPanicStr(t *testing.T, s *Snapshot, b *bytes.Buffer, ppDir string) {
1970 if s.RemoteGOROOT != "" {
1971 t.Fatalf("RemoteGOROOT is %q", s.RemoteGOROOT)
1972 }
1973 if b.String() != "GOTRACEBACK=all\npanic: allo\n\n" {
1974 t.Fatalf("output: %q", b.String())
1975 }
1976 want := []*Goroutine{
1977 {
1978 Signature: Signature{
1979 State: "running",
1980 Stack: Stack{
1981 Calls: []Call{
1982 newCallLocal(
1983 "main.panicstr",
1984 Args{Values: []Arg{{IsAggregate: true, Fields: Args{
1985 Values: []Arg{{Value: 0x123456, IsPtr: true}, {Value: 4}},
1986 }}}},
1987 pathJoin(ppDir, "main.go"),
1988 50),
1989 newCallLocal("main.init.func19", Args{}, pathJoin(ppDir, "main.go"), 307),
1990 newCallLocal("main.main", Args{}, pathJoin(ppDir, "main.go"), 340),
1991 },
1992 },
1993 },
1994 ID: 1,
1995 First: true,
1996 },
1997 }
1998 similarGoroutines(t, want, s.Goroutines)
1999 }
2000
2001 func testPanicUTF8(t *testing.T, s *Snapshot, b *bytes.Buffer, ppDir string) {
2002 if s.RemoteGOROOT != "" {
2003 t.Fatalf("RemoteGOROOT is %q", s.RemoteGOROOT)
2004 }
2005 if b.String() != "GOTRACEBACK=all\npanic: 42\n\n" {
2006 t.Fatalf("output: %q", b.String())
2007 }
2008 ver := "/v2"
2009 if !internaltest.IsUsingModules() {
2010 ver = ""
2011 }
2012 want := []*Goroutine{
2013 {
2014 Signature: Signature{
2015 State: "running",
2016 Stack: Stack{
2017 Calls: []Call{
2018 newCallLocal(
2019 // This is important to note here the inconsistency in the Go
2020 // runtime stack generator. The path is escaped, but symbols are
2021 // not.
2022 "github.com/maruel/panicparse"+ver+"/cmd/panic/internal/utf8.(*Strùct).Pànic",
2023 Args{Values: []Arg{{Value: 1, IsInaccurate: true}}},
2024 // See TestCallUTF8 in stack_test.go for exercising the methods on
2025 // Call in this situation.
2026 pathJoin(ppDir, "internal", "utf8", "utf8.go"),
2027 10),
2028 newCallLocal("main.init.func21", Args{}, pathJoin(ppDir, "main.go"), 322),
2029 newCallLocal("main.main", Args{}, pathJoin(ppDir, "main.go"), 340),
2030 },
2031 },
2032 },
2033 ID: 1,
2034 First: true,
2035 },
2036 }
2037 similarGoroutines(t, want, s.Goroutines)
2038 }
2039
2040 // TestPanicweb implements the parsing of panicweb output.
2041 //
2042 // panicweb is a separate binary from the rest of panic because importing the
2043 // "net" package causes a background thread to be started, which breaks "panic
2044 // asleep".
2045 func TestPanicweb(t *testing.T) {
2046 t.Parallel()
2047 if runtime.GOARCH == "ppc64" || runtime.GOARCH == "ppc64le" {
2048 t.Skip("https://github.com/maruel/panicparse/issues/66")
2049 }
2050 prefix := bytes.Buffer{}
2051 s, suffix, err := ScanSnapshot(bytes.NewReader(internaltest.PanicwebOutput()), &prefix, defaultOpts())
2052 if err != io.EOF {
2053 t.Fatal(err)
2054 }
2055 if s == nil {
2056 t.Fatal("snapshot is nil")
2057 }
2058 compareString(t, "panic: Here's a snapshot of a normal web server.\n\n", prefix.String())
2059 compareString(t, "", string(suffix))
2060 if s.RemoteGOROOT != "" {
2061 t.Fatalf("unexpected RemoteGOROOT: %q", s.RemoteGOROOT)
2062 }
2063 if !s.guessPaths() {
2064 t.Error("expected success")
2065 }
2066 if s.RemoteGOROOT != strings.Replace(runtime.GOROOT(), "\\", "/", -1) {
2067 t.Fatalf("RemoteGOROOT mismatch; want:%q got:%q", runtime.GOROOT(), s.RemoteGOROOT)
2068 }
2069 if got := len(s.Goroutines); got < 30 {
2070 t.Fatalf("unexpected Goroutines; want at least 30, got %d", got)
2071 }
2072 // The goal here is not to find the exact match since it'll change across
2073 // OSes and Go versions, but to find some of the expected signatures.
2074 pwebDir := pathJoin(getPanicParseDir(t), "cmd", "panicweb")
2075 // Reduce the goroutines and categorize the signatures.
2076 var types []panicwebSignatureType
2077 for _, b := range s.Aggregate(AnyPointer).Buckets {
2078 types = append(types, identifyPanicwebSignature(t, b, pwebDir))
2079 }
2080 // Count the expected types.
2081 if v := pstCount(types, pstUnknown); v != 0 {
2082 t.Fatalf("found %d unknown signatures", v)
2083 }
2084 if v := pstCount(types, pstMain); v != 1 {
2085 t.Fatalf("found %d pstMain signatures", v)
2086 }
2087 if v := pstCount(types, pstURL1handler); v != 1 && v != 2 {
2088 t.Fatalf("found %d URL1Handler signatures", v)
2089 }
2090 if v := pstCount(types, pstURL2handler); v != 1 && v != 2 {
2091 t.Fatalf("found %d URL2Handler signatures", v)
2092 }
2093 if v := pstCount(types, pstClient); v == 0 {
2094 t.Fatalf("found %d client signatures", v)
2095 }
2096 if v := pstCount(types, pstServe); v != 1 {
2097 t.Fatalf("found %d serve signatures", v)
2098 }
2099 if v := pstCount(types, pstColorable); v != 1 {
2100 t.Fatalf("found %d colorable signatures", v)
2101 }
2102 if v := pstCount(types, pstStdlib); v < 3 {
2103 t.Fatalf("found %d stdlib signatures", v)
2104 }
2105 }
2106
2107 func TestIsGomodule(t *testing.T) {
2108 t.Parallel()
2109 pwd, err := os.Getwd()
2110 if err != nil {
2111 t.Fatal(err)
2112 }
2113 // Our internal functions work with '/' as path separator.
2114 parts := splitPath(strings.Replace(pwd, "\\", "/", -1))
2115 gmc := gomodCache{}
2116 root, importPath := gmc.isGoModule(parts)
2117 if want := strings.Join(parts[:len(parts)-1], "/"); want != root {
2118 t.Errorf("want: %q, got: %q", want, root)
2119 }
2120 if want := "github.com/maruel/panicparse/v2"; want != importPath {
2121 t.Errorf("want: %q, got: %q", want, importPath)
2122 }
2123 got := reModule.FindStringSubmatch("foo\r\nmodule bar\r\nbaz")
2124 if diff := cmp.Diff([]string{"module bar\r", "bar"}, got); diff != "" {
2125 t.Fatalf("-want, +got:\n%s", diff)
2126 }
2127 }
2128
2129 func TestAtou(t *testing.T) {
2130 t.Parallel()
2131 if i, b := atou([]byte("a")); i != 0 || b {
2132 t.Error("oops")
2133 }
2134 }
2135
2136 func TestTrimLeftSpace(t *testing.T) {
2137 t.Parallel()
2138 if trimLeftSpace(nil) != nil {
2139 t.Error("oops")
2140 }
2141 }
2142
2143 func TestTrimCurlyBrackets(t *testing.T) {
2144 t.Parallel()
2145 data := []struct {
2146 input []byte
2147 want []byte
2148 wantOpened, wantClosed int
2149 }{
2150 {nil, nil, 0, 0},
2151 {[]byte(""), []byte(""), 0, 0},
2152 {[]byte("a"), []byte("a"), 0, 0},
2153 {[]byte("{a"), []byte("a"), 1, 0},
2154 {[]byte("{{a"), []byte("a"), 2, 0},
2155 {[]byte("{{a}}"), []byte("a"), 2, 2},
2156 {[]byte("{a}}"), []byte("a"), 1, 2},
2157 {[]byte("a}}"), []byte("a"), 0, 2},
2158 {[]byte("{}"), []byte(""), 1, 1},
2159 {[]byte("{{}}"), []byte(""), 2, 2},
2160 // Not expected in practice.
2161 {[]byte("}{"), []byte("}{"), 0, 0},
2162 {[]byte("{{}}a{{}}"), []byte("}}a{{"), 2, 2},
2163 }
2164 for i, line := range data {
2165 line := line
2166 t.Run(fmt.Sprintf("%d-%s", i, line.input), func(t *testing.T) {
2167 gotOpened, got, gotClosed := trimCurlyBrackets(line.input)
2168 if !bytes.Equal(line.want, got) {
2169 t.Errorf("want %s, got %s", line.want, got)
2170 }
2171 equiv := bytes.TrimRight(bytes.TrimLeft(line.input, "{"), "}")
2172 if !bytes.Equal(line.want, equiv) {
2173 t.Errorf("want %s, got %s", line.want, got)
2174 }
2175 if line.wantOpened != gotOpened {
2176 t.Errorf("want %d opening curly brackets, got %d", line.wantOpened, gotOpened)
2177 }
2178 if line.wantClosed != gotClosed {
2179 t.Errorf("want %d closing curly brackets, got %d", line.wantClosed, gotClosed)
2180 }
2181 })
2182 }
2183 }
2184
2185 func BenchmarkScanSnapshot_Guess(b *testing.B) {
2186 b.ReportAllocs()
2187 data := internaltest.StaticPanicwebOutput()
2188 opts := defaultOpts()
2189 b.ResetTimer()
2190 for i := 0; i < b.N; i++ {
2191 s, _, err := ScanSnapshot(bytes.NewReader(data), io.Discard, opts)
2192 if err != io.EOF {
2193 b.Fatal(err)
2194 }
2195 if s == nil {
2196 b.Fatal("missing context")
2197 }
2198 }
2199 }
2200
2201 func BenchmarkScanSnapshot_NoGuess(b *testing.B) {
2202 b.ReportAllocs()
2203 data := internaltest.StaticPanicwebOutput()
2204 opts := defaultOpts()
2205 b.ResetTimer()
2206 for i := 0; i < b.N; i++ {
2207 s, _, err := ScanSnapshot(bytes.NewReader(data), io.Discard, opts)
2208 if err != io.EOF {
2209 b.Fatal(err)
2210 }
2211 if s == nil {
2212 b.Fatal("missing context")
2213 }
2214 }
2215 }
2216
2217 func BenchmarkScanSnapshot_Passthru(b *testing.B) {
2218 b.ReportAllocs()
2219 buf := make([]byte, b.N)
2220 for i := range buf {
2221 buf[i] = 'i'
2222 if i%16 == 0 {
2223 buf[i] = '\n'
2224 }
2225 }
2226 prefix := bytes.Buffer{}
2227 prefix.Grow(len(buf))
2228 r := bytes.NewReader(buf)
2229 opts := defaultOpts()
2230 b.ResetTimer()
2231 s, suffix, err := ScanSnapshot(r, &prefix, opts)
2232 if err != io.EOF {
2233 b.Fatal(err)
2234 }
2235 if s != nil {
2236 b.Fatalf("unexpected %v", s)
2237 }
2238 b.StopTimer()
2239 if !bytes.Equal(prefix.Bytes(), buf) {
2240 b.Fatal("unexpected prefix")
2241 }
2242 if len(suffix) != 0 {
2243 b.Fatal("unexpected suffix")
2244 }
2245 }
2246
2247 //
2248
2249 type panicwebSignatureType int
2250
2251 const (
2252 pstUnknown panicwebSignatureType = iota
2253 pstMain
2254 pstURL1handler
2255 pstURL2handler
2256 pstClient
2257 pstServe
2258 pstColorable
2259 pstStdlib
2260 )
2261
2262 func pstCount(s []panicwebSignatureType, t panicwebSignatureType) int {
2263 i := 0
2264 for _, v := range s {
2265 if v == t {
2266 i++
2267 }
2268 }
2269 return i
2270 }
2271
2272 // identifyPanicwebSignature tries to assign one of the predefined signature to
2273 // the bucket provided.
2274 //
2275 // One challenge is that the path will be different depending if this test is
2276 // run within GOPATH or outside.
2277 func identifyPanicwebSignature(t *testing.T, b *Bucket, pwebDir string) panicwebSignatureType {
2278 ver := ""
2279 if !isInGOPATH {
2280 ver = "/v2"
2281 }
2282
2283 // The first bucket (the one calling panic()) is deterministic.
2284 if b.First {
2285 if len(b.IDs) != 1 {
2286 t.Fatal("first bucket is not correct")
2287 return pstUnknown
2288 }
2289 want := Signature{
2290 State: "running",
2291 Stack: Stack{
2292 Calls: []Call{
2293 newCallLocal("main.main", Args{}, pathJoin(pwebDir, "main.go"), 80),
2294 },
2295 },
2296 }
2297 similarSignatures(t, &want, &b.Signature)
2298 return pstMain
2299 }
2300
2301 // We should find exactly 10 sleeping routines in the URL1Handler handler
2302 // signature and 3 in URL2Handler.
2303 if s := b.Stack.Calls[0].Func.Name; s == "URL1Handler" || s == "URL2Handler" {
2304 if b.State != "chan receive" {
2305 t.Fatalf("suspicious: %#v", b)
2306 return pstUnknown
2307 }
2308 if b.Stack.Calls[0].ImportPath != "github.com/maruel/panicparse"+ver+"/cmd/panicweb/internal" {
2309 t.Fatalf("suspicious: %q\n%#v", b.Stack.Calls[0].ImportPath, b)
2310 return pstUnknown
2311 }
2312 if b.Stack.Calls[0].SrcName != "internal.go" {
2313 t.Fatalf("suspicious: %#v", b)
2314 return pstUnknown
2315 }
2316 if b.CreatedBy.Calls[0].SrcName != "server.go" {
2317 t.Fatalf("suspicious: %#v", b)
2318 return pstUnknown
2319 }
2320 if b.CreatedBy.Calls[0].ImportPath != "net/http" {
2321 t.Fatalf("suspicious: %#v", b)
2322 return pstUnknown
2323 }
2324 if b.CreatedBy.Calls[0].Func.Name != "(*Server).Serve" {
2325 t.Fatalf("suspicious: %#v", b)
2326 return pstUnknown
2327 }
2328 if s == "URL1Handler" {
2329 return pstURL1handler
2330 }
2331 return pstURL2handler
2332 }
2333
2334 // Find the client goroutine signatures. For the client, it is likely that
2335 // they haven't all bucketed perfectly.
2336 if b.CreatedBy.Calls[0].ImportPath == "github.com/maruel/panicparse"+ver+"/cmd/panicweb/internal" && b.CreatedBy.Calls[0].Func.Name == "GetAsync" {
2337 // TODO(maruel): More checks.
2338 return pstClient
2339 }
2340
2341 // Now find the two goroutine started by main.
2342 if b.CreatedBy.Calls[0].ImportPath == "github.com/maruel/panicparse"+ver+"/cmd/panicweb" && b.CreatedBy.Calls[0].Func.ImportPath == "main" && b.CreatedBy.Calls[0].Func.Name == "main" {
2343 if b.State == "IO wait" {
2344 return pstServe
2345 }
2346 if b.State == "chan receive" {
2347 // Warning: This is brittle and will fail whenever go-colorable is
2348 // updated so only check the string minimum here.
2349 if !b.Signature.Locked {
2350 t.Fatal("expected Locked")
2351 }
2352 // This is a change detector on internal/main.go.
2353 want := Stack{Calls: []Call{newCallLocal("main.main in goroutine 1", Args{}, pathJoin(pwebDir, "main.go"), 145)}}
2354 compareStacks(t, &b.Signature.CreatedBy, &want)
2355 for i := range b.Signature.Stack.Calls {
2356 if strings.HasPrefix(b.Signature.Stack.Calls[i].ImportPath, "github.com/mattn/go-colorable") {
2357 return pstColorable
2358 }
2359 }
2360 t.Fatalf("failed to find go-colorable\n%# v", b.Signature.Stack.Calls)
2361 }
2362 // That's the unix.Nanosleep() or windows.SleepEx() call.
2363 if b.State == "syscall" {
2364 {
2365 want := Stack{
2366 Calls: []Call{
2367 newCallLocal("main.main in goroutine 1", Args{}, pathJoin(pwebDir, "main.go"), 63),
2368 },
2369 }
2370 zapStacks(t, &want, &b.CreatedBy)
2371 compareStacks(t, &want, &b.CreatedBy)
2372 }
2373 if l := len(b.IDs); l != 1 {
2374 t.Fatalf("expected 1 goroutine for the signature, got %d", l)
2375 }
2376 if runtime.GOOS == "windows" {
2377 if got, want := len(b.Stack.Calls), 4; got != want {
2378 t.Fatalf("expected %d calls, got %d", want, got)
2379 }
2380 if s := b.Stack.Calls[0].RelSrcPath; s != "runtime/syscall_windows.go" {
2381 t.Fatalf("expected %q file, got %q", "runtime/syscall_windows.go", s)
2382 }
2383 } else {
2384 if l := len(b.Stack.Calls); l != 4 {
2385 t.Fatalf("expected %d calls, got %d", 4, l)
2386 }
2387 // The first item shall be an assembly file independent of the OS on Go
2388 // < 1.19.
2389 s := b.Stack.Calls[0].RelSrcPath
2390 if ver := internaltest.GetGoMinorVersion(); ver > 0 && ver < 19 {
2391 if !strings.HasSuffix(s, ".s") {
2392 t.Fatalf("expected assembly file, got %q", s)
2393 }
2394 } else if !strings.HasPrefix(s, "syscall") && !strings.HasSuffix(s, ".go") {
2395 t.Fatalf("expected syscall go file, got %q", s)
2396 }
2397 }
2398 // Process the golang.org/x/sys call specifically.
2399 callIdx := 1
2400 path := "golang.org/x/sys/unix"
2401 fn := "Nanosleep"
2402 mainOS := "main_unix.go"
2403 prefix := "golang.org/x/sys@"
2404 expectVersion := true
2405 usingModules := internaltest.IsUsingModules()
2406 if !usingModules {
2407 // Assert that there's no version by including the trailing /.
2408 prefix = "golang.org/x/sys/"
2409 expectVersion = false
2410 }
2411 if runtime.GOOS == "windows" {
2412 // This changes across Go version, this check is super fragile.
2413 callIdx = 0
2414 path = "syscall"
2415 fn = "Syscall"
2416 mainOS = "main_windows.go"
2417 prefix = "runtime/syscall_windows.go"
2418 expectVersion = false
2419 }
2420 if b.Stack.Calls[callIdx].Func.ImportPath != path || b.Stack.Calls[callIdx].Func.Name != fn {
2421 t.Fatalf("expected %q & %q, got %#v", path, fn, b.Stack.Calls[callIdx].Func)
2422 }
2423 if !strings.HasPrefix(b.Stack.Calls[callIdx].RelSrcPath, prefix) {
2424 t.Fatalf("expected %q, got %q", prefix, b.Stack.Calls[callIdx].RelSrcPath)
2425 }
2426 if expectVersion {
2427 // Assert that it's using v0.1.0 format.
2428 ver := strings.SplitN(b.Stack.Calls[callIdx].RelSrcPath[len(prefix):], "/", 2)[0]
2429 re := regexp.MustCompile(`^v\d+\.\d+\.\d+$`)
2430 if !re.MatchString(ver) {
2431 t.Fatalf("unexpected version string %q", ver)
2432 }
2433 }
2434 {
2435 want := []Call{
2436 newCallLocal("main.sysHang", Args{}, pathJoin(pwebDir, mainOS), 12),
2437 newCallLocal(
2438 "main.main.func3",
2439 Args{},
2440 pathJoin(pwebDir, "main.go"),
2441 65),
2442 }
2443 got := b.Stack.Calls[callIdx+1:]
2444 if ver := internaltest.GetGoMinorVersion(); (ver > 0 && ver < 18 && !is64Bit) || runtime.GOOS == "windows" {
2445 // TODO(maruel): Fix check on Windows.
2446 // On go1.17 on 32 bits this is failing but not on go1.18, so only
2447 // skip in that case.
2448 t.Log("skipping some checks on <go1.18 on 32 bits")
2449 } else {
2450 for i := range want {
2451 zapCalls(t, &want[i], &got[i])
2452 }
2453 if diff := cmp.Diff(want, got); diff != "" {
2454 t.Fatalf("rest of stack mismatch (-want +got):\n%s", diff)
2455 }
2456 }
2457 }
2458 return pstStdlib
2459 }
2460 t.Fatalf("suspicious: %# v", b)
2461 return pstUnknown
2462 }
2463
2464 // The rest should all be created with internal threads.
2465 if b.CreatedBy.Calls[0].Location == Stdlib {
2466 return pstStdlib
2467 }
2468
2469 // On older Go version, there's often an assembly stack in asm_amd64.s.
2470 if b.CreatedBy.Calls[0].Func.Complete == "" {
2471 if len(b.Stack.Calls) == 1 && b.Stack.Calls[0].Func.Complete == "runtime.goexit" {
2472 return pstStdlib
2473 }
2474 }
2475 t.Logf("CreatedBy import: %s", b.CreatedBy.Calls[0].ImportPath)
2476 t.Logf("CreatedBy:\n%#v", b.CreatedBy)
2477 t.Fatalf("unexpected thread started by non-stdlib:\n%#v", b.Stack.Calls)
2478 return pstUnknown
2479 }
2480
2481 //
2482
2483 func defaultOpts() *Opts {
2484 o := DefaultOpts()
2485 o.GuessPaths = false
2486 o.AnalyzeSources = false
2487 return o
2488 }
2489
2490 // getPanicParseDir returns the path to the root directory of panicparse
2491 // package, using "/" as path separator.
2492 func getPanicParseDir(t *testing.T) string {
2493 // We assume that the working directory is the directory containing this
2494 // source. In Go test framework, this normally holds true. If this ever
2495 // becomes false, let's fix this.
2496 thisDir, err := os.Getwd()
2497 if err != nil {
2498 t.Fatal(err)
2499 }
2500 // "/" is used even on Windows in the stack trace, return in this format to
2501 // simply our life.
2502 return strings.Replace(filepath.Dir(thisDir), "\\", "/", -1)
2503 }
2504
2505 func createTree(t *testing.T, root string, tree map[string]string) {
2506 for path, content := range tree {
2507 p := filepath.Join(root, strings.Replace(path, "/", pathSeparator, -1))
2508 b := filepath.Dir(p)
2509 if err := os.MkdirAll(b, 0700); err != nil {
2510 t.Fatal(err)
2511 }
2512 if err := os.WriteFile(p, []byte(content), 0600); err != nil {
2513 t.Fatal(err)
2514 }
2515 }
2516 }