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
|
package generate
import (
"bufio"
"fmt"
"io"
"regexp"
"strings"
)
type CConstant struct {
Name string
Value string
}
type CMember struct {
TypeName string
FieldName string
ArraySize string
}
type CStruct struct {
Name string
Members []CMember
}
// ParseCTypesInput parses C struct definitions and #define constants.
func ParseCTypesInput(r io.Reader) ([]CStruct, []CConstant, error) {
scanner := bufio.NewScanner(r)
var structs []CStruct
var constants []CConstant
var current *CStruct
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, "#define") {
c, ok := parseDefine(line)
if ok {
constants = append(constants, c)
}
continue
}
if isCommentLine(line) || line == "" {
continue
}
if strings.HasPrefix(line, "struct") && strings.HasSuffix(line, "{") {
name := strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(line, "struct"), "{"))
current = &CStruct{Name: name}
continue
}
if line == "};" && current != nil {
structs = append(structs, *current)
current = nil
continue
}
if current != nil {
m, ok := parseMember(line)
if ok {
current.Members = append(current.Members, m)
}
}
}
if err := scanner.Err(); err != nil {
return nil, nil, fmt.Errorf("scanning C input: %w", err)
}
return structs, constants, nil
}
// GenerateTypesGo produces the generated_types.go content.
func GenerateTypesGo(structs []CStruct, constants []CConstant) string {
var b strings.Builder
b.WriteString("// Code generated - don't change manually!\n")
b.WriteString("package types\n\n")
writeTypeDefsAndMaps(&b, constants)
for _, c := range constants {
constType := ""
if strings.HasPrefix(c.Name, "SYS_") {
constType = " TraceId "
}
fmt.Fprintf(&b, "const %s%s = %s\n", c.Name, constType, c.Value)
}
for _, s := range structs {
writeGoStruct(&b, s)
}
return b.String()
}
// AddTypesImports inserts the import block needed by the generated types code.
func AddTypesImports(code string) string {
needsImports := strings.Contains(code, "fmt.") ||
strings.Contains(code, "sync.") ||
strings.Contains(code, "binary.") ||
strings.Contains(code, "bytes.")
if !needsImports {
return code
}
importBlock := `import (
"bytes"
"encoding/binary"
"fmt"
"sync"
)
`
return strings.Replace(code, "package types\n\n", "package types\n\n"+importBlock, 1)
}
func parseDefine(line string) (CConstant, bool) {
fields := strings.Fields(line)
if len(fields) < 3 {
return CConstant{}, false
}
return CConstant{Name: fields[1], Value: fields[2]}, true
}
func isCommentLine(line string) bool {
return strings.HasPrefix(line, "//") || strings.HasPrefix(line, "/*") || strings.HasPrefix(line, "*")
}
var arrayRe = regexp.MustCompile(`^(\w+)\s+(\w+)\[(\w+)\];?$`)
var simpleRe = regexp.MustCompile(`^(\w+)\s+(\w+);?$`)
func parseMember(line string) (CMember, bool) {
line = strings.TrimSuffix(strings.TrimSpace(line), ";")
line = strings.TrimSpace(line)
if m := arrayRe.FindStringSubmatch(line + ";"); m != nil {
return CMember{TypeName: m[1], FieldName: m[2], ArraySize: m[3]}, true
}
if m := simpleRe.FindStringSubmatch(line + ";"); m != nil {
return CMember{TypeName: m[1], FieldName: m[2]}, true
}
return CMember{}, false
}
func writeTypeDefsAndMaps(b *strings.Builder, constants []CConstant) {
b.WriteString("type EventType uint32\n")
b.WriteString("type TraceId uint32\n\n")
writeSyscallFamilyDefs(b)
var sysConstants []CConstant
for _, c := range constants {
if strings.HasPrefix(c.Name, "SYS_") {
sysConstants = append(sysConstants, c)
}
}
writeTraceIdMap(b, "traceId2String", sysConstants, func(name string) string {
return strings.ToLower(strings.TrimPrefix(name, "SYS_"))
})
writeTraceIdMap(b, "traceId2Name", sysConstants, func(name string) string {
s := strings.TrimPrefix(name, "SYS_ENTER_")
s = strings.TrimPrefix(s, "SYS_EXIT_")
return strings.ToLower(s)
})
writeTraceIdFamilyMap(b, sysConstants)
writeTraceIdStringMethod(b)
writeTraceIdNameMethod(b)
writeTraceIdFamilyMethod(b)
b.WriteString("\n")
}
func writeSyscallFamilyDefs(b *strings.Builder) {
b.WriteString(`// SyscallFamily is the broad runtime grouping for a syscall tracepoint.
type SyscallFamily string
const (
FamilyNetwork SyscallFamily = "Network"
FamilyMemory SyscallFamily = "Memory"
FamilySignals SyscallFamily = "Signals"
FamilySched SyscallFamily = "Sched"
FamilyIPC SyscallFamily = "IPC"
FamilyTime SyscallFamily = "Time"
FamilyProcess SyscallFamily = "Process"
FamilySecurity SyscallFamily = "Security"
FamilyFS SyscallFamily = "FS"
FamilyPolling SyscallFamily = "Polling"
FamilyAIO SyscallFamily = "AIO"
FamilyMisc SyscallFamily = "Misc"
)
`)
}
func writeTraceIdMap(b *strings.Builder, mapName string, constants []CConstant, transform func(string) string) {
fmt.Fprintf(b, "var %s = map[TraceId]string{\n\t", mapName)
entries := make([]string, 0, len(constants))
for _, c := range constants {
entries = append(entries, fmt.Sprintf("%s: %q", c.Value, transform(c.Name)))
}
b.WriteString(strings.Join(entries, ", "))
b.WriteString(",\n}\n\n")
}
func writeTraceIdFamilyMap(b *strings.Builder, constants []CConstant) {
b.WriteString("var traceId2Family = map[TraceId]SyscallFamily{\n\t")
entries := make([]string, 0, len(constants))
for _, c := range constants {
tracepoint := strings.ToLower(c.Name)
tracepoint = strings.TrimPrefix(tracepoint, "sys_")
family := ClassifySyscallFamily("sys_" + tracepoint)
entries = append(entries, fmt.Sprintf("%s: %s", c.Value, syscallFamilyConstName(family)))
}
b.WriteString(strings.Join(entries, ", "))
b.WriteString(",\n}\n\n")
}
func syscallFamilyConstName(family SyscallFamily) string {
switch family {
case FamilyNetwork:
return "FamilyNetwork"
case FamilyMemory:
return "FamilyMemory"
case FamilySignals:
return "FamilySignals"
case FamilySched:
return "FamilySched"
case FamilyIPC:
return "FamilyIPC"
case FamilyTime:
return "FamilyTime"
case FamilyProcess:
return "FamilyProcess"
case FamilySecurity:
return "FamilySecurity"
case FamilyFS:
return "FamilyFS"
case FamilyPolling:
return "FamilyPolling"
case FamilyAIO:
return "FamilyAIO"
default:
return "FamilyMisc"
}
}
func writeTraceIdStringMethod(b *strings.Builder) {
b.WriteString(`func (s TraceId) String() string {
str, ok := traceId2String[s]
if !ok {
return fmt.Sprintf("unknown_trace_id_%d", s)
}
return str
}
`)
}
func writeTraceIdNameMethod(b *strings.Builder) {
b.WriteString(`func (s TraceId) Name() string {
str, ok := traceId2Name[s]
if !ok {
return fmt.Sprintf("unknown_trace_id_%d", s)
}
return str
}
`)
}
func writeTraceIdFamilyMethod(b *strings.Builder) {
b.WriteString(`// Family returns the broad syscall family for this tracepoint.
func (s TraceId) Family() SyscallFamily {
family, ok := traceId2Family[s]
if !ok {
return FamilyMisc
}
return family
}
`)
}
func writeGoStruct(b *strings.Builder, s CStruct) {
goName := snakeToCamel(s.Name)
selfRef := strings.ToLower(goName[:1])
b.WriteString("\n")
fmt.Fprintf(b, "type %s struct {\n\t", goName)
memberDefs := make([]string, 0, len(s.Members))
for _, m := range s.Members {
memberDefs = append(memberDefs, goMemberDef(m))
}
b.WriteString(strings.Join(memberDefs, "; "))
b.WriteString(" \n}\n\n")
writeStringMethod(b, goName, selfRef, s.Members)
writeEqualsMethod(b, goName, selfRef, s.Members)
writeGetterMethods(b, goName, selfRef)
if strings.HasSuffix(goName, "Event") {
b.WriteString("\n")
writeSyncPool(b, goName, selfRef)
}
}
func goMemberDef(m CMember) string {
goField := snakeToCamel(m.FieldName)
goType := cTypeToGoType(m.TypeName)
if goField == "TraceId" {
goType = "TraceId"
}
if goField == "EventType" {
goType = "EventType"
}
if m.ArraySize != "" {
return fmt.Sprintf("%s [%s]%s", goField, m.ArraySize, goType)
}
return fmt.Sprintf("%s %s", goField, goType)
}
func writeStringMethod(b *strings.Builder, goName, selfRef string, members []CMember) {
fmtParts := make([]string, 0, len(members))
argParts := make([]string, 0, len(members))
for _, m := range members {
goField := snakeToCamel(m.FieldName)
fmtParts = append(fmtParts, goField+":%v")
ref := selfRef + "." + goField
if m.TypeName == "char" && m.ArraySize != "" {
ref = fmt.Sprintf("string(%s[:])", ref)
}
argParts = append(argParts, ref)
}
fmt.Fprintf(b, "func (%s %s) String() string {\n", selfRef, goName)
fmt.Fprintf(b, "\treturn fmt.Sprintf(\"%s\", %s)\n", strings.Join(fmtParts, " "), strings.Join(argParts, ", "))
b.WriteString("}\n\n")
}
func writeEqualsMethod(b *strings.Builder, goName, selfRef string, members []CMember) {
fmt.Fprintf(b, "func (%s %s) Equals(other any) bool {\n", selfRef, goName)
fmt.Fprintf(b, "\totherConcrete, ok := other.(*%s)\n", goName)
b.WriteString("\tif !ok {\n\t\treturn false\n\t}\n")
conds := make([]string, 0, len(members))
for _, m := range members {
goField := snakeToCamel(m.FieldName)
conds = append(conds, fmt.Sprintf("%s.%s == otherConcrete.%s", selfRef, goField, goField))
}
fmt.Fprintf(b, "\treturn %s\n", strings.Join(conds, " && "))
b.WriteString("}\n\n")
}
func writeGetterMethods(b *strings.Builder, goName, selfRef string) {
getters := []struct {
method string
returnType string
field string
}{
{"GetEventType", "EventType", "EventType"},
{"GetTraceId", "TraceId", "TraceId"},
{"GetPid", "uint32", "Pid"},
{"GetTid", "uint32", "Tid"},
{"GetTime", "uint64", "Time"},
}
for _, g := range getters {
fmt.Fprintf(b, "func (%s *%s) %s() %s {\n\treturn %s.%s\n}\n\n",
selfRef, goName, g.method, g.returnType, selfRef, g.field)
}
}
func writeSyncPool(b *strings.Builder, goName, selfRef string) {
fmt.Fprintf(b, "var poolOf%ss = sync.Pool{\n\tNew: func() any { return &%s{} },\n}\n\n", goName, goName)
fmt.Fprintf(b, "func New%s(raw []byte) *%s {\n", goName, goName)
fmt.Fprintf(b, "\t%s := poolOf%ss.Get().(*%s)\n", selfRef, goName, goName)
fmt.Fprintf(b, "\tif err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, %s); err != nil {\n", selfRef)
fmt.Fprintf(b, "\t\t*%s = %s{}\n", selfRef, goName)
fmt.Fprintf(b, "\t\tpoolOf%ss.Put(%s)\n", goName, selfRef)
b.WriteString("\t\treturn nil\n\t}\n")
fmt.Fprintf(b, "\treturn %s\n}\n\n", selfRef)
fmt.Fprintf(b, "func (%s *%s) Bytes() ([]byte, error) {\n", selfRef, goName)
b.WriteString("\tbuf := new(bytes.Buffer)\n")
fmt.Fprintf(b, "\terr := binary.Write(buf, binary.LittleEndian, %s)\n", selfRef)
b.WriteString("\tif err != nil {\n\t\treturn nil, err\n\t}\n")
b.WriteString("\treturn buf.Bytes(), nil\n}\n\n")
fmt.Fprintf(b, "func (%s *%s) Recycle() {\n\tpoolOf%ss.Put(%s)\n}\n", selfRef, goName, goName, selfRef)
}
func snakeToCamel(s string) string {
parts := strings.Split(s, "_")
for i, p := range parts {
if p == "" {
continue
}
parts[i] = strings.ToUpper(p[:1]) + p[1:]
}
return strings.Join(parts, "")
}
func cTypeToGoType(t string) string {
switch t {
case "char":
return "byte"
case "__s32":
return "int32"
case "__u32":
return "uint32"
case "__s64":
return "int64"
case "__u64":
return "uint64"
default:
return t
}
}
|