Debian Codegraph @

clang/clang.go

raw symbols SCIP
1 // Package clang implements a simple wrapper for invoking clang to
2 // compile C to eBPF
3 package clang
4
5 import (
6 "fmt"
7 "io/ioutil"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "strings"
12
13 "github.com/pkg/errors"
14 )
15
16 // CompileOpts configure how an XDP program is compiled / built
17 type Opts struct {
18 // clang binary to use
19 Clang string
20
21 // Header directories to include
22 Include []string
23
24 // Destination directory for compiled programs.
25 // Uses a temporary directory if empty.
26 Output string
27
28 // Emit DWARF debug info in the XDP elf.
29 // Required for BTF.
30 EmitDebug bool
31 }
32
33 // Compile compiles a C source string into an ELF
34 func Compile(source []byte, name string, opts Opts) ([]byte, error) {
35 var err error
36
37 outdir := opts.Output
38 if outdir == "" {
39 outdir, err = ioutil.TempDir("", "cbpfc-clang")
40 if err != nil {
41 return nil, errors.Wrap(err, "can't create output directory")
42 }
43 defer os.RemoveAll(outdir)
44 } else {
45 _ = os.Mkdir(outdir, 0755)
46 }
47
48 inputFile := fmt.Sprintf("%s.c", name)
49 outputFile := fmt.Sprintf("%s.elf", name)
50 err = ioutil.WriteFile(filepath.Join(outdir, inputFile), source, 0644)
51 if err != nil {
52 return nil, errors.Wrap(err, "can't write out program")
53 }
54
55 flags := []string{
56 "-O2",
57 "-Wall", "-Werror",
58 "-nostdinc",
59 "-c",
60 "-target", "bpf",
61 inputFile,
62 "-o", outputFile,
63 }
64
65 for _, include := range opts.Include {
66 // debug build script will be in a different directory, relative imports won't work
67 absInclude, err := filepath.Abs(include)
68 if err != nil {
69 return nil, errors.Wrapf(err, "can't get absolute path to include %s", include)
70 }
71
72 flags = append(flags, "-I", absInclude)
73 }
74
75 if opts.EmitDebug {
76 flags = append(flags, "-g")
77 }
78
79 cmd := exec.Command(opts.Clang, flags...)
80
81 // debug build script
82 if opts.Output != "" {
83 cmdline := cmd.Path + " " + strings.Join(flags, " ") + "\n"
84 err := ioutil.WriteFile(filepath.Join(outdir, "build"), []byte(cmdline), 0644)
85 if err != nil {
86 return nil, errors.Wrap(err, "can't write build cmdline")
87 }
88 }
89
90 cmd.Dir = outdir
91 _, err = cmd.Output()
92 if err != nil {
93 switch e := err.(type) {
94 case *exec.ExitError:
95 return nil, errors.Wrapf(e, "unable to compile C:\n%s", string(e.Stderr))
96 default:
97 return nil, errors.Wrapf(e, "unable to compile C")
98 }
99 }
100
101 elf, err := ioutil.ReadFile(filepath.Join(outdir, outputFile))
102 if err != nil {
103 return nil, errors.Wrap(err, "can't read ELF")
104 }
105
106 return elf, nil
107 }