blob: 8fc48983e0a45fe9ef506bff4fe35676d1fc932d [file] [log] [blame]
Mitch Phillipsda9a4632019-07-15 09:34:09 -07001// Copyright 2016 Google Inc. All rights reserved.
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 cc
16
17import (
Mitch Phillips4de896e2019-08-28 16:04:36 -070018 "path/filepath"
Mitch Phillipse1ee1a12019-10-17 19:20:41 -070019 "sort"
Mitch Phillipsa0a5e192019-09-27 14:00:06 -070020 "strings"
Mitch Phillips4de896e2019-08-28 16:04:36 -070021
Victor Chang00c144f2021-02-09 12:30:33 +000022 "github.com/google/blueprint/proptools"
23
Mitch Phillipsda9a4632019-07-15 09:34:09 -070024 "android/soong/android"
25 "android/soong/cc/config"
hamzehc0a671f2021-07-22 12:05:08 -070026 "android/soong/fuzz"
Mitch Phillipsda9a4632019-07-15 09:34:09 -070027)
28
29func init() {
Cory Barkera1da26f2022-06-07 20:12:06 +000030 android.RegisterModuleType("cc_fuzz", LibFuzzFactory)
LaMont Jones0c10e4d2023-05-16 00:58:37 +000031 android.RegisterParallelSingletonType("cc_fuzz_packaging", fuzzPackagingFactory)
David Fufd121fc2023-07-07 18:11:51 +000032 android.RegisterParallelSingletonType("cc_fuzz_presubmit_packaging", fuzzPackagingFactoryPresubmit)
Cory Barkera1da26f2022-06-07 20:12:06 +000033}
34
35type FuzzProperties struct {
Cory Barker9cfcf6d2022-07-22 17:22:02 +000036 FuzzFramework fuzz.Framework `blueprint:"mutated"`
Cory Barkera1da26f2022-06-07 20:12:06 +000037}
38
39type fuzzer struct {
40 Properties FuzzProperties
41}
42
43func (fuzzer *fuzzer) flags(ctx ModuleContext, flags Flags) Flags {
Cory Barker9cfcf6d2022-07-22 17:22:02 +000044 if fuzzer.Properties.FuzzFramework == fuzz.AFL {
45 flags.Local.CFlags = append(flags.Local.CFlags, []string{
46 "-fsanitize-coverage=trace-pc-guard",
47 "-Wno-unused-result",
48 "-Wno-unused-parameter",
49 "-Wno-unused-function",
50 }...)
Cory Barkera1da26f2022-06-07 20:12:06 +000051 }
52
53 return flags
54}
55
56func (fuzzer *fuzzer) props() []interface{} {
57 return []interface{}{&fuzzer.Properties}
58}
59
60func fuzzMutatorDeps(mctx android.TopDownMutatorContext) {
61 currentModule, ok := mctx.Module().(*Module)
62 if !ok {
63 return
64 }
65
Cory Barker9cfcf6d2022-07-22 17:22:02 +000066 if currentModule.fuzzer == nil {
Cory Barkera1da26f2022-06-07 20:12:06 +000067 return
68 }
69
70 mctx.WalkDeps(func(child android.Module, parent android.Module) bool {
71 c, ok := child.(*Module)
72 if !ok {
73 return false
74 }
75
76 if c.sanitize == nil {
77 return false
78 }
79
80 isFuzzerPointer := c.sanitize.getSanitizerBoolPtr(Fuzzer)
81 if isFuzzerPointer == nil || !*isFuzzerPointer {
82 return false
83 }
84
85 if c.fuzzer == nil {
86 return false
87 }
88
Cory Barker9cfcf6d2022-07-22 17:22:02 +000089 c.fuzzer.Properties.FuzzFramework = currentModule.fuzzer.Properties.FuzzFramework
Cory Barkera1da26f2022-06-07 20:12:06 +000090 return true
91 })
92}
93
Mitch Phillipsda9a4632019-07-15 09:34:09 -070094// cc_fuzz creates a host/device fuzzer binary. Host binaries can be found at
95// $ANDROID_HOST_OUT/fuzz/, and device binaries can be found at /data/fuzz on
96// your device, or $ANDROID_PRODUCT_OUT/data/fuzz in your build tree.
Cory Barkera1da26f2022-06-07 20:12:06 +000097func LibFuzzFactory() android.Module {
Cory Barker9cfcf6d2022-07-22 17:22:02 +000098 module := NewFuzzer(android.HostAndDeviceSupported)
Aditya Choudhary87b2ab22023-11-17 15:27:06 +000099 module.testModule = true
Cory Barkera1da26f2022-06-07 20:12:06 +0000100 return module.Init()
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700101}
102
103type fuzzBinary struct {
104 *binaryDecorator
105 *baseCompiler
Cory Barkera1da26f2022-06-07 20:12:06 +0000106 fuzzPackagedModule fuzz.FuzzPackagedModule
hamzeh41ad8812021-07-07 14:00:07 -0700107 installedSharedDeps []string
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000108 sharedLibraries android.RuleBuilderInstalls
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700109}
110
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400111func (fuzz *fuzzBinary) fuzzBinary() bool {
112 return true
113}
114
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700115func (fuzz *fuzzBinary) linkerProps() []interface{} {
116 props := fuzz.binaryDecorator.linkerProps()
hamzeh41ad8812021-07-07 14:00:07 -0700117 props = append(props, &fuzz.fuzzPackagedModule.FuzzProperties)
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000118
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700119 return props
120}
121
122func (fuzz *fuzzBinary) linkerInit(ctx BaseModuleContext) {
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700123 fuzz.binaryDecorator.linkerInit(ctx)
124}
125
Cory Barkera1da26f2022-06-07 20:12:06 +0000126func (fuzzBin *fuzzBinary) linkerDeps(ctx DepsContext, deps Deps) Deps {
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000127 if ctx.Config().Getenv("FUZZ_FRAMEWORK") == "AFL" {
Cory Barkera1da26f2022-06-07 20:12:06 +0000128 deps.HeaderLibs = append(deps.HeaderLibs, "libafl_headers")
Cory Barkera1da26f2022-06-07 20:12:06 +0000129 } else {
130 deps.StaticLibs = append(deps.StaticLibs, config.LibFuzzerRuntimeLibrary(ctx.toolchain()))
Kris Alderd406da12022-10-21 09:34:21 -0700131 // Fuzzers built with HWASAN should use the interceptors for better
132 // mutation based on signals in strcmp, memcpy, etc. This is only needed for
133 // fuzz targets, not generic HWASAN-ified binaries or libraries.
134 if module, ok := ctx.Module().(*Module); ok {
135 if module.IsSanitizerEnabled(Hwasan) {
136 deps.StaticLibs = append(deps.StaticLibs, config.LibFuzzerRuntimeInterceptors(ctx.toolchain()))
137 }
138 }
Cory Barkera1da26f2022-06-07 20:12:06 +0000139 }
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000140
141 deps = fuzzBin.binaryDecorator.linkerDeps(ctx, deps)
142 return deps
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700143}
144
145func (fuzz *fuzzBinary) linkerFlags(ctx ModuleContext, flags Flags) Flags {
146 flags = fuzz.binaryDecorator.linkerFlags(ctx, flags)
Mitch Phillips1f7f54f2019-11-14 14:50:47 -0800147 // RunPaths on devices isn't instantiated by the base linker. `../lib` for
148 // installed fuzz targets (both host and device), and `./lib` for fuzz
149 // target packages.
Mitch Phillips1f7f54f2019-11-14 14:50:47 -0800150 flags.Local.LdFlags = append(flags.Local.LdFlags, `-Wl,-rpath,\$$ORIGIN/lib`)
Cory Barkera1da26f2022-06-07 20:12:06 +0000151
Kris Alderc2634812022-10-25 10:58:59 -0700152 // When running on device, fuzz targets with vendor: true set will be in
153 // fuzzer_name/vendor/fuzzer_name (note the extra 'vendor' and thus need to
154 // link with libraries in ../../lib/. Non-vendor binaries only need to look
155 // one level up, in ../lib/.
156 if ctx.inVendor() {
157 flags.Local.LdFlags = append(flags.Local.LdFlags, `-Wl,-rpath,\$$ORIGIN/../../lib`)
158 } else {
159 flags.Local.LdFlags = append(flags.Local.LdFlags, `-Wl,-rpath,\$$ORIGIN/../lib`)
160 }
161
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700162 return flags
163}
164
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400165// IsValidSharedDependency takes a module and determines if it is a unique shared library
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700166// that should be installed in the fuzz target output directories. This function
167// returns true, unless:
Colin Crossd079e0b2022-08-16 10:27:33 -0700168// - The module is not an installable shared library, or
169// - The module is a header or stub, or
170// - The module is a prebuilt and its source is available, or
171// - The module is a versioned member of an SDK snapshot.
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400172func IsValidSharedDependency(dependency android.Module) bool {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700173 // TODO(b/144090547): We should be parsing these modules using
174 // ModuleDependencyTag instead of the current brute-force checking.
175
Colin Cross31076b32020-10-23 17:22:06 -0700176 linkable, ok := dependency.(LinkableInterface)
177 if !ok || !linkable.CcLibraryInterface() {
178 // Discard non-linkables.
179 return false
180 }
181
182 if !linkable.Shared() {
183 // Discard static libs.
184 return false
185 }
186
Colin Cross31076b32020-10-23 17:22:06 -0700187 if lib := moduleLibraryInterface(dependency); lib != nil && lib.buildStubs() && linkable.CcLibrary() {
Mitch Phillipsf50bddb2019-11-12 14:03:31 -0800188 // Discard stubs libs (only CCLibrary variants). Prebuilt libraries should not
189 // be excluded on the basis of they're not CCLibrary()'s.
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700190 return false
191 }
192
Mitch Phillipsf50bddb2019-11-12 14:03:31 -0800193 // We discarded module stubs libraries above, but the LLNDK prebuilts stubs
194 // libraries must be handled differently - by looking for the stubDecorator.
195 // Discard LLNDK prebuilts stubs as well.
196 if ccLibrary, isCcLibrary := dependency.(*Module); isCcLibrary {
197 if _, isLLndkStubLibrary := ccLibrary.linker.(*stubDecorator); isLLndkStubLibrary {
198 return false
199 }
Victor Chang00c144f2021-02-09 12:30:33 +0000200 // Discard installable:false libraries because they are expected to be absent
201 // in runtime.
Colin Cross1bc94122021-10-28 13:25:54 -0700202 if !proptools.BoolDefault(ccLibrary.Installable(), true) {
Victor Chang00c144f2021-02-09 12:30:33 +0000203 return false
204 }
Mitch Phillipsf50bddb2019-11-12 14:03:31 -0800205 }
206
Martin Stjernholm02460ab2020-10-06 02:36:43 +0100207 // If the same library is present both as source and a prebuilt we must pick
208 // only one to avoid a conflict. Always prefer the source since the prebuilt
209 // probably won't be built with sanitizers enabled.
Paul Duffinf7c99f52021-04-28 10:41:21 +0100210 if prebuilt := android.GetEmbeddedPrebuilt(dependency); prebuilt != nil && prebuilt.SourceExists() {
Martin Stjernholm02460ab2020-10-06 02:36:43 +0100211 return false
212 }
213
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700214 return true
215}
216
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500217func SharedLibraryInstallLocation(
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000218 libraryBase string, isHost bool, fuzzDir string, archString string) string {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700219 installLocation := "$(PRODUCT_OUT)/data"
220 if isHost {
221 installLocation = "$(HOST_OUT)"
222 }
223 installLocation = filepath.Join(
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000224 installLocation, fuzzDir, archString, "lib", libraryBase)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700225 return installLocation
226}
227
Mitch Phillips0bf97132020-03-06 09:38:12 -0800228// Get the device-only shared library symbols install directory.
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000229func SharedLibrarySymbolsInstallLocation(libraryBase string, fuzzDir string, archString string) string {
230 return filepath.Join("$(PRODUCT_OUT)/symbols/data/", fuzzDir, archString, "/lib/", libraryBase)
Mitch Phillips0bf97132020-03-06 09:38:12 -0800231}
232
Cory Barkera1da26f2022-06-07 20:12:06 +0000233func (fuzzBin *fuzzBinary) install(ctx ModuleContext, file android.Path) {
234 installBase := "fuzz"
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -0700235
Cory Barkera1da26f2022-06-07 20:12:06 +0000236 fuzzBin.binaryDecorator.baseInstaller.dir = filepath.Join(
237 installBase, ctx.Target().Arch.ArchType.String(), ctx.ModuleName())
238 fuzzBin.binaryDecorator.baseInstaller.dir64 = filepath.Join(
239 installBase, ctx.Target().Arch.ArchType.String(), ctx.ModuleName())
240 fuzzBin.binaryDecorator.baseInstaller.install(ctx, file)
241
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500242 fuzzBin.fuzzPackagedModule = PackageFuzzModule(ctx, fuzzBin.fuzzPackagedModule, pctx)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700243
244 // Grab the list of required shared libraries.
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000245 fuzzBin.sharedLibraries, _ = CollectAllSharedDependencies(ctx)
Colin Crossdc809f92019-11-20 15:58:32 -0800246
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000247 for _, ruleBuilderInstall := range fuzzBin.sharedLibraries {
248 install := ruleBuilderInstall.To
Cory Barkera1da26f2022-06-07 20:12:06 +0000249 fuzzBin.installedSharedDeps = append(fuzzBin.installedSharedDeps,
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500250 SharedLibraryInstallLocation(
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000251 install, ctx.Host(), installBase, ctx.Arch().ArchType.String()))
Mitch Phillips0bf97132020-03-06 09:38:12 -0800252
253 // Also add the dependency on the shared library symbols dir.
254 if !ctx.Host() {
Cory Barkera1da26f2022-06-07 20:12:06 +0000255 fuzzBin.installedSharedDeps = append(fuzzBin.installedSharedDeps,
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000256 SharedLibrarySymbolsInstallLocation(install, installBase, ctx.Arch().ArchType.String()))
Mitch Phillips0bf97132020-03-06 09:38:12 -0800257 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700258 }
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700259}
260
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500261func PackageFuzzModule(ctx android.ModuleContext, fuzzPackagedModule fuzz.FuzzPackagedModule, pctx android.PackageContext) fuzz.FuzzPackagedModule {
262 fuzzPackagedModule.Corpus = android.PathsForModuleSrc(ctx, fuzzPackagedModule.FuzzProperties.Corpus)
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500263 intermediateDir := android.PathForModuleOut(ctx, "corpus")
Inseob Kim3b244062023-07-11 13:31:36 +0900264
265 // Create one rule per file to avoid MAX_ARG_STRLEN hardlimit.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500266 for _, entry := range fuzzPackagedModule.Corpus {
Inseob Kim3b244062023-07-11 13:31:36 +0900267 ctx.Build(pctx, android.BuildParams{
268 Rule: android.Cp,
269 Output: intermediateDir.Join(ctx, entry.Base()),
270 Input: entry,
271 })
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500272 }
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500273 fuzzPackagedModule.CorpusIntermediateDir = intermediateDir
274
275 fuzzPackagedModule.Data = android.PathsForModuleSrc(ctx, fuzzPackagedModule.FuzzProperties.Data)
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500276 intermediateDir = android.PathForModuleOut(ctx, "data")
Inseob Kim3b244062023-07-11 13:31:36 +0900277
278 // Create one rule per file to avoid MAX_ARG_STRLEN hardlimit.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500279 for _, entry := range fuzzPackagedModule.Data {
Inseob Kim3b244062023-07-11 13:31:36 +0900280 ctx.Build(pctx, android.BuildParams{
281 Rule: android.Cp,
282 Output: intermediateDir.Join(ctx, entry.Rel()),
283 Input: entry,
284 })
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500285 }
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500286 fuzzPackagedModule.DataIntermediateDir = intermediateDir
287
288 if fuzzPackagedModule.FuzzProperties.Dictionary != nil {
289 fuzzPackagedModule.Dictionary = android.PathForModuleSrc(ctx, *fuzzPackagedModule.FuzzProperties.Dictionary)
290 if fuzzPackagedModule.Dictionary.Ext() != ".dict" {
291 ctx.PropertyErrorf("dictionary",
292 "Fuzzer dictionary %q does not have '.dict' extension",
293 fuzzPackagedModule.Dictionary.String())
294 }
295 }
296
297 if fuzzPackagedModule.FuzzProperties.Fuzz_config != nil {
298 configPath := android.PathForModuleOut(ctx, "config").Join(ctx, "config.json")
299 android.WriteFileRule(ctx, configPath, fuzzPackagedModule.FuzzProperties.Fuzz_config.String())
300 fuzzPackagedModule.Config = configPath
301 }
302 return fuzzPackagedModule
303}
304
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000305func NewFuzzer(hod android.HostOrDeviceSupported) *Module {
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400306 module, binary := newBinary(hod, false)
Cory Barkera1da26f2022-06-07 20:12:06 +0000307 baseInstallerPath := "fuzz"
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700308
Cory Barkera1da26f2022-06-07 20:12:06 +0000309 binary.baseInstaller = NewBaseInstaller(baseInstallerPath, baseInstallerPath, InstallInData)
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700310
Cory Barkera1da26f2022-06-07 20:12:06 +0000311 fuzzBin := &fuzzBinary{
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700312 binaryDecorator: binary,
313 baseCompiler: NewBaseCompiler(),
314 }
Cory Barkera1da26f2022-06-07 20:12:06 +0000315 module.compiler = fuzzBin
316 module.linker = fuzzBin
317 module.installer = fuzzBin
Colin Crosseec9b282019-07-18 16:20:52 -0700318
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000319 module.fuzzer.Properties.FuzzFramework = fuzz.LibFuzzer
320
Colin Crosseec9b282019-07-18 16:20:52 -0700321 // The fuzzer runtime is not present for darwin host modules, disable cc_fuzz modules when targeting darwin.
322 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400323
324 extraProps := struct {
325 Sanitize struct {
326 Fuzzer *bool
327 }
Colin Crosseec9b282019-07-18 16:20:52 -0700328 Target struct {
329 Darwin struct {
330 Enabled *bool
331 }
Alex Light71123ec2019-07-24 13:34:19 -0700332 Linux_bionic struct {
333 Enabled *bool
334 }
Colin Crosseec9b282019-07-18 16:20:52 -0700335 }
336 }{}
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400337 extraProps.Sanitize.Fuzzer = BoolPtr(true)
338 extraProps.Target.Darwin.Enabled = BoolPtr(false)
339 extraProps.Target.Linux_bionic.Enabled = BoolPtr(false)
340 ctx.AppendProperties(&extraProps)
Cory Barkera1da26f2022-06-07 20:12:06 +0000341
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000342 targetFramework := fuzz.GetFramework(ctx, fuzz.Cc)
343 if !fuzz.IsValidFrameworkForModule(targetFramework, fuzz.Cc, fuzzBin.fuzzPackagedModule.FuzzProperties.Fuzzing_frameworks) {
344 ctx.Module().Disable()
345 return
346 }
347
348 if targetFramework == fuzz.AFL {
349 fuzzBin.baseCompiler.Properties.Srcs = append(fuzzBin.baseCompiler.Properties.Srcs, ":aflpp_driver", ":afl-compiler-rt")
350 module.fuzzer.Properties.FuzzFramework = fuzz.AFL
351 }
352 })
Cory Barker74aea6c2022-08-08 15:55:12 +0000353
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700354 return module
355}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700356
357// Responsible for generating GNU Make rules that package fuzz targets into
358// their architecture & target/host specific zip file.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500359type ccRustFuzzPackager struct {
hamzehc0a671f2021-07-22 12:05:08 -0700360 fuzz.FuzzPackager
Cole Faust06ea5312023-10-18 17:38:40 -0700361 fuzzPackagingArchModules string
362 fuzzTargetSharedDepsInstallPairs string
363 allFuzzTargetsName string
364 onlyIncludePresubmits bool
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700365}
366
367func fuzzPackagingFactory() android.Singleton {
Cory Barkera1da26f2022-06-07 20:12:06 +0000368
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500369 fuzzPackager := &ccRustFuzzPackager{
Cory Barkera1da26f2022-06-07 20:12:06 +0000370 fuzzPackagingArchModules: "SOONG_FUZZ_PACKAGING_ARCH_MODULES",
371 fuzzTargetSharedDepsInstallPairs: "FUZZ_TARGET_SHARED_DEPS_INSTALL_PAIRS",
372 allFuzzTargetsName: "ALL_FUZZ_TARGETS",
Cole Faust06ea5312023-10-18 17:38:40 -0700373 onlyIncludePresubmits: false,
David Fufd121fc2023-07-07 18:11:51 +0000374 }
375 return fuzzPackager
376}
377
378func fuzzPackagingFactoryPresubmit() android.Singleton {
379
380 fuzzPackager := &ccRustFuzzPackager{
381 fuzzPackagingArchModules: "SOONG_PRESUBMIT_FUZZ_PACKAGING_ARCH_MODULES",
382 fuzzTargetSharedDepsInstallPairs: "PRESUBMIT_FUZZ_TARGET_SHARED_DEPS_INSTALL_PAIRS",
383 allFuzzTargetsName: "ALL_PRESUBMIT_FUZZ_TARGETS",
Cole Faust06ea5312023-10-18 17:38:40 -0700384 onlyIncludePresubmits: true,
Cory Barkera1da26f2022-06-07 20:12:06 +0000385 }
Cory Barkera1da26f2022-06-07 20:12:06 +0000386 return fuzzPackager
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700387}
388
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500389func (s *ccRustFuzzPackager) GenerateBuildActions(ctx android.SingletonContext) {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700390 // Map between each architecture + host/device combination, and the files that
391 // need to be packaged (in the tuple of {source file, destination folder in
392 // archive}).
hamzehc0a671f2021-07-22 12:05:08 -0700393 archDirs := make(map[fuzz.ArchOs][]fuzz.FileToZip)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700394
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700395 // List of individual fuzz targets, so that 'make fuzz' also installs the targets
396 // to the correct output directories as well.
hamzeh41ad8812021-07-07 14:00:07 -0700397 s.FuzzTargets = make(map[string]bool)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700398
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400399 // Map tracking whether each shared library has an install rule to avoid duplicate install rules from
400 // multiple fuzzers that depend on the same shared library.
401 sharedLibraryInstalled := make(map[string]bool)
402
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700403 ctx.VisitAllModules(func(module android.Module) {
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500404 ccModule, ok := module.(LinkableInterface)
405 if !ok || ccModule.PreventInstall() {
hamzeh41ad8812021-07-07 14:00:07 -0700406 return
407 }
hamzeh41ad8812021-07-07 14:00:07 -0700408 // Discard non-fuzz targets.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500409 if ok := fuzz.IsValid(ccModule.FuzzModuleStruct()); !ok {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700410 return
411 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700412
Cory Barkera1da26f2022-06-07 20:12:06 +0000413 sharedLibsInstallDirPrefix := "lib"
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500414 if !ccModule.IsFuzzModule() {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700415 return
416 }
417
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700418 hostOrTargetString := "target"
Colin Cross64a4a5f2023-05-16 17:54:27 -0700419 if ccModule.Target().HostCross {
420 hostOrTargetString = "host_cross"
421 } else if ccModule.Host() {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700422 hostOrTargetString = "host"
423 }
David Fufd121fc2023-07-07 18:11:51 +0000424 if s.onlyIncludePresubmits == true {
425 hostOrTargetString = "presubmit-" + hostOrTargetString
426 }
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700427
Cory Barkera1da26f2022-06-07 20:12:06 +0000428 fpm := fuzz.FuzzPackagedModule{}
429 if ok {
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500430 fpm = ccModule.FuzzPackagedModule()
Cory Barkera1da26f2022-06-07 20:12:06 +0000431 }
432
433 intermediatePath := "fuzz"
Cory Barkera1da26f2022-06-07 20:12:06 +0000434
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500435 archString := ccModule.Target().Arch.ArchType.String()
Cory Barkera1da26f2022-06-07 20:12:06 +0000436 archDir := android.PathForIntermediates(ctx, intermediatePath, hostOrTargetString, archString)
hamzehc0a671f2021-07-22 12:05:08 -0700437 archOs := fuzz.ArchOs{HostOrTarget: hostOrTargetString, Arch: archString, Dir: archDir.String()}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700438
hamzehc0a671f2021-07-22 12:05:08 -0700439 var files []fuzz.FileToZip
Colin Crossf1a035e2020-11-16 17:32:30 -0800440 builder := android.NewRuleBuilder(pctx, ctx)
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800441
hamzeh41ad8812021-07-07 14:00:07 -0700442 // Package the corpus, data, dict and config into a zipfile.
Cory Barkera1da26f2022-06-07 20:12:06 +0000443 files = s.PackageArtifacts(ctx, module, fpm, archDir, builder)
Tri Voad172d82019-11-27 13:45:45 -0800444
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400445 // Package shared libraries
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500446 files = append(files, GetSharedLibsToZip(ccModule.FuzzSharedLibraries(), ccModule, &s.FuzzPackager, archString, sharedLibsInstallDirPrefix, &sharedLibraryInstalled)...)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700447
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700448 // The executable.
Colin Cross80462dc2023-05-08 15:09:31 -0700449 files = append(files, fuzz.FileToZip{SourceFilePath: android.OutputFileForModule(ctx, ccModule, "unstripped")})
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700450
David Fufd121fc2023-07-07 18:11:51 +0000451 if s.onlyIncludePresubmits == true {
452 if fpm.FuzzProperties.Fuzz_config == nil {
453 return
454 }
Cole Faust06ea5312023-10-18 17:38:40 -0700455 if !BoolDefault(fpm.FuzzProperties.Fuzz_config.Use_for_presubmit, false) {
David Fufd121fc2023-07-07 18:11:51 +0000456 return
457 }
458 }
Cory Barkera1da26f2022-06-07 20:12:06 +0000459 archDirs[archOs], ok = s.BuildZipFile(ctx, module, fpm, files, builder, archDir, archString, hostOrTargetString, archOs, archDirs)
hamzeh41ad8812021-07-07 14:00:07 -0700460 if !ok {
461 return
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700462 }
463 })
464
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000465 s.CreateFuzzPackage(ctx, archDirs, fuzz.Cc, pctx)
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700466}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700467
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500468func (s *ccRustFuzzPackager) MakeVars(ctx android.MakeVarsContext) {
hamzeh41ad8812021-07-07 14:00:07 -0700469 packages := s.Packages.Strings()
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700470 sort.Strings(packages)
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400471 sort.Strings(s.FuzzPackager.SharedLibInstallStrings)
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700472 // TODO(mitchp): Migrate this to use MakeVarsContext::DistForGoal() when it's
473 // ready to handle phony targets created in Soong. In the meantime, this
474 // exports the phony 'fuzz' target and dependencies on packages to
475 // core/main.mk so that we can use dist-for-goals.
Cory Barkera1da26f2022-06-07 20:12:06 +0000476
477 ctx.Strict(s.fuzzPackagingArchModules, strings.Join(packages, " "))
478
479 ctx.Strict(s.fuzzTargetSharedDepsInstallPairs,
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400480 strings.Join(s.FuzzPackager.SharedLibInstallStrings, " "))
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700481
482 // Preallocate the slice of fuzz targets to minimise memory allocations.
Cory Barkera1da26f2022-06-07 20:12:06 +0000483 s.PreallocateSlice(ctx, s.allFuzzTargetsName)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700484}
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400485
486// GetSharedLibsToZip finds and marks all the transiently-dependent shared libraries for
487// packaging.
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000488func GetSharedLibsToZip(sharedLibraries android.RuleBuilderInstalls, module LinkableInterface, s *fuzz.FuzzPackager, archString string, destinationPathPrefix string, sharedLibraryInstalled *map[string]bool) []fuzz.FileToZip {
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400489 var files []fuzz.FileToZip
490
Cory Barkera1da26f2022-06-07 20:12:06 +0000491 fuzzDir := "fuzz"
Cory Barkera1da26f2022-06-07 20:12:06 +0000492
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000493 for _, ruleBuilderInstall := range sharedLibraries {
494 library := ruleBuilderInstall.From
495 install := ruleBuilderInstall.To
Colin Cross80462dc2023-05-08 15:09:31 -0700496 files = append(files, fuzz.FileToZip{
497 SourceFilePath: library,
498 DestinationPathPrefix: destinationPathPrefix,
499 DestinationPath: install,
500 })
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400501
502 // For each architecture-specific shared library dependency, we need to
503 // install it to the output directory. Setup the install destination here,
504 // which will be used by $(copy-many-files) in the Make backend.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500505 installDestination := SharedLibraryInstallLocation(
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000506 install, module.Host(), fuzzDir, archString)
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400507 if (*sharedLibraryInstalled)[installDestination] {
508 continue
509 }
510 (*sharedLibraryInstalled)[installDestination] = true
511
512 // Escape all the variables, as the install destination here will be called
513 // via. $(eval) in Make.
514 installDestination = strings.ReplaceAll(
515 installDestination, "$", "$$")
516 s.SharedLibInstallStrings = append(s.SharedLibInstallStrings,
517 library.String()+":"+installDestination)
518
519 // Ensure that on device, the library is also reinstalled to the /symbols/
520 // dir. Symbolized DSO's are always installed to the device when fuzzing, but
521 // we want symbolization tools (like `stack`) to be able to find the symbols
522 // in $ANDROID_PRODUCT_OUT/symbols automagically.
523 if !module.Host() {
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000524 symbolsInstallDestination := SharedLibrarySymbolsInstallLocation(install, fuzzDir, archString)
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400525 symbolsInstallDestination = strings.ReplaceAll(symbolsInstallDestination, "$", "$$")
526 s.SharedLibInstallStrings = append(s.SharedLibInstallStrings,
527 library.String()+":"+symbolsInstallDestination)
528 }
529 }
530 return files
531}
Colin Cross31d89b42022-10-04 16:35:39 -0700532
533// CollectAllSharedDependencies search over the provided module's dependencies using
534// VisitDirectDeps and WalkDeps to enumerate all shared library dependencies.
535// VisitDirectDeps is used first to avoid incorrectly using the core libraries (sanitizer
536// runtimes, libc, libdl, etc.) from a dependency. This may cause issues when dependencies
537// have explicit sanitizer tags, as we may get a dependency on an unsanitized libc, etc.
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000538func CollectAllSharedDependencies(ctx android.ModuleContext) (android.RuleBuilderInstalls, []android.Module) {
Colin Cross31d89b42022-10-04 16:35:39 -0700539 seen := make(map[string]bool)
540 recursed := make(map[string]bool)
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000541 deps := []android.Module{}
Colin Cross31d89b42022-10-04 16:35:39 -0700542
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000543 var sharedLibraries android.RuleBuilderInstalls
Colin Cross31d89b42022-10-04 16:35:39 -0700544
545 // Enumerate the first level of dependencies, as we discard all non-library
546 // modules in the BFS loop below.
547 ctx.VisitDirectDeps(func(dep android.Module) {
548 if !IsValidSharedDependency(dep) {
549 return
550 }
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000551 if !ctx.OtherModuleHasProvider(dep, SharedLibraryInfoProvider) {
552 return
553 }
Colin Cross31d89b42022-10-04 16:35:39 -0700554 if seen[ctx.OtherModuleName(dep)] {
555 return
556 }
557 seen[ctx.OtherModuleName(dep)] = true
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000558 deps = append(deps, dep)
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000559
560 sharedLibraryInfo := ctx.OtherModuleProvider(dep, SharedLibraryInfoProvider).(SharedLibraryInfo)
561 installDestination := sharedLibraryInfo.SharedLibrary.Base()
562 ruleBuilderInstall := android.RuleBuilderInstall{android.OutputFileForModule(ctx, dep, "unstripped"), installDestination}
563 sharedLibraries = append(sharedLibraries, ruleBuilderInstall)
Colin Cross31d89b42022-10-04 16:35:39 -0700564 })
565
566 ctx.WalkDeps(func(child, parent android.Module) bool {
Ivan Lozano61c02cc2023-06-09 14:06:44 -0400567
568 // If this is a Rust module which is not rust_ffi_shared, we still want to bundle any transitive
569 // shared dependencies (even for rust_ffi_static)
570 if rustmod, ok := child.(LinkableInterface); ok && rustmod.RustLibraryInterface() && !rustmod.Shared() {
571 if recursed[ctx.OtherModuleName(child)] {
572 return false
573 }
574 recursed[ctx.OtherModuleName(child)] = true
575 return true
576 }
577
Colin Cross31d89b42022-10-04 16:35:39 -0700578 if !IsValidSharedDependency(child) {
579 return false
580 }
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000581 if !ctx.OtherModuleHasProvider(child, SharedLibraryInfoProvider) {
582 return false
583 }
Colin Cross31d89b42022-10-04 16:35:39 -0700584 if !seen[ctx.OtherModuleName(child)] {
585 seen[ctx.OtherModuleName(child)] = true
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000586 deps = append(deps, child)
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000587
588 sharedLibraryInfo := ctx.OtherModuleProvider(child, SharedLibraryInfoProvider).(SharedLibraryInfo)
589 installDestination := sharedLibraryInfo.SharedLibrary.Base()
590 ruleBuilderInstall := android.RuleBuilderInstall{android.OutputFileForModule(ctx, child, "unstripped"), installDestination}
591 sharedLibraries = append(sharedLibraries, ruleBuilderInstall)
Colin Cross31d89b42022-10-04 16:35:39 -0700592 }
593
594 if recursed[ctx.OtherModuleName(child)] {
595 return false
596 }
597 recursed[ctx.OtherModuleName(child)] = true
598 return true
599 })
600
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000601 return sharedLibraries, deps
Colin Cross31d89b42022-10-04 16:35:39 -0700602}