summaryrefslogtreecommitdiff
path: root/internal/generate/codegen.go
blob: 339dc1f1d292eb75d7093d689afbaba07290726a (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
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
package generate

import (
	"cmp"
	"fmt"
	"slices"
	"strings"
)

// Syscall groups enter+exit formats by syscall name.
type Syscall struct {
	Name  string
	Enter *Format
	Exit  *Format
}

// GeneratedTracepoint holds a classified format ready for code generation.
type GeneratedTracepoint struct {
	Format         *Format
	Classification ClassificationResult
}

// GenerateTracepointsC produces the full generated_tracepoints.c content from
// concatenated sysfs format data parsed into formats.
func GenerateTracepointsC(formats []Format) string {
	syscalls := groupBySyscall(formats)
	var b strings.Builder

	b.WriteString("// Code generated - don't change manually!\n\n")

	var accepted []GeneratedTracepoint
	for _, sc := range syscalls {
		tracepoints, reason := classifySyscall(sc)
		if reason != "" {
			fmt.Fprintf(&b, "/// %s\n", reason)
			continue
		}
		accepted = append(accepted, tracepoints...)
	}

	slices.SortFunc(accepted, func(a, b GeneratedTracepoint) int {
		return cmp.Compare(b.Format.ID, a.Format.ID)
	})

	b.WriteString("\n")
	for _, tp := range accepted {
		fmt.Fprintf(&b, "#define %s %d\n", strings.ToUpper(tp.Format.Name), tp.Format.ID)
	}
	b.WriteString("\n")

	for _, tp := range accepted {
		b.WriteString(generateBPFHandler(tp))
		b.WriteString("\n")
	}

	return b.String()
}

func groupBySyscall(formats []Format) []Syscall {
	m := make(map[string]*Syscall)
	var order []string

	for i := range formats {
		f := &formats[i]
		parts := strings.SplitN(f.Name, "_", 3)
		if len(parts) < 3 {
			continue
		}
		enterExit := parts[1]
		what := parts[2]

		sc, ok := m[what]
		if !ok {
			sc = &Syscall{Name: what}
			m[what] = sc
			order = append(order, what)
		}
		if enterExit == "enter" {
			sc.Enter = f
		} else {
			sc.Exit = f
		}
	}

	result := make([]Syscall, 0, len(order))
	for _, name := range order {
		result = append(result, *m[name])
	}
	return result
}

func classifySyscall(sc Syscall) ([]GeneratedTracepoint, string) {
	var enterClass, exitClass ClassificationResult
	allCanGenerate := true

	if sc.Enter != nil {
		enterClass = classifyEnterForGeneration(sc.Enter)
		if enterClass.Kind == KindNone {
			allCanGenerate = false
		}
	} else {
		allCanGenerate = false
	}

	if sc.Exit != nil {
		exitClass = ClassifyFormat(sc.Exit)
		if exitClass.Kind == KindNone {
			allCanGenerate = false
		}
	} else {
		allCanGenerate = false
	}

	if !allCanGenerate {
		names := syscallFormatNames(sc)
		return nil, fmt.Sprintf("Skipping %s as incomplete or unclassifiable", strings.Join(names, " "))
	}

	if isEnterRejected(enterClass.Kind) {
		names := syscallFormatNames(sc)
		return nil, fmt.Sprintf("Ignoring %s as enter-rejected", strings.Join(names, " "))
	}

	var result []GeneratedTracepoint
	if sc.Enter != nil {
		result = append(result, GeneratedTracepoint{Format: sc.Enter, Classification: enterClass})
	}
	// Emit the exit handler only for syscalls that can actually return.
	// Noreturn syscalls (exit, exit_group) never return to userspace, so their
	// sys_exit tracepoint never fires; emitting a handler would be dead code in
	// the generated BPF program. We still emit their enter handler above.
	if sc.Exit != nil && !isNoreturnSyscall(sc.Name) {
		result = append(result, GeneratedTracepoint{Format: sc.Exit, Classification: exitClass})
	}
	return result, ""
}

func classifyEnterForGeneration(f *Format) ClassificationResult {
	classification := ClassifyFormat(f)
	if classification.Kind != KindNone || len(f.ExternalFields) == 0 {
		return classification
	}
	return ClassificationResult{Kind: KindNull}
}

// isEnterRejected reports whether kind must not appear on a syscall-enter
// tracepoint. The answer comes from the kindRegistry so no switch statement
// needs updating when a new TracepointKind is added.
func isEnterRejected(kind TracepointKind) bool {
	return !lookupKind(kind).enterAccepted
}

// noreturnSyscalls lists syscalls that never return control to userspace.
// Their sys_exit tracepoint can never fire, so the generator suppresses the
// matching exit handler (see classifySyscall) to avoid dead code in the
// generated BPF program.
var noreturnSyscalls = map[string]bool{
	"exit":       true,
	"exit_group": true,
}

// isNoreturnSyscall reports whether the named syscall never returns and thus
// must not have an exit handler emitted.
func isNoreturnSyscall(name string) bool {
	return noreturnSyscalls[name]
}

func syscallFormatNames(sc Syscall) []string {
	var names []string
	if sc.Enter != nil {
		names = append(names, sc.Enter.Name)
	}
	if sc.Exit != nil {
		names = append(names, sc.Exit.Name)
	}
	slices.Sort(names)
	return names
}