blob: 250c63839630e0357a6ec5d0f3fc1abfdf163bcb [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)
Cory Barkera1da26f2022-06-07 20:12:06 +000099 return module.Init()
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700100}
101
102type fuzzBinary struct {
103 *binaryDecorator
104 *baseCompiler
Cory Barkera1da26f2022-06-07 20:12:06 +0000105 fuzzPackagedModule fuzz.FuzzPackagedModule
hamzeh41ad8812021-07-07 14:00:07 -0700106 installedSharedDeps []string
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000107 sharedLibraries android.RuleBuilderInstalls
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700108}
109
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400110func (fuzz *fuzzBinary) fuzzBinary() bool {
111 return true
112}
113
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700114func (fuzz *fuzzBinary) linkerProps() []interface{} {
115 props := fuzz.binaryDecorator.linkerProps()
hamzeh41ad8812021-07-07 14:00:07 -0700116 props = append(props, &fuzz.fuzzPackagedModule.FuzzProperties)
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000117
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700118 return props
119}
120
121func (fuzz *fuzzBinary) linkerInit(ctx BaseModuleContext) {
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700122 fuzz.binaryDecorator.linkerInit(ctx)
123}
124
Cory Barkera1da26f2022-06-07 20:12:06 +0000125func (fuzzBin *fuzzBinary) linkerDeps(ctx DepsContext, deps Deps) Deps {
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000126 if ctx.Config().Getenv("FUZZ_FRAMEWORK") == "AFL" {
Cory Barkera1da26f2022-06-07 20:12:06 +0000127 deps.HeaderLibs = append(deps.HeaderLibs, "libafl_headers")
Cory Barkera1da26f2022-06-07 20:12:06 +0000128 } else {
129 deps.StaticLibs = append(deps.StaticLibs, config.LibFuzzerRuntimeLibrary(ctx.toolchain()))
Kris Alderd406da12022-10-21 09:34:21 -0700130 // Fuzzers built with HWASAN should use the interceptors for better
131 // mutation based on signals in strcmp, memcpy, etc. This is only needed for
132 // fuzz targets, not generic HWASAN-ified binaries or libraries.
133 if module, ok := ctx.Module().(*Module); ok {
134 if module.IsSanitizerEnabled(Hwasan) {
135 deps.StaticLibs = append(deps.StaticLibs, config.LibFuzzerRuntimeInterceptors(ctx.toolchain()))
136 }
137 }
Cory Barkera1da26f2022-06-07 20:12:06 +0000138 }
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000139
140 deps = fuzzBin.binaryDecorator.linkerDeps(ctx, deps)
141 return deps
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700142}
143
144func (fuzz *fuzzBinary) linkerFlags(ctx ModuleContext, flags Flags) Flags {
145 flags = fuzz.binaryDecorator.linkerFlags(ctx, flags)
Mitch Phillips1f7f54f2019-11-14 14:50:47 -0800146 // RunPaths on devices isn't instantiated by the base linker. `../lib` for
147 // installed fuzz targets (both host and device), and `./lib` for fuzz
148 // target packages.
Mitch Phillips1f7f54f2019-11-14 14:50:47 -0800149 flags.Local.LdFlags = append(flags.Local.LdFlags, `-Wl,-rpath,\$$ORIGIN/lib`)
Cory Barkera1da26f2022-06-07 20:12:06 +0000150
Kris Alderc2634812022-10-25 10:58:59 -0700151 // When running on device, fuzz targets with vendor: true set will be in
152 // fuzzer_name/vendor/fuzzer_name (note the extra 'vendor' and thus need to
153 // link with libraries in ../../lib/. Non-vendor binaries only need to look
154 // one level up, in ../lib/.
155 if ctx.inVendor() {
156 flags.Local.LdFlags = append(flags.Local.LdFlags, `-Wl,-rpath,\$$ORIGIN/../../lib`)
157 } else {
158 flags.Local.LdFlags = append(flags.Local.LdFlags, `-Wl,-rpath,\$$ORIGIN/../lib`)
159 }
160
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700161 return flags
162}
163
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400164// IsValidSharedDependency takes a module and determines if it is a unique shared library
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700165// that should be installed in the fuzz target output directories. This function
166// returns true, unless:
Colin Crossd079e0b2022-08-16 10:27:33 -0700167// - The module is not an installable shared library, or
168// - The module is a header or stub, or
169// - The module is a prebuilt and its source is available, or
170// - The module is a versioned member of an SDK snapshot.
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400171func IsValidSharedDependency(dependency android.Module) bool {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700172 // TODO(b/144090547): We should be parsing these modules using
173 // ModuleDependencyTag instead of the current brute-force checking.
174
Colin Cross31076b32020-10-23 17:22:06 -0700175 linkable, ok := dependency.(LinkableInterface)
176 if !ok || !linkable.CcLibraryInterface() {
177 // Discard non-linkables.
178 return false
179 }
180
181 if !linkable.Shared() {
182 // Discard static libs.
183 return false
184 }
185
Colin Cross31076b32020-10-23 17:22:06 -0700186 if lib := moduleLibraryInterface(dependency); lib != nil && lib.buildStubs() && linkable.CcLibrary() {
Mitch Phillipsf50bddb2019-11-12 14:03:31 -0800187 // Discard stubs libs (only CCLibrary variants). Prebuilt libraries should not
188 // be excluded on the basis of they're not CCLibrary()'s.
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700189 return false
190 }
191
Mitch Phillipsf50bddb2019-11-12 14:03:31 -0800192 // We discarded module stubs libraries above, but the LLNDK prebuilts stubs
193 // libraries must be handled differently - by looking for the stubDecorator.
194 // Discard LLNDK prebuilts stubs as well.
195 if ccLibrary, isCcLibrary := dependency.(*Module); isCcLibrary {
196 if _, isLLndkStubLibrary := ccLibrary.linker.(*stubDecorator); isLLndkStubLibrary {
197 return false
198 }
Victor Chang00c144f2021-02-09 12:30:33 +0000199 // Discard installable:false libraries because they are expected to be absent
200 // in runtime.
Colin Cross1bc94122021-10-28 13:25:54 -0700201 if !proptools.BoolDefault(ccLibrary.Installable(), true) {
Victor Chang00c144f2021-02-09 12:30:33 +0000202 return false
203 }
Mitch Phillipsf50bddb2019-11-12 14:03:31 -0800204 }
205
Martin Stjernholm02460ab2020-10-06 02:36:43 +0100206 // If the same library is present both as source and a prebuilt we must pick
207 // only one to avoid a conflict. Always prefer the source since the prebuilt
208 // probably won't be built with sanitizers enabled.
Paul Duffinf7c99f52021-04-28 10:41:21 +0100209 if prebuilt := android.GetEmbeddedPrebuilt(dependency); prebuilt != nil && prebuilt.SourceExists() {
Martin Stjernholm02460ab2020-10-06 02:36:43 +0100210 return false
211 }
212
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700213 return true
214}
215
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500216func SharedLibraryInstallLocation(
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000217 libraryBase string, isHost bool, fuzzDir string, archString string) string {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700218 installLocation := "$(PRODUCT_OUT)/data"
219 if isHost {
220 installLocation = "$(HOST_OUT)"
221 }
222 installLocation = filepath.Join(
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000223 installLocation, fuzzDir, archString, "lib", libraryBase)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700224 return installLocation
225}
226
Mitch Phillips0bf97132020-03-06 09:38:12 -0800227// Get the device-only shared library symbols install directory.
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000228func SharedLibrarySymbolsInstallLocation(libraryBase string, fuzzDir string, archString string) string {
229 return filepath.Join("$(PRODUCT_OUT)/symbols/data/", fuzzDir, archString, "/lib/", libraryBase)
Mitch Phillips0bf97132020-03-06 09:38:12 -0800230}
231
Cory Barkera1da26f2022-06-07 20:12:06 +0000232func (fuzzBin *fuzzBinary) install(ctx ModuleContext, file android.Path) {
233 installBase := "fuzz"
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -0700234
Cory Barkera1da26f2022-06-07 20:12:06 +0000235 fuzzBin.binaryDecorator.baseInstaller.dir = filepath.Join(
236 installBase, ctx.Target().Arch.ArchType.String(), ctx.ModuleName())
237 fuzzBin.binaryDecorator.baseInstaller.dir64 = filepath.Join(
238 installBase, ctx.Target().Arch.ArchType.String(), ctx.ModuleName())
239 fuzzBin.binaryDecorator.baseInstaller.install(ctx, file)
240
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500241 fuzzBin.fuzzPackagedModule = PackageFuzzModule(ctx, fuzzBin.fuzzPackagedModule, pctx)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700242
243 // Grab the list of required shared libraries.
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000244 fuzzBin.sharedLibraries, _ = CollectAllSharedDependencies(ctx)
Colin Crossdc809f92019-11-20 15:58:32 -0800245
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000246 for _, ruleBuilderInstall := range fuzzBin.sharedLibraries {
247 install := ruleBuilderInstall.To
Cory Barkera1da26f2022-06-07 20:12:06 +0000248 fuzzBin.installedSharedDeps = append(fuzzBin.installedSharedDeps,
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500249 SharedLibraryInstallLocation(
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000250 install, ctx.Host(), installBase, ctx.Arch().ArchType.String()))
Mitch Phillips0bf97132020-03-06 09:38:12 -0800251
252 // Also add the dependency on the shared library symbols dir.
253 if !ctx.Host() {
Cory Barkera1da26f2022-06-07 20:12:06 +0000254 fuzzBin.installedSharedDeps = append(fuzzBin.installedSharedDeps,
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000255 SharedLibrarySymbolsInstallLocation(install, installBase, ctx.Arch().ArchType.String()))
Mitch Phillips0bf97132020-03-06 09:38:12 -0800256 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700257 }
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700258}
259
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500260func PackageFuzzModule(ctx android.ModuleContext, fuzzPackagedModule fuzz.FuzzPackagedModule, pctx android.PackageContext) fuzz.FuzzPackagedModule {
261 fuzzPackagedModule.Corpus = android.PathsForModuleSrc(ctx, fuzzPackagedModule.FuzzProperties.Corpus)
262 builder := android.NewRuleBuilder(pctx, ctx)
263 intermediateDir := android.PathForModuleOut(ctx, "corpus")
264 for _, entry := range fuzzPackagedModule.Corpus {
265 builder.Command().Text("cp").
266 Input(entry).
267 Output(intermediateDir.Join(ctx, entry.Base()))
268 }
269 builder.Build("copy_corpus", "copy corpus")
270 fuzzPackagedModule.CorpusIntermediateDir = intermediateDir
271
272 fuzzPackagedModule.Data = android.PathsForModuleSrc(ctx, fuzzPackagedModule.FuzzProperties.Data)
273 builder = android.NewRuleBuilder(pctx, ctx)
274 intermediateDir = android.PathForModuleOut(ctx, "data")
275 for _, entry := range fuzzPackagedModule.Data {
276 builder.Command().Text("cp").
277 Input(entry).
278 Output(intermediateDir.Join(ctx, entry.Rel()))
279 }
280 builder.Build("copy_data", "copy data")
281 fuzzPackagedModule.DataIntermediateDir = intermediateDir
282
283 if fuzzPackagedModule.FuzzProperties.Dictionary != nil {
284 fuzzPackagedModule.Dictionary = android.PathForModuleSrc(ctx, *fuzzPackagedModule.FuzzProperties.Dictionary)
285 if fuzzPackagedModule.Dictionary.Ext() != ".dict" {
286 ctx.PropertyErrorf("dictionary",
287 "Fuzzer dictionary %q does not have '.dict' extension",
288 fuzzPackagedModule.Dictionary.String())
289 }
290 }
291
292 if fuzzPackagedModule.FuzzProperties.Fuzz_config != nil {
293 configPath := android.PathForModuleOut(ctx, "config").Join(ctx, "config.json")
294 android.WriteFileRule(ctx, configPath, fuzzPackagedModule.FuzzProperties.Fuzz_config.String())
295 fuzzPackagedModule.Config = configPath
296 }
297 return fuzzPackagedModule
298}
299
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000300func NewFuzzer(hod android.HostOrDeviceSupported) *Module {
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400301 module, binary := newBinary(hod, false)
Cory Barkera1da26f2022-06-07 20:12:06 +0000302 baseInstallerPath := "fuzz"
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700303
Cory Barkera1da26f2022-06-07 20:12:06 +0000304 binary.baseInstaller = NewBaseInstaller(baseInstallerPath, baseInstallerPath, InstallInData)
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700305
Cory Barkera1da26f2022-06-07 20:12:06 +0000306 fuzzBin := &fuzzBinary{
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700307 binaryDecorator: binary,
308 baseCompiler: NewBaseCompiler(),
309 }
Cory Barkera1da26f2022-06-07 20:12:06 +0000310 module.compiler = fuzzBin
311 module.linker = fuzzBin
312 module.installer = fuzzBin
Colin Crosseec9b282019-07-18 16:20:52 -0700313
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000314 module.fuzzer.Properties.FuzzFramework = fuzz.LibFuzzer
315
Colin Crosseec9b282019-07-18 16:20:52 -0700316 // The fuzzer runtime is not present for darwin host modules, disable cc_fuzz modules when targeting darwin.
317 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400318
319 extraProps := struct {
320 Sanitize struct {
321 Fuzzer *bool
322 }
Colin Crosseec9b282019-07-18 16:20:52 -0700323 Target struct {
324 Darwin struct {
325 Enabled *bool
326 }
Alex Light71123ec2019-07-24 13:34:19 -0700327 Linux_bionic struct {
328 Enabled *bool
329 }
Colin Crosseec9b282019-07-18 16:20:52 -0700330 }
331 }{}
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400332 extraProps.Sanitize.Fuzzer = BoolPtr(true)
333 extraProps.Target.Darwin.Enabled = BoolPtr(false)
334 extraProps.Target.Linux_bionic.Enabled = BoolPtr(false)
335 ctx.AppendProperties(&extraProps)
Cory Barkera1da26f2022-06-07 20:12:06 +0000336
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000337 targetFramework := fuzz.GetFramework(ctx, fuzz.Cc)
338 if !fuzz.IsValidFrameworkForModule(targetFramework, fuzz.Cc, fuzzBin.fuzzPackagedModule.FuzzProperties.Fuzzing_frameworks) {
339 ctx.Module().Disable()
340 return
341 }
342
343 if targetFramework == fuzz.AFL {
344 fuzzBin.baseCompiler.Properties.Srcs = append(fuzzBin.baseCompiler.Properties.Srcs, ":aflpp_driver", ":afl-compiler-rt")
345 module.fuzzer.Properties.FuzzFramework = fuzz.AFL
346 }
347 })
Cory Barker74aea6c2022-08-08 15:55:12 +0000348
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700349 return module
350}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700351
352// Responsible for generating GNU Make rules that package fuzz targets into
353// their architecture & target/host specific zip file.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500354type ccRustFuzzPackager struct {
hamzehc0a671f2021-07-22 12:05:08 -0700355 fuzz.FuzzPackager
David Fufd121fc2023-07-07 18:11:51 +0000356 fuzzPackagingArchModules string
357 fuzzTargetSharedDepsInstallPairs string
358 allFuzzTargetsName string
359 onlyIncludePresubmits bool
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700360}
361
362func fuzzPackagingFactory() android.Singleton {
Cory Barkera1da26f2022-06-07 20:12:06 +0000363
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500364 fuzzPackager := &ccRustFuzzPackager{
Cory Barkera1da26f2022-06-07 20:12:06 +0000365 fuzzPackagingArchModules: "SOONG_FUZZ_PACKAGING_ARCH_MODULES",
366 fuzzTargetSharedDepsInstallPairs: "FUZZ_TARGET_SHARED_DEPS_INSTALL_PAIRS",
367 allFuzzTargetsName: "ALL_FUZZ_TARGETS",
David Fufd121fc2023-07-07 18:11:51 +0000368 onlyIncludePresubmits: false,
369 }
370 return fuzzPackager
371}
372
373func fuzzPackagingFactoryPresubmit() android.Singleton {
374
375 fuzzPackager := &ccRustFuzzPackager{
376 fuzzPackagingArchModules: "SOONG_PRESUBMIT_FUZZ_PACKAGING_ARCH_MODULES",
377 fuzzTargetSharedDepsInstallPairs: "PRESUBMIT_FUZZ_TARGET_SHARED_DEPS_INSTALL_PAIRS",
378 allFuzzTargetsName: "ALL_PRESUBMIT_FUZZ_TARGETS",
379 onlyIncludePresubmits: true,
Cory Barkera1da26f2022-06-07 20:12:06 +0000380 }
Cory Barkera1da26f2022-06-07 20:12:06 +0000381 return fuzzPackager
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700382}
383
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500384func (s *ccRustFuzzPackager) GenerateBuildActions(ctx android.SingletonContext) {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700385 // Map between each architecture + host/device combination, and the files that
386 // need to be packaged (in the tuple of {source file, destination folder in
387 // archive}).
hamzehc0a671f2021-07-22 12:05:08 -0700388 archDirs := make(map[fuzz.ArchOs][]fuzz.FileToZip)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700389
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700390 // List of individual fuzz targets, so that 'make fuzz' also installs the targets
391 // to the correct output directories as well.
hamzeh41ad8812021-07-07 14:00:07 -0700392 s.FuzzTargets = make(map[string]bool)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700393
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400394 // Map tracking whether each shared library has an install rule to avoid duplicate install rules from
395 // multiple fuzzers that depend on the same shared library.
396 sharedLibraryInstalled := make(map[string]bool)
397
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700398 ctx.VisitAllModules(func(module android.Module) {
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500399 ccModule, ok := module.(LinkableInterface)
400 if !ok || ccModule.PreventInstall() {
hamzeh41ad8812021-07-07 14:00:07 -0700401 return
402 }
hamzeh41ad8812021-07-07 14:00:07 -0700403 // Discard non-fuzz targets.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500404 if ok := fuzz.IsValid(ccModule.FuzzModuleStruct()); !ok {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700405 return
406 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700407
Cory Barkera1da26f2022-06-07 20:12:06 +0000408 sharedLibsInstallDirPrefix := "lib"
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500409 if !ccModule.IsFuzzModule() {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700410 return
411 }
412
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700413 hostOrTargetString := "target"
Colin Cross64a4a5f2023-05-16 17:54:27 -0700414 if ccModule.Target().HostCross {
415 hostOrTargetString = "host_cross"
416 } else if ccModule.Host() {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700417 hostOrTargetString = "host"
418 }
David Fufd121fc2023-07-07 18:11:51 +0000419 if s.onlyIncludePresubmits == true {
420 hostOrTargetString = "presubmit-" + hostOrTargetString
421 }
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700422
Cory Barkera1da26f2022-06-07 20:12:06 +0000423 fpm := fuzz.FuzzPackagedModule{}
424 if ok {
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500425 fpm = ccModule.FuzzPackagedModule()
Cory Barkera1da26f2022-06-07 20:12:06 +0000426 }
427
428 intermediatePath := "fuzz"
Cory Barkera1da26f2022-06-07 20:12:06 +0000429
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500430 archString := ccModule.Target().Arch.ArchType.String()
Cory Barkera1da26f2022-06-07 20:12:06 +0000431 archDir := android.PathForIntermediates(ctx, intermediatePath, hostOrTargetString, archString)
hamzehc0a671f2021-07-22 12:05:08 -0700432 archOs := fuzz.ArchOs{HostOrTarget: hostOrTargetString, Arch: archString, Dir: archDir.String()}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700433
hamzehc0a671f2021-07-22 12:05:08 -0700434 var files []fuzz.FileToZip
Colin Crossf1a035e2020-11-16 17:32:30 -0800435 builder := android.NewRuleBuilder(pctx, ctx)
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800436
hamzeh41ad8812021-07-07 14:00:07 -0700437 // Package the corpus, data, dict and config into a zipfile.
Cory Barkera1da26f2022-06-07 20:12:06 +0000438 files = s.PackageArtifacts(ctx, module, fpm, archDir, builder)
Tri Voad172d82019-11-27 13:45:45 -0800439
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400440 // Package shared libraries
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500441 files = append(files, GetSharedLibsToZip(ccModule.FuzzSharedLibraries(), ccModule, &s.FuzzPackager, archString, sharedLibsInstallDirPrefix, &sharedLibraryInstalled)...)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700442
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700443 // The executable.
Colin Cross80462dc2023-05-08 15:09:31 -0700444 files = append(files, fuzz.FileToZip{SourceFilePath: android.OutputFileForModule(ctx, ccModule, "unstripped")})
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700445
David Fufd121fc2023-07-07 18:11:51 +0000446 if s.onlyIncludePresubmits == true {
447 if fpm.FuzzProperties.Fuzz_config == nil {
448 return
449 }
450 if !BoolDefault(fpm.FuzzProperties.Fuzz_config.Use_for_presubmit, false){
451 return
452 }
453 }
Cory Barkera1da26f2022-06-07 20:12:06 +0000454 archDirs[archOs], ok = s.BuildZipFile(ctx, module, fpm, files, builder, archDir, archString, hostOrTargetString, archOs, archDirs)
hamzeh41ad8812021-07-07 14:00:07 -0700455 if !ok {
456 return
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700457 }
458 })
459
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000460 s.CreateFuzzPackage(ctx, archDirs, fuzz.Cc, pctx)
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700461}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700462
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500463func (s *ccRustFuzzPackager) MakeVars(ctx android.MakeVarsContext) {
hamzeh41ad8812021-07-07 14:00:07 -0700464 packages := s.Packages.Strings()
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700465 sort.Strings(packages)
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400466 sort.Strings(s.FuzzPackager.SharedLibInstallStrings)
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700467 // TODO(mitchp): Migrate this to use MakeVarsContext::DistForGoal() when it's
468 // ready to handle phony targets created in Soong. In the meantime, this
469 // exports the phony 'fuzz' target and dependencies on packages to
470 // core/main.mk so that we can use dist-for-goals.
Cory Barkera1da26f2022-06-07 20:12:06 +0000471
472 ctx.Strict(s.fuzzPackagingArchModules, strings.Join(packages, " "))
473
474 ctx.Strict(s.fuzzTargetSharedDepsInstallPairs,
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400475 strings.Join(s.FuzzPackager.SharedLibInstallStrings, " "))
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700476
477 // Preallocate the slice of fuzz targets to minimise memory allocations.
Cory Barkera1da26f2022-06-07 20:12:06 +0000478 s.PreallocateSlice(ctx, s.allFuzzTargetsName)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700479}
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400480
481// GetSharedLibsToZip finds and marks all the transiently-dependent shared libraries for
482// packaging.
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000483func 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 -0400484 var files []fuzz.FileToZip
485
Cory Barkera1da26f2022-06-07 20:12:06 +0000486 fuzzDir := "fuzz"
Cory Barkera1da26f2022-06-07 20:12:06 +0000487
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000488 for _, ruleBuilderInstall := range sharedLibraries {
489 library := ruleBuilderInstall.From
490 install := ruleBuilderInstall.To
Colin Cross80462dc2023-05-08 15:09:31 -0700491 files = append(files, fuzz.FileToZip{
492 SourceFilePath: library,
493 DestinationPathPrefix: destinationPathPrefix,
494 DestinationPath: install,
495 })
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400496
497 // For each architecture-specific shared library dependency, we need to
498 // install it to the output directory. Setup the install destination here,
499 // which will be used by $(copy-many-files) in the Make backend.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500500 installDestination := SharedLibraryInstallLocation(
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000501 install, module.Host(), fuzzDir, archString)
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400502 if (*sharedLibraryInstalled)[installDestination] {
503 continue
504 }
505 (*sharedLibraryInstalled)[installDestination] = true
506
507 // Escape all the variables, as the install destination here will be called
508 // via. $(eval) in Make.
509 installDestination = strings.ReplaceAll(
510 installDestination, "$", "$$")
511 s.SharedLibInstallStrings = append(s.SharedLibInstallStrings,
512 library.String()+":"+installDestination)
513
514 // Ensure that on device, the library is also reinstalled to the /symbols/
515 // dir. Symbolized DSO's are always installed to the device when fuzzing, but
516 // we want symbolization tools (like `stack`) to be able to find the symbols
517 // in $ANDROID_PRODUCT_OUT/symbols automagically.
518 if !module.Host() {
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000519 symbolsInstallDestination := SharedLibrarySymbolsInstallLocation(install, fuzzDir, archString)
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400520 symbolsInstallDestination = strings.ReplaceAll(symbolsInstallDestination, "$", "$$")
521 s.SharedLibInstallStrings = append(s.SharedLibInstallStrings,
522 library.String()+":"+symbolsInstallDestination)
523 }
524 }
525 return files
526}
Colin Cross31d89b42022-10-04 16:35:39 -0700527
528// CollectAllSharedDependencies search over the provided module's dependencies using
529// VisitDirectDeps and WalkDeps to enumerate all shared library dependencies.
530// VisitDirectDeps is used first to avoid incorrectly using the core libraries (sanitizer
531// runtimes, libc, libdl, etc.) from a dependency. This may cause issues when dependencies
532// have explicit sanitizer tags, as we may get a dependency on an unsanitized libc, etc.
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000533func CollectAllSharedDependencies(ctx android.ModuleContext) (android.RuleBuilderInstalls, []android.Module) {
Colin Cross31d89b42022-10-04 16:35:39 -0700534 seen := make(map[string]bool)
535 recursed := make(map[string]bool)
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000536 deps := []android.Module{}
Colin Cross31d89b42022-10-04 16:35:39 -0700537
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000538 var sharedLibraries android.RuleBuilderInstalls
Colin Cross31d89b42022-10-04 16:35:39 -0700539
540 // Enumerate the first level of dependencies, as we discard all non-library
541 // modules in the BFS loop below.
542 ctx.VisitDirectDeps(func(dep android.Module) {
543 if !IsValidSharedDependency(dep) {
544 return
545 }
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000546 if !ctx.OtherModuleHasProvider(dep, SharedLibraryInfoProvider) {
547 return
548 }
Colin Cross31d89b42022-10-04 16:35:39 -0700549 if seen[ctx.OtherModuleName(dep)] {
550 return
551 }
552 seen[ctx.OtherModuleName(dep)] = true
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000553 deps = append(deps, dep)
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000554
555 sharedLibraryInfo := ctx.OtherModuleProvider(dep, SharedLibraryInfoProvider).(SharedLibraryInfo)
556 installDestination := sharedLibraryInfo.SharedLibrary.Base()
557 ruleBuilderInstall := android.RuleBuilderInstall{android.OutputFileForModule(ctx, dep, "unstripped"), installDestination}
558 sharedLibraries = append(sharedLibraries, ruleBuilderInstall)
Colin Cross31d89b42022-10-04 16:35:39 -0700559 })
560
561 ctx.WalkDeps(func(child, parent android.Module) bool {
Ivan Lozano61c02cc2023-06-09 14:06:44 -0400562
563 // If this is a Rust module which is not rust_ffi_shared, we still want to bundle any transitive
564 // shared dependencies (even for rust_ffi_static)
565 if rustmod, ok := child.(LinkableInterface); ok && rustmod.RustLibraryInterface() && !rustmod.Shared() {
566 if recursed[ctx.OtherModuleName(child)] {
567 return false
568 }
569 recursed[ctx.OtherModuleName(child)] = true
570 return true
571 }
572
Colin Cross31d89b42022-10-04 16:35:39 -0700573 if !IsValidSharedDependency(child) {
574 return false
575 }
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000576 if !ctx.OtherModuleHasProvider(child, SharedLibraryInfoProvider) {
577 return false
578 }
Colin Cross31d89b42022-10-04 16:35:39 -0700579 if !seen[ctx.OtherModuleName(child)] {
580 seen[ctx.OtherModuleName(child)] = true
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000581 deps = append(deps, child)
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000582
583 sharedLibraryInfo := ctx.OtherModuleProvider(child, SharedLibraryInfoProvider).(SharedLibraryInfo)
584 installDestination := sharedLibraryInfo.SharedLibrary.Base()
585 ruleBuilderInstall := android.RuleBuilderInstall{android.OutputFileForModule(ctx, child, "unstripped"), installDestination}
586 sharedLibraries = append(sharedLibraries, ruleBuilderInstall)
Colin Cross31d89b42022-10-04 16:35:39 -0700587 }
588
589 if recursed[ctx.OtherModuleName(child)] {
590 return false
591 }
592 recursed[ctx.OtherModuleName(child)] = true
593 return true
594 })
595
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000596 return sharedLibraries, deps
Colin Cross31d89b42022-10-04 16:35:39 -0700597}