Merge "Add option to generate BTF debug info for bpf programs" am: c7afdefa26 am: e375f4c53e am: aae5c94a71

Original change: https://android-review.googlesource.com/c/platform/build/soong/+/1909413

Change-Id: I44c4b8bb79a9bf3ae020cfeea6d66d267075ad44
diff --git a/bpf/bpf.go b/bpf/bpf.go
index 187b4db..a4999e5 100644
--- a/bpf/bpf.go
+++ b/bpf/bpf.go
@@ -23,6 +23,7 @@
 	_ "android/soong/cc/config"
 
 	"github.com/google/blueprint"
+	"github.com/google/blueprint/proptools"
 )
 
 func init() {
@@ -41,6 +42,14 @@
 			CommandDeps: []string{"$ccCmd"},
 		},
 		"ccCmd", "cFlags")
+
+	stripRule = pctx.AndroidStaticRule("stripRule",
+		blueprint.RuleParams{
+			Command: `$stripCmd --strip-unneeded --remove-section=.rel.BTF ` +
+				`--remove-section=.rel.BTF.ext --remove-section=.BTF.ext $in -o $out`,
+			CommandDeps: []string{"$stripCmd"},
+		},
+		"stripCmd")
 )
 
 func registerBpfBuildComponents(ctx android.RegistrationContext) {
@@ -64,6 +73,8 @@
 	Cflags       []string
 	Include_dirs []string
 	Sub_dir      string
+	// If set to true, generate BTF debug info for maps & programs
+	Btf          *bool
 }
 
 type bpf struct {
@@ -99,10 +110,14 @@
 
 	cflags = append(cflags, bpf.properties.Cflags...)
 
+	if proptools.Bool(bpf.properties.Btf) {
+		cflags = append(cflags, "-g")
+	}
+
 	srcs := android.PathsForModuleSrc(ctx, bpf.properties.Srcs)
 
 	for _, src := range srcs {
-		obj := android.ObjPathWithExt(ctx, "", src, "o")
+		obj := android.ObjPathWithExt(ctx, "unstripped", src, "o")
 
 		ctx.Build(pctx, android.BuildParams{
 			Rule:   ccRule,
@@ -114,7 +129,21 @@
 			},
 		})
 
-		bpf.objs = append(bpf.objs, obj.WithoutRel())
+		if proptools.Bool(bpf.properties.Btf) {
+			objStripped := android.ObjPathWithExt(ctx, "", src, "o")
+			ctx.Build(pctx, android.BuildParams{
+				Rule: stripRule,
+				Input: obj,
+				Output: objStripped,
+				Args: map[string]string{
+					"stripCmd": "${config.ClangBin}/llvm-strip",
+				},
+			})
+			bpf.objs = append(bpf.objs, objStripped.WithoutRel())
+		} else {
+			bpf.objs = append(bpf.objs, obj.WithoutRel())
+		}
+
 	}
 }