blob: 737675057769e2bb2abda4250d55aad1b923b943 [file] [log] [blame]
Colin Cross38406592018-05-17 11:17:01 -07001// Copyright (C) 2018 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package bpf
16
17import (
18 "fmt"
19 "io"
Ken Chen5372a242022-07-07 17:48:06 +080020 "path/filepath"
Connor O'Brien3e739cf2022-08-17 15:45:52 -070021 "runtime"
Colin Cross38406592018-05-17 11:17:01 -070022 "strings"
23
24 "android/soong/android"
Zi Wangb3cb38c2022-09-23 16:36:11 -070025 "android/soong/bazel"
Zi Wangaa981ed2022-10-04 16:59:31 -070026 "android/soong/bazel/cquery"
Colin Cross38406592018-05-17 11:17:01 -070027
28 "github.com/google/blueprint"
Connor O'Brien25739652021-12-02 20:09:45 -080029 "github.com/google/blueprint/proptools"
Colin Cross38406592018-05-17 11:17:01 -070030)
31
32func init() {
Paul Duffin12c7eb82021-02-24 18:51:54 +000033 registerBpfBuildComponents(android.InitRegistrationContext)
Colin Cross38406592018-05-17 11:17:01 -070034 pctx.Import("android/soong/cc/config")
Connor O'Brien3e739cf2022-08-17 15:45:52 -070035 if runtime.GOOS != "darwin" {
36 pctx.StaticVariable("relPwd", "PWD=/proc/self/cwd")
37 }
Colin Cross38406592018-05-17 11:17:01 -070038}
39
40var (
41 pctx = android.NewPackageContext("android/soong/bpf")
42
Ramy Medhat8ea054a2020-01-27 14:19:44 -050043 ccRule = pctx.AndroidRemoteStaticRule("ccRule", android.RemoteRuleSupports{Goma: true},
Colin Cross38406592018-05-17 11:17:01 -070044 blueprint.RuleParams{
45 Depfile: "${out}.d",
46 Deps: blueprint.DepsGCC,
Connor O'Brien3e739cf2022-08-17 15:45:52 -070047 Command: "$relPwd $ccCmd --target=bpf -c $cFlags -MD -MF ${out}.d -o $out $in",
Colin Cross38406592018-05-17 11:17:01 -070048 CommandDeps: []string{"$ccCmd"},
49 },
50 "ccCmd", "cFlags")
Connor O'Brien25739652021-12-02 20:09:45 -080051
52 stripRule = pctx.AndroidStaticRule("stripRule",
53 blueprint.RuleParams{
54 Command: `$stripCmd --strip-unneeded --remove-section=.rel.BTF ` +
55 `--remove-section=.rel.BTF.ext --remove-section=.BTF.ext $in -o $out`,
56 CommandDeps: []string{"$stripCmd"},
57 },
58 "stripCmd")
Colin Cross38406592018-05-17 11:17:01 -070059)
60
Paul Duffin12c7eb82021-02-24 18:51:54 +000061func registerBpfBuildComponents(ctx android.RegistrationContext) {
62 ctx.RegisterModuleType("bpf", BpfFactory)
63}
64
65var PrepareForTestWithBpf = android.FixtureRegisterWithContext(registerBpfBuildComponents)
66
markchien2f59ec92020-09-02 16:23:38 +080067// BpfModule interface is used by the apex package to gather information from a bpf module.
68type BpfModule interface {
69 android.Module
70
71 OutputFiles(tag string) (android.Paths, error)
Ken Chenfad7f9d2021-11-10 22:02:57 +080072
73 // Returns the sub install directory if the bpf module is included by apex.
74 SubDir() string
markchien2f59ec92020-09-02 16:23:38 +080075}
76
Colin Cross38406592018-05-17 11:17:01 -070077type BpfProperties struct {
Zi Wang4877c722022-08-11 18:05:13 +000078 // source paths to the files.
79 Srcs []string `android:"path"`
80
81 // additional cflags that should be used to build the bpf variant of
82 // the C/C++ module.
83 Cflags []string
84
85 // directories (relative to the root of the source tree) that will
86 // be added to the include paths using -I.
Colin Cross38406592018-05-17 11:17:01 -070087 Include_dirs []string
Zi Wang4877c722022-08-11 18:05:13 +000088
89 // optional subdirectory under which this module is installed into.
90 Sub_dir string
91
92 // if set to true, generate BTF debug info for maps & programs.
93 Btf *bool
94
Steven Moreland606c5e92019-12-12 14:23:42 -080095 Vendor *bool
96
97 VendorInternal bool `blueprint:"mutated"`
Colin Cross38406592018-05-17 11:17:01 -070098}
99
100type bpf struct {
101 android.ModuleBase
Zi Wangb3cb38c2022-09-23 16:36:11 -0700102 android.BazelModuleBase
Colin Cross38406592018-05-17 11:17:01 -0700103
104 properties BpfProperties
105
106 objs android.Paths
107}
108
Steven Moreland606c5e92019-12-12 14:23:42 -0800109var _ android.ImageInterface = (*bpf)(nil)
110
111func (bpf *bpf) ImageMutatorBegin(ctx android.BaseModuleContext) {}
112
113func (bpf *bpf) CoreVariantNeeded(ctx android.BaseModuleContext) bool {
114 return !proptools.Bool(bpf.properties.Vendor)
115}
116
117func (bpf *bpf) RamdiskVariantNeeded(ctx android.BaseModuleContext) bool {
118 return false
119}
120
121func (bpf *bpf) VendorRamdiskVariantNeeded(ctx android.BaseModuleContext) bool {
122 return false
123}
124
125func (bpf *bpf) DebugRamdiskVariantNeeded(ctx android.BaseModuleContext) bool {
126 return false
127}
128
129func (bpf *bpf) RecoveryVariantNeeded(ctx android.BaseModuleContext) bool {
130 return false
131}
132
133func (bpf *bpf) ExtraImageVariations(ctx android.BaseModuleContext) []string {
134 if proptools.Bool(bpf.properties.Vendor) {
135 return []string{"vendor"}
136 }
137 return nil
138}
139
140func (bpf *bpf) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
141 bpf.properties.VendorInternal = variation == "vendor"
142}
143
Colin Cross38406592018-05-17 11:17:01 -0700144func (bpf *bpf) GenerateAndroidBuildActions(ctx android.ModuleContext) {
145 cflags := []string{
146 "-nostdlibinc",
Kousik Kumarfb0e2512020-03-25 15:01:27 -0700147
148 // Make paths in deps files relative
149 "-no-canonical-prefixes",
150
Colin Cross38406592018-05-17 11:17:01 -0700151 "-O2",
152 "-isystem bionic/libc/include",
153 "-isystem bionic/libc/kernel/uapi",
154 // The architecture doesn't matter here, but asm/types.h is included by linux/types.h.
155 "-isystem bionic/libc/kernel/uapi/asm-arm64",
156 "-isystem bionic/libc/kernel/android/uapi",
Ken Chenfd264442021-12-20 18:22:55 +0800157 "-I frameworks/libs/net/common/native/bpf_headers/include/bpf",
Maciej Żenczykowski79f6f752020-02-18 15:38:36 -0800158 // TODO(b/149785767): only give access to specific file with AID_* constants
159 "-I system/core/libcutils/include",
Colin Cross38406592018-05-17 11:17:01 -0700160 "-I " + ctx.ModuleDir(),
161 }
162
163 for _, dir := range android.PathsForSource(ctx, bpf.properties.Include_dirs) {
164 cflags = append(cflags, "-I "+dir.String())
165 }
166
167 cflags = append(cflags, bpf.properties.Cflags...)
168
Connor O'Brien25739652021-12-02 20:09:45 -0800169 if proptools.Bool(bpf.properties.Btf) {
170 cflags = append(cflags, "-g")
Connor O'Brien3e739cf2022-08-17 15:45:52 -0700171 if runtime.GOOS != "darwin" {
172 cflags = append(cflags, "-fdebug-prefix-map=/proc/self/cwd=")
173 }
Connor O'Brien25739652021-12-02 20:09:45 -0800174 }
175
Colin Cross8a497952019-03-05 22:25:09 -0800176 srcs := android.PathsForModuleSrc(ctx, bpf.properties.Srcs)
Colin Cross38406592018-05-17 11:17:01 -0700177
178 for _, src := range srcs {
Ken Chen5372a242022-07-07 17:48:06 +0800179 if strings.ContainsRune(filepath.Base(src.String()), '_') {
180 ctx.ModuleErrorf("invalid character '_' in source name")
181 }
Connor O'Brien25739652021-12-02 20:09:45 -0800182 obj := android.ObjPathWithExt(ctx, "unstripped", src, "o")
Colin Cross38406592018-05-17 11:17:01 -0700183
184 ctx.Build(pctx, android.BuildParams{
Colin Cross815daf92019-05-14 16:05:20 -0700185 Rule: ccRule,
Colin Cross38406592018-05-17 11:17:01 -0700186 Input: src,
187 Output: obj,
188 Args: map[string]string{
189 "cFlags": strings.Join(cflags, " "),
190 "ccCmd": "${config.ClangBin}/clang",
191 },
192 })
193
Connor O'Brien25739652021-12-02 20:09:45 -0800194 if proptools.Bool(bpf.properties.Btf) {
195 objStripped := android.ObjPathWithExt(ctx, "", src, "o")
196 ctx.Build(pctx, android.BuildParams{
Steven Moreland606c5e92019-12-12 14:23:42 -0800197 Rule: stripRule,
198 Input: obj,
Connor O'Brien25739652021-12-02 20:09:45 -0800199 Output: objStripped,
200 Args: map[string]string{
201 "stripCmd": "${config.ClangBin}/llvm-strip",
202 },
203 })
204 bpf.objs = append(bpf.objs, objStripped.WithoutRel())
205 } else {
206 bpf.objs = append(bpf.objs, obj.WithoutRel())
207 }
208
Colin Cross38406592018-05-17 11:17:01 -0700209 }
210}
211
Colin Cross38406592018-05-17 11:17:01 -0700212func (bpf *bpf) AndroidMk() android.AndroidMkData {
213 return android.AndroidMkData{
214 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
215 var names []string
216 fmt.Fprintln(w)
217 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
218 fmt.Fprintln(w)
Steven Moreland606c5e92019-12-12 14:23:42 -0800219 var localModulePath string
220 if bpf.properties.VendorInternal {
221 localModulePath = "LOCAL_MODULE_PATH := $(TARGET_OUT_VENDOR_ETC)/bpf"
222 } else {
223 localModulePath = "LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)/bpf"
224 }
Ken Chenfad7f9d2021-11-10 22:02:57 +0800225 if len(bpf.properties.Sub_dir) > 0 {
226 localModulePath += "/" + bpf.properties.Sub_dir
227 }
Colin Cross38406592018-05-17 11:17:01 -0700228 for _, obj := range bpf.objs {
229 objName := name + "_" + obj.Base()
230 names = append(names, objName)
231 fmt.Fprintln(w, "include $(CLEAR_VARS)")
232 fmt.Fprintln(w, "LOCAL_MODULE := ", objName)
Bob Badourb4999222021-01-07 03:34:31 +0000233 data.Entries.WriteLicenseVariables(w)
Colin Cross38406592018-05-17 11:17:01 -0700234 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", obj.String())
235 fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", obj.Base())
236 fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC")
Ken Chenfad7f9d2021-11-10 22:02:57 +0800237 fmt.Fprintln(w, localModulePath)
Colin Cross38406592018-05-17 11:17:01 -0700238 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
239 fmt.Fprintln(w)
240 }
241 fmt.Fprintln(w, "include $(CLEAR_VARS)")
242 fmt.Fprintln(w, "LOCAL_MODULE := ", name)
Bob Badourb4999222021-01-07 03:34:31 +0000243 data.Entries.WriteLicenseVariables(w)
Colin Cross38406592018-05-17 11:17:01 -0700244 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", strings.Join(names, " "))
245 fmt.Fprintln(w, "include $(BUILD_PHONY_PACKAGE)")
246 },
247 }
248}
249
Zi Wangaa981ed2022-10-04 16:59:31 -0700250var _ android.MixedBuildBuildable = (*bpf)(nil)
251
252func (bpf *bpf) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
253 return true
254}
255
256func (bpf *bpf) QueueBazelCall(ctx android.BaseModuleContext) {
257 bazelCtx := ctx.Config().BazelContext
258 bazelCtx.QueueBazelRequest(
259 bpf.GetBazelLabel(ctx, bpf),
260 cquery.GetOutputFiles,
261 android.GetConfigKey(ctx))
262}
263
264func (bpf *bpf) ProcessBazelQueryResponse(ctx android.ModuleContext) {
265 bazelCtx := ctx.Config().BazelContext
266 objPaths, err := bazelCtx.GetOutputFiles(bpf.GetBazelLabel(ctx, bpf), android.GetConfigKey(ctx))
267 if err != nil {
268 ctx.ModuleErrorf(err.Error())
269 return
270 }
271
272 bazelOuts := android.Paths{}
273 for _, p := range objPaths {
274 bazelOuts = append(bazelOuts, android.PathForBazelOut(ctx, p))
275 }
276 bpf.objs = bazelOuts
277}
278
Colin Cross41955e82019-05-29 14:40:35 -0700279// Implements OutputFileFileProducer interface so that the obj output can be used in the data property
Jaewoong Jung5f3fb4b2018-12-13 15:01:46 -0800280// of other modules.
Colin Cross41955e82019-05-29 14:40:35 -0700281func (bpf *bpf) OutputFiles(tag string) (android.Paths, error) {
282 switch tag {
283 case "":
284 return bpf.objs, nil
285 default:
286 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
287 }
Jaewoong Jung5f3fb4b2018-12-13 15:01:46 -0800288}
289
Ken Chenfad7f9d2021-11-10 22:02:57 +0800290func (bpf *bpf) SubDir() string {
291 return bpf.properties.Sub_dir
292}
293
Colin Cross41955e82019-05-29 14:40:35 -0700294var _ android.OutputFileProducer = (*bpf)(nil)
Jaewoong Jung5f3fb4b2018-12-13 15:01:46 -0800295
markchien2f59ec92020-09-02 16:23:38 +0800296func BpfFactory() android.Module {
Colin Cross38406592018-05-17 11:17:01 -0700297 module := &bpf{}
298
299 module.AddProperties(&module.properties)
300
301 android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibCommon)
Zi Wangb3cb38c2022-09-23 16:36:11 -0700302 android.InitBazelModule(module)
Colin Cross38406592018-05-17 11:17:01 -0700303 return module
304}
Zi Wangb3cb38c2022-09-23 16:36:11 -0700305
306type bazelBpfAttributes struct {
307 Srcs bazel.LabelListAttribute
308 Copts bazel.StringListAttribute
309 Absolute_includes bazel.StringListAttribute
310 Btf *bool
311 // TODO(b/249528391): Add support for sub_dir
312}
313
314// bpf bp2build converter
315func (b *bpf) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
316 if ctx.ModuleType() != "bpf" {
317 return
318 }
319
320 srcs := bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, b.properties.Srcs))
321 copts := bazel.MakeStringListAttribute(b.properties.Cflags)
322 absolute_includes := bazel.MakeStringListAttribute(b.properties.Include_dirs)
323 btf := b.properties.Btf
324
325 attrs := bazelBpfAttributes{
326 Srcs: srcs,
327 Copts: copts,
328 Absolute_includes: absolute_includes,
329 Btf: btf,
330 }
331 props := bazel.BazelTargetModuleProperties{
332 Rule_class: "bpf",
333 Bzl_load_location: "//build/bazel/rules/bpf:bpf.bzl",
334 }
335
336 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: b.Name()}, &attrs)
337}