aboutsummaryrefslogtreecommitdiffstats
path: root/tools/syz-diff/patch.go
blob: 98a464ca026593ddd640bbf0659691e02d4b5fde (plain)
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
// Copyright 2024 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 main

import (
	"sort"
	"strings"
	"time"

	"github.com/google/syzkaller/pkg/log"
	"github.com/google/syzkaller/pkg/mgrconfig"
	"github.com/google/syzkaller/pkg/osutil"
	"github.com/google/syzkaller/pkg/vcs"
)

func PatchFocusAreas(cfg *mgrconfig.Config, gitPatch []byte) {
	const maxAffectedByHeader = 50

	names := map[string]bool{}
	includedNames := map[string]bool{}
	for _, file := range vcs.ParseGitDiff(gitPatch) {
		names[file] = true

		if strings.HasSuffix(file, ".h") && cfg.KernelSrc != "" {
			// Ideally, we should combine this with the recompilation process - then we know
			// exactly which files were affected by the patch.
			out, err := osutil.RunCmd(time.Minute, cfg.KernelSrc, "/usr/bin/grep",
				"-rl", "--include", `*.c`, `<`+strings.TrimPrefix(file, "include/")+`>`)
			if err != nil {
				log.Logf(0, "failed to grep for the header usages: %v", err)
				continue
			}
			lines := strings.Split(string(out), "\n")
			if len(lines) >= maxAffectedByHeader {
				// It's too widespread. It won't help us focus on anything.
				log.Logf(0, "the header %q is included in too many files (%d)", file, len(lines))
				continue
			}
			for _, name := range lines {
				name = strings.TrimSpace(name)
				if name == "" {
					continue
				}
				includedNames[name] = true
			}
		}
	}

	var namesList, includedList []string
	for name := range names {
		namesList = append(namesList, name)
	}
	for name := range includedNames {
		if names[name] {
			continue
		}
		includedList = append(includedList, name)
	}

	if len(namesList) > 0 {
		sort.Strings(namesList)
		log.Logf(0, "adding the following modified files to focus_order: %q", namesList)
		cfg.Experimental.FocusAreas = append(cfg.Experimental.FocusAreas,
			mgrconfig.FocusArea{
				Name: "modified",
				Filter: mgrconfig.CovFilterCfg{
					Files: namesList,
				},
				Weight: 3.0,
			})
	}

	if len(includedList) > 0 {
		sort.Strings(includedList)
		log.Logf(0, "adding the following included files to focus_order: %q", includedList)
		cfg.Experimental.FocusAreas = append(cfg.Experimental.FocusAreas,
			mgrconfig.FocusArea{
				Name: "included",
				Filter: mgrconfig.CovFilterCfg{
					Files: includedList,
				},
				Weight: 2.0,
			})
	}

	// Still fuzz the rest of the kernel.
	if len(cfg.Experimental.FocusAreas) > 0 {
		cfg.Experimental.FocusAreas = append(cfg.Experimental.FocusAreas,
			mgrconfig.FocusArea{
				Weight: 1.0,
			})
	}
}