blob: 8c0d28be20061658e2ca303fb7a30cdf0942187b [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"
Connor O'Brien6a288bc2022-11-10 13:58:48 -080027 "android/soong/cc"
Colin Cross38406592018-05-17 11:17:01 -070028
29 "github.com/google/blueprint"
Connor O'Brien25739652021-12-02 20:09:45 -080030 "github.com/google/blueprint/proptools"
Colin Cross38406592018-05-17 11:17:01 -070031)
32
33func init() {
Paul Duffin12c7eb82021-02-24 18:51:54 +000034 registerBpfBuildComponents(android.InitRegistrationContext)
Colin Cross38406592018-05-17 11:17:01 -070035 pctx.Import("android/soong/cc/config")
Connor O'Brien6a288bc2022-11-10 13:58:48 -080036 pctx.StaticVariable("relPwd", cc.PwdPrefix())
Colin Cross38406592018-05-17 11:17:01 -070037}
38
39var (
40 pctx = android.NewPackageContext("android/soong/bpf")
41
Ramy Medhat8ea054a2020-01-27 14:19:44 -050042 ccRule = pctx.AndroidRemoteStaticRule("ccRule", android.RemoteRuleSupports{Goma: true},
Colin Cross38406592018-05-17 11:17:01 -070043 blueprint.RuleParams{
44 Depfile: "${out}.d",
45 Deps: blueprint.DepsGCC,
Connor O'Brien3e739cf2022-08-17 15:45:52 -070046 Command: "$relPwd $ccCmd --target=bpf -c $cFlags -MD -MF ${out}.d -o $out $in",
Colin Cross38406592018-05-17 11:17:01 -070047 CommandDeps: []string{"$ccCmd"},
48 },
49 "ccCmd", "cFlags")
Connor O'Brien25739652021-12-02 20:09:45 -080050
51 stripRule = pctx.AndroidStaticRule("stripRule",
52 blueprint.RuleParams{
53 Command: `$stripCmd --strip-unneeded --remove-section=.rel.BTF ` +
54 `--remove-section=.rel.BTF.ext --remove-section=.BTF.ext $in -o $out`,
55 CommandDeps: []string{"$stripCmd"},
56 },
57 "stripCmd")
Colin Cross38406592018-05-17 11:17:01 -070058)
59
Paul Duffin12c7eb82021-02-24 18:51:54 +000060func registerBpfBuildComponents(ctx android.RegistrationContext) {
61 ctx.RegisterModuleType("bpf", BpfFactory)
62}
63
64var PrepareForTestWithBpf = android.FixtureRegisterWithContext(registerBpfBuildComponents)
65
markchien2f59ec92020-09-02 16:23:38 +080066// BpfModule interface is used by the apex package to gather information from a bpf module.
67type BpfModule interface {
68 android.Module
69
70 OutputFiles(tag string) (android.Paths, error)
Ken Chenfad7f9d2021-11-10 22:02:57 +080071
72 // Returns the sub install directory if the bpf module is included by apex.
73 SubDir() string
markchien2f59ec92020-09-02 16:23:38 +080074}
75
Colin Cross38406592018-05-17 11:17:01 -070076type BpfProperties struct {
Zi Wang4877c722022-08-11 18:05:13 +000077 // source paths to the files.
78 Srcs []string `android:"path"`
79
80 // additional cflags that should be used to build the bpf variant of
81 // the C/C++ module.
82 Cflags []string
83
84 // directories (relative to the root of the source tree) that will
85 // be added to the include paths using -I.
Colin Cross38406592018-05-17 11:17:01 -070086 Include_dirs []string
Zi Wang4877c722022-08-11 18:05:13 +000087
88 // optional subdirectory under which this module is installed into.
89 Sub_dir string
90
91 // if set to true, generate BTF debug info for maps & programs.
92 Btf *bool
93
Steven Moreland606c5e92019-12-12 14:23:42 -080094 Vendor *bool
95
96 VendorInternal bool `blueprint:"mutated"`
Colin Cross38406592018-05-17 11:17:01 -070097}
98
99type bpf struct {
100 android.ModuleBase
Zi Wangb3cb38c2022-09-23 16:36:11 -0700101 android.BazelModuleBase
Colin Cross38406592018-05-17 11:17:01 -0700102
103 properties BpfProperties
104
105 objs android.Paths
106}
107
Steven Moreland606c5e92019-12-12 14:23:42 -0800108var _ android.ImageInterface = (*bpf)(nil)
109
110func (bpf *bpf) ImageMutatorBegin(ctx android.BaseModuleContext) {}
111
112func (bpf *bpf) CoreVariantNeeded(ctx android.BaseModuleContext) bool {
113 return !proptools.Bool(bpf.properties.Vendor)
114}
115
116func (bpf *bpf) RamdiskVariantNeeded(ctx android.BaseModuleContext) bool {
117 return false
118}
119
120func (bpf *bpf) VendorRamdiskVariantNeeded(ctx android.BaseModuleContext) bool {
121 return false
122}
123
124func (bpf *bpf) DebugRamdiskVariantNeeded(ctx android.BaseModuleContext) bool {
125 return false
126}
127
128func (bpf *bpf) RecoveryVariantNeeded(ctx android.BaseModuleContext) bool {
129 return false
130}
131
132func (bpf *bpf) ExtraImageVariations(ctx android.BaseModuleContext) []string {
133 if proptools.Bool(bpf.properties.Vendor) {
134 return []string{"vendor"}
135 }
136 return nil
137}
138
139func (bpf *bpf) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
140 bpf.properties.VendorInternal = variation == "vendor"
141}
142
Colin Cross38406592018-05-17 11:17:01 -0700143func (bpf *bpf) GenerateAndroidBuildActions(ctx android.ModuleContext) {
144 cflags := []string{
145 "-nostdlibinc",
Kousik Kumarfb0e2512020-03-25 15:01:27 -0700146
147 // Make paths in deps files relative
148 "-no-canonical-prefixes",
149
Colin Cross38406592018-05-17 11:17:01 -0700150 "-O2",
151 "-isystem bionic/libc/include",
152 "-isystem bionic/libc/kernel/uapi",
153 // The architecture doesn't matter here, but asm/types.h is included by linux/types.h.
154 "-isystem bionic/libc/kernel/uapi/asm-arm64",
155 "-isystem bionic/libc/kernel/android/uapi",
Motomu Utsumi44591552023-08-22 12:03:16 +0900156 "-I packages/modules/Connectivity/staticlibs/native/bpf_headers/include/bpf",
Maciej Żenczykowski79f6f752020-02-18 15:38:36 -0800157 // TODO(b/149785767): only give access to specific file with AID_* constants
158 "-I system/core/libcutils/include",
Colin Cross38406592018-05-17 11:17:01 -0700159 "-I " + ctx.ModuleDir(),
160 }
161
162 for _, dir := range android.PathsForSource(ctx, bpf.properties.Include_dirs) {
163 cflags = append(cflags, "-I "+dir.String())
164 }
165
166 cflags = append(cflags, bpf.properties.Cflags...)
167
Connor O'Brien25739652021-12-02 20:09:45 -0800168 if proptools.Bool(bpf.properties.Btf) {
169 cflags = append(cflags, "-g")
Connor O'Brien3e739cf2022-08-17 15:45:52 -0700170 if runtime.GOOS != "darwin" {
171 cflags = append(cflags, "-fdebug-prefix-map=/proc/self/cwd=")
172 }
Connor O'Brien25739652021-12-02 20:09:45 -0800173 }
174
Colin Cross8a497952019-03-05 22:25:09 -0800175 srcs := android.PathsForModuleSrc(ctx, bpf.properties.Srcs)
Colin Cross38406592018-05-17 11:17:01 -0700176
177 for _, src := range srcs {
Ken Chen5372a242022-07-07 17:48:06 +0800178 if strings.ContainsRune(filepath.Base(src.String()), '_') {
179 ctx.ModuleErrorf("invalid character '_' in source name")
180 }
Connor O'Brien25739652021-12-02 20:09:45 -0800181 obj := android.ObjPathWithExt(ctx, "unstripped", src, "o")
Colin Cross38406592018-05-17 11:17:01 -0700182
183 ctx.Build(pctx, android.BuildParams{
Colin Cross815daf92019-05-14 16:05:20 -0700184 Rule: ccRule,
Colin Cross38406592018-05-17 11:17:01 -0700185 Input: src,
186 Output: obj,
187 Args: map[string]string{
188 "cFlags": strings.Join(cflags, " "),
189 "ccCmd": "${config.ClangBin}/clang",
190 },
191 })
192
Connor O'Brien25739652021-12-02 20:09:45 -0800193 if proptools.Bool(bpf.properties.Btf) {
194 objStripped := android.ObjPathWithExt(ctx, "", src, "o")
195 ctx.Build(pctx, android.BuildParams{
Steven Moreland606c5e92019-12-12 14:23:42 -0800196 Rule: stripRule,
197 Input: obj,
Connor O'Brien25739652021-12-02 20:09:45 -0800198 Output: objStripped,
199 Args: map[string]string{
200 "stripCmd": "${config.ClangBin}/llvm-strip",
201 },
202 })
203 bpf.objs = append(bpf.objs, objStripped.WithoutRel())
204 } else {
205 bpf.objs = append(bpf.objs, obj.WithoutRel())
206 }
207
Colin Cross38406592018-05-17 11:17:01 -0700208 }
Aditya Choudhary26df39f2023-11-29 16:42:42 +0000209 ctx.SetProvider(blueprint.SrcsFileProviderKey, blueprint.SrcsFileProviderData{SrcPaths: srcs.Strings()})
Colin Cross38406592018-05-17 11:17:01 -0700210}
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)
Sasha Smundak5c4729d2022-12-01 10:49:23 -0800231 fmt.Fprintln(w, "include $(CLEAR_VARS)", " # bpf.bpf.obj")
Colin Cross38406592018-05-17 11:17:01 -0700232 fmt.Fprintln(w, "LOCAL_MODULE := ", objName)
233 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", obj.String())
234 fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", obj.Base())
235 fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC")
Ken Chenfad7f9d2021-11-10 22:02:57 +0800236 fmt.Fprintln(w, localModulePath)
Colin Cross38406592018-05-17 11:17:01 -0700237 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
238 fmt.Fprintln(w)
239 }
Sasha Smundak5c4729d2022-12-01 10:49:23 -0800240 fmt.Fprintln(w, "include $(CLEAR_VARS)", " # bpf.bpf")
Colin Cross38406592018-05-17 11:17:01 -0700241 fmt.Fprintln(w, "LOCAL_MODULE := ", name)
Sasha Smundakdcb61292022-12-08 10:41:33 -0800242 android.AndroidMkEmitAssignList(w, "LOCAL_REQUIRED_MODULES", names)
Colin Cross38406592018-05-17 11:17:01 -0700243 fmt.Fprintln(w, "include $(BUILD_PHONY_PACKAGE)")
244 },
245 }
246}
247
Zi Wangaa981ed2022-10-04 16:59:31 -0700248var _ android.MixedBuildBuildable = (*bpf)(nil)
249
250func (bpf *bpf) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
251 return true
252}
253
254func (bpf *bpf) QueueBazelCall(ctx android.BaseModuleContext) {
255 bazelCtx := ctx.Config().BazelContext
256 bazelCtx.QueueBazelRequest(
257 bpf.GetBazelLabel(ctx, bpf),
258 cquery.GetOutputFiles,
259 android.GetConfigKey(ctx))
260}
261
262func (bpf *bpf) ProcessBazelQueryResponse(ctx android.ModuleContext) {
263 bazelCtx := ctx.Config().BazelContext
264 objPaths, err := bazelCtx.GetOutputFiles(bpf.GetBazelLabel(ctx, bpf), android.GetConfigKey(ctx))
265 if err != nil {
266 ctx.ModuleErrorf(err.Error())
267 return
268 }
269
270 bazelOuts := android.Paths{}
271 for _, p := range objPaths {
272 bazelOuts = append(bazelOuts, android.PathForBazelOut(ctx, p))
273 }
274 bpf.objs = bazelOuts
275}
276
Colin Cross41955e82019-05-29 14:40:35 -0700277// Implements OutputFileFileProducer interface so that the obj output can be used in the data property
Jaewoong Jung5f3fb4b2018-12-13 15:01:46 -0800278// of other modules.
Colin Cross41955e82019-05-29 14:40:35 -0700279func (bpf *bpf) OutputFiles(tag string) (android.Paths, error) {
280 switch tag {
281 case "":
282 return bpf.objs, nil
283 default:
284 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
285 }
Jaewoong Jung5f3fb4b2018-12-13 15:01:46 -0800286}
287
Ken Chenfad7f9d2021-11-10 22:02:57 +0800288func (bpf *bpf) SubDir() string {
289 return bpf.properties.Sub_dir
290}
291
Colin Cross41955e82019-05-29 14:40:35 -0700292var _ android.OutputFileProducer = (*bpf)(nil)
Jaewoong Jung5f3fb4b2018-12-13 15:01:46 -0800293
markchien2f59ec92020-09-02 16:23:38 +0800294func BpfFactory() android.Module {
Colin Cross38406592018-05-17 11:17:01 -0700295 module := &bpf{}
296
297 module.AddProperties(&module.properties)
298
299 android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibCommon)
Zi Wangb3cb38c2022-09-23 16:36:11 -0700300 android.InitBazelModule(module)
Colin Cross38406592018-05-17 11:17:01 -0700301 return module
302}
Zi Wangb3cb38c2022-09-23 16:36:11 -0700303
304type bazelBpfAttributes struct {
305 Srcs bazel.LabelListAttribute
306 Copts bazel.StringListAttribute
307 Absolute_includes bazel.StringListAttribute
308 Btf *bool
309 // TODO(b/249528391): Add support for sub_dir
310}
311
312// bpf bp2build converter
Chris Parsons637458d2023-09-19 20:09:00 +0000313func (b *bpf) ConvertWithBp2build(ctx android.Bp2buildMutatorContext) {
Zi Wangb3cb38c2022-09-23 16:36:11 -0700314 if ctx.ModuleType() != "bpf" {
315 return
316 }
317
318 srcs := bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, b.properties.Srcs))
319 copts := bazel.MakeStringListAttribute(b.properties.Cflags)
320 absolute_includes := bazel.MakeStringListAttribute(b.properties.Include_dirs)
321 btf := b.properties.Btf
322
323 attrs := bazelBpfAttributes{
324 Srcs: srcs,
325 Copts: copts,
326 Absolute_includes: absolute_includes,
327 Btf: btf,
328 }
329 props := bazel.BazelTargetModuleProperties{
330 Rule_class: "bpf",
331 Bzl_load_location: "//build/bazel/rules/bpf:bpf.bzl",
332 }
333
334 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: b.Name()}, &attrs)
335}