-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
preprocess.go
59 lines (51 loc) · 1.59 KB
/
preprocess.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
package ebpf
import (
"bufio"
"bytes"
"io"
"regexp"
"github.com/DataDog/datadog-agent/pkg/ebpf/bytecode"
)
var (
// CIncludePattern is the regex for #include headers of C files
CIncludePattern = `^\s*#\s*include\s+"(.*)"$`
includeRegexp *regexp.Regexp
)
func init() {
includeRegexp = regexp.MustCompile(CIncludePattern)
}
// PreprocessFile pre-processes the `#include` of embedded headers.
// It will only replace top-level includes for files that exist
// and does not evaluate the content of included files for #include directives.
func PreprocessFile(bpfDir, fileName string) (*bytes.Buffer, error) {
sourceReader, err := bytecode.GetReader(bpfDir, fileName)
if err != nil {
return nil, err
}
defer sourceReader.Close()
// Note that embedded headers including other embedded headers is not managed because
// this would also require to properly handle inclusion guards.
source := new(bytes.Buffer)
scanner := bufio.NewScanner(sourceReader)
for scanner.Scan() {
match := includeRegexp.FindSubmatch(scanner.Bytes())
if len(match) == 2 {
header, err := bytecode.GetReader(bpfDir, string(match[1]))
if err == nil {
if _, err := io.Copy(source, header); err != nil {
header.Close()
return source, err
}
header.Close()
continue
}
}
source.Write(scanner.Bytes())
source.WriteByte('\n')
}
return source, nil
}