-
Notifications
You must be signed in to change notification settings - Fork 3k
/
compile.go
390 lines (339 loc) · 11.4 KB
/
compile.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
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package loader
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"path"
"strings"
"sync"
"syscall"
"github.com/cilium/ebpf"
"github.com/cilium/ebpf/asm"
"github.com/sirupsen/logrus"
"github.com/cilium/cilium/pkg/command/exec"
"github.com/cilium/cilium/pkg/common"
"github.com/cilium/cilium/pkg/datapath/linux/probes"
"github.com/cilium/cilium/pkg/logging/logfields"
"github.com/cilium/cilium/pkg/option"
)
// OutputType determines the type to be generated by the compilation steps.
type OutputType string
const (
outputObject = OutputType("obj")
outputSource = OutputType("c")
compiler = "clang"
endpointPrefix = "bpf_lxc"
endpointProg = endpointPrefix + "." + string(outputSource)
endpointObj = endpointPrefix + ".o"
hostEndpointPrefix = "bpf_host"
hostEndpointNetdevPrefix = "bpf_netdev_"
hostEndpointProg = hostEndpointPrefix + "." + string(outputSource)
hostEndpointObj = hostEndpointPrefix + ".o"
networkPrefix = "bpf_network"
networkProg = networkPrefix + "." + string(outputSource)
networkObj = networkPrefix + ".o"
xdpPrefix = "bpf_xdp"
xdpProg = xdpPrefix + "." + string(outputSource)
xdpObj = xdpPrefix + ".o"
overlayPrefix = "bpf_overlay"
overlayProg = overlayPrefix + "." + string(outputSource)
overlayObj = overlayPrefix + ".o"
)
var (
probeCPUOnce sync.Once
// default fallback
nameBPFCPU = "v1"
)
// progInfo describes a program to be compiled with the expected output format
type progInfo struct {
// Source is the program source (base) filename to be compiled
Source string
// Output is the expected (base) filename produced from the source
Output string
// OutputType to be created by LLVM
OutputType OutputType
// Options are passed directly to LLVM as individual parameters
Options []string
}
// directoryInfo includes relevant directories for compilation and linking
type directoryInfo struct {
// Library contains the library code to be used for compilation
Library string
// Runtime contains headers for compilation
Runtime string
// State contains node, lxc, and features headers for templatization
State string
// Output is the directory where the files will be stored
Output string
}
var (
standardCFlags = []string{"-O2", "--target=bpf", "-std=gnu89",
"-nostdinc", fmt.Sprintf("-D__NR_CPUS__=%d", common.GetNumPossibleCPUs(log)),
"-Wall", "-Wextra", "-Werror", "-Wshadow",
"-Wno-address-of-packed-member",
"-Wno-unknown-warning-option",
"-Wno-gnu-variable-sized-type-not-at-end",
"-Wdeclaration-after-statement",
"-Wimplicit-int-conversion",
"-Wenum-conversion"}
// testIncludes allows the unit tests to inject additional include
// paths into the compile command at test time. It is usually nil.
testIncludes []string
epProg = &progInfo{
Source: endpointProg,
Output: endpointObj,
OutputType: outputObject,
}
hostEpProg = &progInfo{
Source: hostEndpointProg,
Output: hostEndpointObj,
OutputType: outputObject,
}
networkTcProg = &progInfo{
Source: networkProg,
Output: networkObj,
OutputType: outputObject,
}
)
// GetBPFCPU returns the BPF CPU for this host.
func GetBPFCPU() string {
probeCPUOnce.Do(func() {
if !option.Config.DryMode {
// We can probe the availability of BPF instructions indirectly
// based on what kernel helpers are available when both were
// added in the same release.
// We want to enable v3 only on kernels 5.10+ where we have
// tested it and need it to work around complexity issues.
if probes.HaveV3ISA() == nil {
if probes.HaveProgramHelper(ebpf.SchedCLS, asm.FnRedirectNeigh) == nil {
nameBPFCPU = "v3"
return
}
}
// We want to enable v2 on all kernels that support it, that is,
// kernels 4.14+.
if probes.HaveV2ISA() == nil {
nameBPFCPU = "v2"
}
}
})
return nameBPFCPU
}
func pidFromProcess(proc *os.Process) string {
result := "not-started"
if proc != nil {
result = fmt.Sprintf("%d", proc.Pid)
}
return result
}
// compile and optionally link a program.
//
// May output assembly or source code after prepocessing.
func compile(ctx context.Context, prog *progInfo, dir *directoryInfo) (string, error) {
compileArgs := append(testIncludes,
fmt.Sprintf("-I%s", path.Join(dir.Runtime, "globals")),
fmt.Sprintf("-I%s", dir.State),
fmt.Sprintf("-I%s", dir.Library),
fmt.Sprintf("-I%s", path.Join(dir.Library, "include")),
)
switch prog.OutputType {
case outputSource:
compileArgs = append(compileArgs, "-E") // Preprocessor
case outputObject:
compileArgs = append(compileArgs, "-g")
}
compileArgs = append(compileArgs, standardCFlags...)
compileArgs = append(compileArgs, "-mcpu="+GetBPFCPU())
compileArgs = append(compileArgs, prog.Options...)
compileArgs = append(compileArgs,
"-c", path.Join(dir.Library, prog.Source),
"-o", "-", // Always output to stdout
)
log.WithFields(logrus.Fields{
"target": compiler,
"args": compileArgs,
}).Debug("Launching compiler")
compileCmd, cancelCompile := exec.WithCancel(ctx, compiler, compileArgs...)
defer cancelCompile()
output, err := os.Create(path.Join(dir.Output, prog.Output))
if err != nil {
return "", err
}
defer output.Close()
compileCmd.Stdout = output
var compilerStderr bytes.Buffer
compileCmd.Stderr = &compilerStderr
if err := compileCmd.Run(); err != nil {
err = fmt.Errorf("Failed to compile %s: %w", prog.Output, err)
// In linux/unix based implementations, cancelling the context for a cmd.Run() will
// return errors: "context cancelled" if the context is cancelled prior to the process
// starting and "signal: killed" if it is already running.
// This can mess up calling logging logic which expects the returned error to have
// context.Cancelled so we join this error in to fix that.
if errors.Is(ctx.Err(), context.Canceled) &&
compileCmd.ProcessState != nil &&
!compileCmd.ProcessState.Exited() &&
strings.HasSuffix(err.Error(), syscall.SIGKILL.String()) {
err = errors.Join(err, ctx.Err())
}
if !errors.Is(err, context.Canceled) {
log.WithFields(logrus.Fields{
"compiler-pid": pidFromProcess(compileCmd.Process),
}).Error(err)
}
scanner := bufio.NewScanner(io.LimitReader(&compilerStderr, 1_000_000))
for scanner.Scan() {
log.Warn(scanner.Text())
}
return "", err
}
// Cmd.ProcessState is populated by Cmd.Wait(). Cmd.Run() bails out if
// Cmd.Start() fails, which will leave Cmd.ProcessState nil. Only log peak
// RSS if the compilation succeeded, which will be the majority of cases.
if usage, ok := compileCmd.ProcessState.SysUsage().(*syscall.Rusage); ok {
log.WithFields(logrus.Fields{
"compiler-pid": compileCmd.Process.Pid,
"output": output.Name(),
}).Debugf("Compilation had peak RSS of %d bytes", usage.Maxrss)
}
return output.Name(), nil
}
// compileDatapath invokes the compiler and linker to create all state files for
// the BPF datapath, with the primary target being the BPF ELF binary.
//
// It also creates the following output files:
// * Preprocessed C
// * Assembly
// * Object compiled with debug symbols
func compileDatapath(ctx context.Context, dirs *directoryInfo, isHost bool, logger *logrus.Entry) error {
scopedLog := logger.WithField(logfields.Debug, true)
versionCmd := exec.CommandContext(ctx, compiler, "--version")
compilerVersion, err := versionCmd.CombinedOutput(scopedLog, true)
if err != nil {
return err
}
scopedLog.WithFields(logrus.Fields{
compiler: string(compilerVersion),
}).Debug("Compiling datapath")
prog := epProg
if isHost {
prog = hostEpProg
}
if option.Config.Debug && prog.OutputType == outputObject {
// Write out preprocessing files for debugging purposes
debugProg := *prog
debugProg.Output = debugProg.Source
debugProg.OutputType = outputSource
if _, err := compile(ctx, &debugProg, dirs); err != nil {
// Only log an error here if the context was not canceled. This log message
// should only represent failures with respect to compiling the program.
if !errors.Is(err, context.Canceled) {
scopedLog.WithField(logfields.Params, logfields.Repr(debugProg)).WithError(err).Debug("JoinEP: Failed to compile")
}
return err
}
}
if _, err := compile(ctx, prog, dirs); err != nil {
// Only log an error here if the context was not canceled. This log message
// should only represent failures with respect to compiling the program.
if !errors.Is(err, context.Canceled) {
scopedLog.WithField(logfields.Params, logfields.Repr(prog)).WithError(err).Warn("JoinEP: Failed to compile")
}
return err
}
return nil
}
// CompileWithOptions compiles a BPF program generating an object file,
// using a set of provided compiler options.
func CompileWithOptions(ctx context.Context, src string, out string, opts []string) error {
prog := progInfo{
Source: src,
Options: opts,
Output: out,
OutputType: outputObject,
}
dirs := directoryInfo{
Library: option.Config.BpfDir,
Runtime: option.Config.StateDir,
Output: option.Config.StateDir,
State: option.Config.StateDir,
}
_, err := compile(ctx, &prog, &dirs)
return err
}
// Compile compiles a BPF program generating an object file.
func Compile(ctx context.Context, src string, out string) error {
return CompileWithOptions(ctx, src, out, nil)
}
// compileTemplate compiles a BPF program generating a template object file.
func compileTemplate(ctx context.Context, out string, isHost bool) error {
dirs := directoryInfo{
Library: option.Config.BpfDir,
Runtime: option.Config.StateDir,
Output: out,
State: out,
}
return compileDatapath(ctx, &dirs, isHost, log)
}
// compileNetwork compiles a BPF program attached to network
func compileNetwork(ctx context.Context) error {
dirs := directoryInfo{
Library: option.Config.BpfDir,
Runtime: option.Config.StateDir,
Output: option.Config.StateDir,
State: option.Config.StateDir,
}
scopedLog := log.WithField(logfields.Debug, true)
versionCmd := exec.CommandContext(ctx, compiler, "--version")
compilerVersion, err := versionCmd.CombinedOutput(scopedLog, true)
if err != nil {
return err
}
scopedLog.WithFields(logrus.Fields{
compiler: string(compilerVersion),
}).Debug("Compiling network programs")
// Write out assembly and preprocessing files for debugging purposes
if _, err := compile(ctx, networkTcProg, &dirs); err != nil {
scopedLog.WithField(logfields.Params, logfields.Repr(networkTcProg)).
WithError(err).Warn("Failed to compile")
return err
}
return nil
}
// compileOverlay compiles BPF programs in bpf_overlay.c.
func compileOverlay(ctx context.Context, opts []string) error {
dirs := &directoryInfo{
Library: option.Config.BpfDir,
Runtime: option.Config.StateDir,
Output: option.Config.StateDir,
State: option.Config.StateDir,
}
scopedLog := log.WithField(logfields.Debug, true)
versionCmd := exec.CommandContext(ctx, compiler, "--version")
compilerVersion, err := versionCmd.CombinedOutput(scopedLog, true)
if err != nil {
return err
}
scopedLog.WithFields(logrus.Fields{
compiler: string(compilerVersion),
}).Debug("Compiling overlay programs")
prog := &progInfo{
Source: overlayProg,
Output: overlayObj,
OutputType: outputObject,
Options: opts,
}
// Write out assembly and preprocessing files for debugging purposes
if _, err := compile(ctx, prog, dirs); err != nil {
scopedLog.WithField(logfields.Params, logfields.Repr(prog)).
WithError(err).Warn("Failed to compile")
return err
}
return nil
}