forked from google/syzkaller
-
Notifications
You must be signed in to change notification settings - Fork 1
/
report.go
643 lines (598 loc) · 17.1 KB
/
report.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
// Copyright 2016 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
// Package report contains functions that process kernel output,
// detect/extract crash messages, symbolize them, etc.
package report
import (
"bufio"
"bytes"
"fmt"
"regexp"
"strings"
"github.com/google/syzkaller/pkg/mgrconfig"
"github.com/google/syzkaller/sys/targets"
)
type Reporter interface {
// ContainsCrash searches kernel console output for oops messages.
ContainsCrash(output []byte) bool
// Parse extracts information about oops from console output.
// Returns nil if no oops found.
Parse(output []byte) *Report
// Symbolize symbolizes rep.Report and fills in Maintainers.
Symbolize(rep *Report) error
}
type Report struct {
// Title contains a representative description of the first oops.
Title string
// Bug type (e.g. hang, memory leak, etc).
Type Type
// The indicative function name.
Frame string
// Report contains whole oops text.
Report []byte
// Output contains whole raw console output as passed to Reporter.Parse.
Output []byte
// StartPos/EndPos denote region of output with oops message(s).
StartPos int
EndPos int
// SkipPos is position in output where parsing for the next report should start.
SkipPos int
// Suppressed indicates whether the report should not be reported to user.
Suppressed bool
// Corrupted indicates whether the report is truncated of corrupted in some other way.
Corrupted bool
// CorruptedReason contains reason why the report is marked as corrupted.
CorruptedReason string
// Maintainers is list of maintainer emails (filled in by Symbolize).
Maintainers []string
// guiltyFile is the source file that we think is to blame for the crash (filled in by Symbolize).
guiltyFile string
// reportPrefixLen is length of additional prefix lines that we added before actual crash report.
reportPrefixLen int
}
type Type int
const (
Unknown Type = iota
Hang
MemoryLeak
DataRace
UnexpectedReboot
)
func (t Type) String() string {
switch t {
case Unknown:
return "UNKNOWN"
case Hang:
return "HANG"
case MemoryLeak:
return "LEAK"
case DataRace:
return "DATARACE"
case UnexpectedReboot:
return "REBOOT"
default:
panic("unknown report type")
}
}
// NewReporter creates reporter for the specified OS/Type.
func NewReporter(cfg *mgrconfig.Config) (Reporter, error) {
typ := cfg.TargetOS
if cfg.Type == "gvisor" {
typ = cfg.Type
}
ctor := ctors[typ]
if ctor == nil {
return nil, fmt.Errorf("unknown OS: %v", typ)
}
ignores, err := compileRegexps(cfg.Ignores)
if err != nil {
return nil, err
}
target := targets.Get(cfg.TargetOS, cfg.TargetArch)
if target == nil && typ != "gvisor" {
return nil, fmt.Errorf("unknown target %v/%v", cfg.TargetOS, cfg.TargetArch)
}
config := &config{
target: target,
kernelSrc: cfg.KernelSrc,
kernelBuildSrc: cfg.KernelBuildSrc,
kernelObj: cfg.KernelObj,
ignores: ignores,
}
rep, suppressions, err := ctor(config)
if err != nil {
return nil, err
}
supps, err := compileRegexps(append(suppressions, cfg.Suppressions...))
if err != nil {
return nil, err
}
return &reporterWrapper{rep, supps, typ}, nil
}
const (
VMDiagnosisStart = "\nVM DIAGNOSIS:\n"
unexpectedKernelReboot = "unexpected kernel reboot"
memoryLeakPrefix = "memory leak in "
dataRacePrefix = "KCSAN: data-race"
corruptedNoFrames = "extracted no frames"
)
var ctors = map[string]fn{
"akaros": ctorAkaros,
"linux": ctorLinux,
"gvisor": ctorGvisor,
"freebsd": ctorFreebsd,
"netbsd": ctorNetbsd,
"openbsd": ctorOpenbsd,
"fuchsia": ctorFuchsia,
"windows": ctorStub,
}
type config struct {
target *targets.Target
kernelSrc string
kernelBuildSrc string
kernelObj string
ignores []*regexp.Regexp
}
type fn func(cfg *config) (Reporter, []string, error)
func compileRegexps(list []string) ([]*regexp.Regexp, error) {
compiled := make([]*regexp.Regexp, len(list))
for i, str := range list {
re, err := regexp.Compile(str)
if err != nil {
return nil, fmt.Errorf("failed to compile %q: %v", str, err)
}
compiled[i] = re
}
return compiled, nil
}
type reporterWrapper struct {
Reporter
suppressions []*regexp.Regexp
typ string
}
func (wrap *reporterWrapper) Parse(output []byte) *Report {
rep := wrap.Reporter.Parse(output)
if rep == nil {
return nil
}
rep.Title = sanitizeTitle(replaceTable(dynamicTitleReplacement, rep.Title))
rep.Suppressed = matchesAny(rep.Output, wrap.suppressions)
if bytes.Contains(rep.Output, gceConsoleHangup) {
rep.Corrupted = true
}
rep.Type = extractReportType(rep)
if match := reportFrameRe.FindStringSubmatch(rep.Title); match != nil {
rep.Frame = match[1]
}
if pos := bytes.Index(rep.Report, []byte(VMDiagnosisStart)); pos != -1 {
rep.Report = rep.Report[:pos]
}
rep.SkipPos = len(output)
if pos := bytes.IndexByte(output[rep.StartPos:], '\n'); pos != -1 {
rep.SkipPos = rep.StartPos + pos
}
if rep.EndPos < rep.SkipPos {
// This generally should not happen.
// But openbsd does some hacks with /r/n which may lead to off-by-one EndPos.
rep.EndPos = rep.SkipPos
}
return rep
}
func extractReportType(rep *Report) Type {
// Type/frame extraction logic should be integrated with oops types.
// But for now we do this more ad-hoc analysis here to at least isolate
// the rest of the code base from report parsing.
if rep.Title == unexpectedKernelReboot {
return UnexpectedReboot
}
if strings.HasPrefix(rep.Title, memoryLeakPrefix) {
return MemoryLeak
}
if strings.HasPrefix(rep.Title, dataRacePrefix) {
return DataRace
}
if strings.HasPrefix(rep.Title, "INFO: rcu detected stall") ||
strings.HasPrefix(rep.Title, "INFO: task hung") ||
strings.HasPrefix(rep.Title, "BUG: soft lockup") {
return Hang
}
return Unknown
}
func IsSuppressed(reporter Reporter, output []byte) bool {
return matchesAny(output, reporter.(*reporterWrapper).suppressions) ||
bytes.Contains(output, gceConsoleHangup)
}
// ParseAll returns all successive reports in output.
func ParseAll(reporter Reporter, output []byte) (reports []*Report) {
for {
rep := reporter.Parse(output)
if rep == nil {
return
}
reports = append(reports, rep)
output = output[rep.SkipPos:]
}
}
// GCE console connection sometimes fails with this message.
// The message frequently happens right after a kernel panic.
// So if we see it in output where we recognized a crash, we mark the report as corrupted
// because the crash message is usually truncated (maybe we don't even have the title line).
// If we see it in no output/lost connection reports then we mark them as suppressed instead
// because the crash itself may have been caused by the console connection error.
var gceConsoleHangup = []byte("serialport: VM disconnected.")
type replacement struct {
match *regexp.Regexp
replacement string
}
func replaceTable(replacements []replacement, str string) string {
for _, repl := range replacements {
str = repl.match.ReplaceAllString(str, repl.replacement)
}
return str
}
var dynamicTitleReplacement = []replacement{
{
// Executor PIDs are not interesting.
regexp.MustCompile(`syz-executor\.?[0-9]+((/|:)[0-9]+)?`),
"syz-executor",
},
{
// syzkaller binaries are coming from repro.
regexp.MustCompile(`syzkaller[0-9]+((/|:)[0-9]+)?`),
"syzkaller",
},
{
// Replace that everything looks like an address with "ADDR",
// addresses in descriptions can't be good regardless of the oops regexps.
regexp.MustCompile(`([^a-zA-Z])(?:0x)?[0-9a-f]{6,}`),
"${1}ADDR",
},
{
// Replace that everything looks like a decimal number with "NUM".
regexp.MustCompile(`([^a-zA-Z])[0-9]{5,}`),
"${1}NUM",
},
{
// Replace that everything looks like a file line number with "LINE".
regexp.MustCompile(`(:[0-9]+)+`),
":LINE",
},
{
// Replace all raw references to runctions (e.g. "ip6_fragment+0x1052/0x2d80")
// with just function name ("ip6_fragment"). Offsets and sizes are not stable.
regexp.MustCompile(`([a-zA-Z][a-zA-Z0-9_.]+)\+0x[0-9a-z]+/0x[0-9a-z]+`),
"${1}",
},
{
// CPU numbers are not interesting.
regexp.MustCompile(`CPU#[0-9]+`),
"CPU",
},
}
func sanitizeTitle(title string) string {
const maxTitleLen = 120 // Corrupted/intermixed lines can be very long.
res := make([]byte, 0, len(title))
prev := byte(' ')
for i := 0; i < len(title) && i < maxTitleLen; i++ {
ch := title[i]
switch {
case ch == '\t':
ch = ' '
case ch < 0x20 || ch >= 0x7f:
continue
}
if ch == ' ' && prev == ' ' {
continue
}
res = append(res, ch)
prev = ch
}
return strings.TrimSpace(string(res))
}
type oops struct {
header []byte
formats []oopsFormat
suppressions []*regexp.Regexp
}
type oopsFormat struct {
title *regexp.Regexp
// If title is matched but report is not, the report is considered corrupted.
report *regexp.Regexp
// Format string to create report title.
// Strings captured by title (or by report if present) are passed as input.
// If stack is not nil, extracted function name is passed as an additional last argument.
fmt string
// If not nil, a function name is extracted from the report and passed to fmt.
// If not nil but frame extraction fails, the report is considered corrupted.
stack *stackFmt
noStackTrace bool
corrupted bool
}
type stackFmt struct {
// parts describe how guilty stack frame must be extracted from the report.
// parts are matched consecutively potentially capturing frames.
// parts can be of 3 types:
// - non-capturing regexp, matched against report and advances current position
// - capturing regexp, same as above, but also yields a frame
// - special value parseStackTrace means that a stack trace must be parsed
// starting from current position
parts []*regexp.Regexp
// If parts2 is present it is tried when parts matching fails.
parts2 []*regexp.Regexp
// Skip these functions in stack traces (matched as substring).
skip []string
// Custom frame extractor (optional).
// Accepts set of all frames, returns guilty frame and corruption reason.
extractor frameExtractor
}
type frameExtractor func(frames []string) (frame string, corrupted string)
var parseStackTrace *regexp.Regexp
func compile(re string) *regexp.Regexp {
re = strings.Replace(re, "{{ADDR}}", "0x[0-9a-f]+", -1)
re = strings.Replace(re, "{{PC}}", "\\[\\<?(?:0x)?[0-9a-f]+\\>?\\]", -1)
re = strings.Replace(re, "{{FUNC}}", "([a-zA-Z0-9_]+)(?:\\.|\\+)", -1)
re = strings.Replace(re, "{{SRC}}", "([a-zA-Z0-9-_/.]+\\.[a-z]+:[0-9]+)", -1)
return regexp.MustCompile(re)
}
func containsCrash(output []byte, oopses []*oops, ignores []*regexp.Regexp) bool {
for pos := 0; pos < len(output); {
next := bytes.IndexByte(output[pos:], '\n')
if next != -1 {
next += pos
} else {
next = len(output)
}
for _, oops := range oopses {
if matchOops(output[pos:next], oops, ignores) {
return true
}
}
pos = next + 1
}
return false
}
func matchOops(line []byte, oops *oops, ignores []*regexp.Regexp) bool {
match := bytes.Index(line, oops.header)
if match == -1 {
return false
}
if matchesAny(line, oops.suppressions) {
return false
}
if matchesAny(line, ignores) {
return false
}
return true
}
func extractDescription(output []byte, oops *oops, params *stackParams) (
desc string, corrupted string, format oopsFormat) {
startPos := len(output)
matchedTitle := false
for _, f := range oops.formats {
match := f.title.FindSubmatchIndex(output)
if match == nil || match[0] > startPos {
continue
}
if match[0] == startPos && desc != "" {
continue
}
if match[0] < startPos {
desc = ""
format = oopsFormat{}
startPos = match[0]
}
matchedTitle = true
if f.report != nil {
match = f.report.FindSubmatchIndex(output)
if match == nil {
continue
}
}
var args []interface{}
for i := 2; i < len(match); i += 2 {
args = append(args, string(output[match[i]:match[i+1]]))
}
corrupted = ""
if f.stack != nil {
frame := ""
frame, corrupted = extractStackFrame(params, f.stack, output[match[0]:])
if frame == "" {
frame = "corrupted"
if corrupted == "" {
corrupted = "extracted no stack frame"
}
}
args = append(args, frame)
}
desc = fmt.Sprintf(f.fmt, args...)
format = f
}
if desc == "" {
// If we are here and matchedTitle is set, it means that we've matched
// a title of an oops but not full report regexp or stack trace,
// which means the report was corrupted.
if matchedTitle {
corrupted = "matched title but not report regexp"
}
pos := bytes.Index(output, oops.header)
if pos == -1 {
return
}
end := bytes.IndexByte(output[pos:], '\n')
if end == -1 {
end = len(output)
} else {
end += pos
}
desc = string(output[pos:end])
}
if corrupted == "" && format.corrupted {
corrupted = "report format is marked as corrupted"
}
return
}
type stackParams struct {
// stackStartRes matches start of stack traces.
stackStartRes []*regexp.Regexp
// frameRes match different formats of lines containing kernel frames (capture function name).
frameRes []*regexp.Regexp
// skipPatterns match functions that must be unconditionally skipped.
skipPatterns []string
// If we looked at any lines that match corruptedLines during report analysis,
// then the report is marked as corrupted.
corruptedLines []*regexp.Regexp
}
func extractStackFrame(params *stackParams, stack *stackFmt, output []byte) (string, string) {
skip := append([]string{}, params.skipPatterns...)
skip = append(skip, stack.skip...)
var skipRe *regexp.Regexp
if len(skip) != 0 {
skipRe = regexp.MustCompile(strings.Join(skip, "|"))
}
extractor := stack.extractor
if extractor == nil {
extractor = func(frames []string) (string, string) {
return frames[0], ""
}
}
frame, corrupted := extractStackFrameImpl(params, output, skipRe, stack.parts, extractor)
if frame != "" || len(stack.parts2) == 0 {
return frame, corrupted
}
return extractStackFrameImpl(params, output, skipRe, stack.parts2, extractor)
}
func extractStackFrameImpl(params *stackParams, output []byte, skipRe *regexp.Regexp,
parts []*regexp.Regexp, extractor frameExtractor) (string, string) {
s := bufio.NewScanner(bytes.NewReader(output))
var frames []string
nextPart:
for _, part := range parts {
if part == parseStackTrace {
for s.Scan() {
ln := bytes.Trim(s.Bytes(), "\r")
if matchesAny(ln, params.corruptedLines) {
break nextPart
}
if matchesAny(ln, params.stackStartRes) {
continue nextPart
}
var match [][]byte
for _, re := range params.frameRes {
match = re.FindSubmatch(ln)
if match != nil {
break
}
}
frames = appendStackFrame(frames, match, skipRe)
}
} else {
for s.Scan() {
ln := bytes.Trim(s.Bytes(), "\r")
if matchesAny(ln, params.corruptedLines) {
break nextPart
}
match := part.FindSubmatch(ln)
if match == nil {
continue
}
frames = appendStackFrame(frames, match, skipRe)
break
}
}
}
if len(frames) == 0 {
return "", corruptedNoFrames
}
return extractor(frames)
}
func appendStackFrame(frames []string, match [][]byte, skipRe *regexp.Regexp) []string {
if len(match) < 2 {
return frames
}
for _, frame := range match[1:] {
if frame != nil && (skipRe == nil || !skipRe.Match(frame)) {
frames = append(frames, string(frame))
break
}
}
return frames
}
func simpleLineParser(output []byte, oopses []*oops, params *stackParams, ignores []*regexp.Regexp) *Report {
rep := &Report{
Output: output,
}
var oops *oops
for pos := 0; pos < len(output); {
next := bytes.IndexByte(output[pos:], '\n')
if next != -1 {
next += pos
} else {
next = len(output)
}
line := output[pos:next]
for _, oops1 := range oopses {
if matchOops(line, oops1, ignores) {
oops = oops1
rep.StartPos = pos
rep.EndPos = next
break
}
}
if oops != nil {
break
}
pos = next + 1
}
if oops == nil {
return nil
}
title, corrupted, _ := extractDescription(output[rep.StartPos:], oops, params)
rep.Title = title
rep.Report = output[rep.StartPos:]
rep.Corrupted = corrupted != ""
rep.CorruptedReason = corrupted
return rep
}
func matchesAny(line []byte, res []*regexp.Regexp) bool {
for _, re := range res {
if re.Match(line) {
return true
}
}
return false
}
// replace replaces [start:end] in where with what, inplace.
func replace(where []byte, start, end int, what []byte) []byte {
if len(what) >= end-start {
where = append(where, what[end-start:]...)
copy(where[start+len(what):], where[end:])
copy(where[start:], what)
} else {
copy(where[start+len(what):], where[end:])
where = where[:len(where)-(end-start-len(what))]
copy(where[start:], what)
}
return where
}
var (
filenameRe = regexp.MustCompile(`[a-zA-Z0-9_\-\./]*[a-zA-Z0-9_\-]+\.(c|h):[0-9]+`)
reportFrameRe = regexp.MustCompile(`.* in ([a-zA-Z0-9_]+)`)
)
// These are produced by syzkaller itself.
// But also catches crashes in Go programs in gvisor/fuchsia.
var commonOopses = []*oops{
{
[]byte("panic:"),
[]oopsFormat{
{
title: compile("panic:(.*)"),
fmt: "panic:%[1]v",
noStackTrace: true,
},
},
[]*regexp.Regexp{
// This can match some kernel functions (skb_panic, skb_over_panic).
compile("_panic:"),
},
},
}