blob: df9f21ad27a185e057565adf4782983d8a415442 [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)
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500262 intermediateDir := android.PathForModuleOut(ctx, "corpus")
Inseob Kim3b244062023-07-11 13:31:36 +0900263
264 // Create one rule per file to avoid MAX_ARG_STRLEN hardlimit.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500265 for _, entry := range fuzzPackagedModule.Corpus {
Inseob Kim3b244062023-07-11 13:31:36 +0900266 ctx.Build(pctx, android.BuildParams{
267 Rule: android.Cp,
268 Output: intermediateDir.Join(ctx, entry.Base()),
269 Input: entry,
270 })
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500271 }
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500272 fuzzPackagedModule.CorpusIntermediateDir = intermediateDir
273
274 fuzzPackagedModule.Data = android.PathsForModuleSrc(ctx, fuzzPackagedModule.FuzzProperties.Data)
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500275 intermediateDir = android.PathForModuleOut(ctx, "data")
Inseob Kim3b244062023-07-11 13:31:36 +0900276
277 // Create one rule per file to avoid MAX_ARG_STRLEN hardlimit.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500278 for _, entry := range fuzzPackagedModule.Data {
Inseob Kim3b244062023-07-11 13:31:36 +0900279 ctx.Build(pctx, android.BuildParams{
280 Rule: android.Cp,
281 Output: intermediateDir.Join(ctx, entry.Rel()),
282 Input: entry,
283 })
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500284 }
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500285 fuzzPackagedModule.DataIntermediateDir = intermediateDir
286
287 if fuzzPackagedModule.FuzzProperties.Dictionary != nil {
288 fuzzPackagedModule.Dictionary = android.PathForModuleSrc(ctx, *fuzzPackagedModule.FuzzProperties.Dictionary)
289 if fuzzPackagedModule.Dictionary.Ext() != ".dict" {
290 ctx.PropertyErrorf("dictionary",
291 "Fuzzer dictionary %q does not have '.dict' extension",
292 fuzzPackagedModule.Dictionary.String())
293 }
294 }
295
296 if fuzzPackagedModule.FuzzProperties.Fuzz_config != nil {
297 configPath := android.PathForModuleOut(ctx, "config").Join(ctx, "config.json")
298 android.WriteFileRule(ctx, configPath, fuzzPackagedModule.FuzzProperties.Fuzz_config.String())
299 fuzzPackagedModule.Config = configPath
300 }
301 return fuzzPackagedModule
302}
303
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000304func NewFuzzer(hod android.HostOrDeviceSupported) *Module {
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400305 module, binary := newBinary(hod, false)
Cory Barkera1da26f2022-06-07 20:12:06 +0000306 baseInstallerPath := "fuzz"
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700307
Cory Barkera1da26f2022-06-07 20:12:06 +0000308 binary.baseInstaller = NewBaseInstaller(baseInstallerPath, baseInstallerPath, InstallInData)
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700309
Cory Barkera1da26f2022-06-07 20:12:06 +0000310 fuzzBin := &fuzzBinary{
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700311 binaryDecorator: binary,
312 baseCompiler: NewBaseCompiler(),
313 }
Cory Barkera1da26f2022-06-07 20:12:06 +0000314 module.compiler = fuzzBin
315 module.linker = fuzzBin
316 module.installer = fuzzBin
Colin Crosseec9b282019-07-18 16:20:52 -0700317
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000318 module.fuzzer.Properties.FuzzFramework = fuzz.LibFuzzer
319
Colin Crosseec9b282019-07-18 16:20:52 -0700320 // The fuzzer runtime is not present for darwin host modules, disable cc_fuzz modules when targeting darwin.
321 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400322
323 extraProps := struct {
324 Sanitize struct {
325 Fuzzer *bool
326 }
Colin Crosseec9b282019-07-18 16:20:52 -0700327 Target struct {
328 Darwin struct {
329 Enabled *bool
330 }
Alex Light71123ec2019-07-24 13:34:19 -0700331 Linux_bionic struct {
332 Enabled *bool
333 }
Colin Crosseec9b282019-07-18 16:20:52 -0700334 }
335 }{}
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400336 extraProps.Sanitize.Fuzzer = BoolPtr(true)
337 extraProps.Target.Darwin.Enabled = BoolPtr(false)
338 extraProps.Target.Linux_bionic.Enabled = BoolPtr(false)
339 ctx.AppendProperties(&extraProps)
Cory Barkera1da26f2022-06-07 20:12:06 +0000340
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000341 targetFramework := fuzz.GetFramework(ctx, fuzz.Cc)
342 if !fuzz.IsValidFrameworkForModule(targetFramework, fuzz.Cc, fuzzBin.fuzzPackagedModule.FuzzProperties.Fuzzing_frameworks) {
343 ctx.Module().Disable()
344 return
345 }
346
347 if targetFramework == fuzz.AFL {
348 fuzzBin.baseCompiler.Properties.Srcs = append(fuzzBin.baseCompiler.Properties.Srcs, ":aflpp_driver", ":afl-compiler-rt")
349 module.fuzzer.Properties.FuzzFramework = fuzz.AFL
350 }
351 })
Cory Barker74aea6c2022-08-08 15:55:12 +0000352
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700353 return module
354}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700355
356// Responsible for generating GNU Make rules that package fuzz targets into
357// their architecture & target/host specific zip file.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500358type ccRustFuzzPackager struct {
hamzehc0a671f2021-07-22 12:05:08 -0700359 fuzz.FuzzPackager
Cole Faust06ea5312023-10-18 17:38:40 -0700360 fuzzPackagingArchModules string
361 fuzzTargetSharedDepsInstallPairs string
362 allFuzzTargetsName string
363 onlyIncludePresubmits bool
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700364}
365
366func fuzzPackagingFactory() android.Singleton {
Cory Barkera1da26f2022-06-07 20:12:06 +0000367
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500368 fuzzPackager := &ccRustFuzzPackager{
Cory Barkera1da26f2022-06-07 20:12:06 +0000369 fuzzPackagingArchModules: "SOONG_FUZZ_PACKAGING_ARCH_MODULES",
370 fuzzTargetSharedDepsInstallPairs: "FUZZ_TARGET_SHARED_DEPS_INSTALL_PAIRS",
371 allFuzzTargetsName: "ALL_FUZZ_TARGETS",
Cole Faust06ea5312023-10-18 17:38:40 -0700372 onlyIncludePresubmits: false,
David Fufd121fc2023-07-07 18:11:51 +0000373 }
374 return fuzzPackager
375}
376
377func fuzzPackagingFactoryPresubmit() android.Singleton {
378
379 fuzzPackager := &ccRustFuzzPackager{
380 fuzzPackagingArchModules: "SOONG_PRESUBMIT_FUZZ_PACKAGING_ARCH_MODULES",
381 fuzzTargetSharedDepsInstallPairs: "PRESUBMIT_FUZZ_TARGET_SHARED_DEPS_INSTALL_PAIRS",
382 allFuzzTargetsName: "ALL_PRESUBMIT_FUZZ_TARGETS",
Cole Faust06ea5312023-10-18 17:38:40 -0700383 onlyIncludePresubmits: true,
Cory Barkera1da26f2022-06-07 20:12:06 +0000384 }
Cory Barkera1da26f2022-06-07 20:12:06 +0000385 return fuzzPackager
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700386}
387
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500388func (s *ccRustFuzzPackager) GenerateBuildActions(ctx android.SingletonContext) {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700389 // Map between each architecture + host/device combination, and the files that
390 // need to be packaged (in the tuple of {source file, destination folder in
391 // archive}).
hamzehc0a671f2021-07-22 12:05:08 -0700392 archDirs := make(map[fuzz.ArchOs][]fuzz.FileToZip)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700393
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700394 // List of individual fuzz targets, so that 'make fuzz' also installs the targets
395 // to the correct output directories as well.
hamzeh41ad8812021-07-07 14:00:07 -0700396 s.FuzzTargets = make(map[string]bool)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700397
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400398 // Map tracking whether each shared library has an install rule to avoid duplicate install rules from
399 // multiple fuzzers that depend on the same shared library.
400 sharedLibraryInstalled := make(map[string]bool)
401
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700402 ctx.VisitAllModules(func(module android.Module) {
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500403 ccModule, ok := module.(LinkableInterface)
404 if !ok || ccModule.PreventInstall() {
hamzeh41ad8812021-07-07 14:00:07 -0700405 return
406 }
hamzeh41ad8812021-07-07 14:00:07 -0700407 // Discard non-fuzz targets.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500408 if ok := fuzz.IsValid(ccModule.FuzzModuleStruct()); !ok {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700409 return
410 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700411
Cory Barkera1da26f2022-06-07 20:12:06 +0000412 sharedLibsInstallDirPrefix := "lib"
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500413 if !ccModule.IsFuzzModule() {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700414 return
415 }
416
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700417 hostOrTargetString := "target"
Colin Cross64a4a5f2023-05-16 17:54:27 -0700418 if ccModule.Target().HostCross {
419 hostOrTargetString = "host_cross"
420 } else if ccModule.Host() {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700421 hostOrTargetString = "host"
422 }
David Fufd121fc2023-07-07 18:11:51 +0000423 if s.onlyIncludePresubmits == true {
424 hostOrTargetString = "presubmit-" + hostOrTargetString
425 }
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700426
Cory Barkera1da26f2022-06-07 20:12:06 +0000427 fpm := fuzz.FuzzPackagedModule{}
428 if ok {
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500429 fpm = ccModule.FuzzPackagedModule()
Cory Barkera1da26f2022-06-07 20:12:06 +0000430 }
431
432 intermediatePath := "fuzz"
Cory Barkera1da26f2022-06-07 20:12:06 +0000433
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500434 archString := ccModule.Target().Arch.ArchType.String()
Cory Barkera1da26f2022-06-07 20:12:06 +0000435 archDir := android.PathForIntermediates(ctx, intermediatePath, hostOrTargetString, archString)
hamzehc0a671f2021-07-22 12:05:08 -0700436 archOs := fuzz.ArchOs{HostOrTarget: hostOrTargetString, Arch: archString, Dir: archDir.String()}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700437
hamzehc0a671f2021-07-22 12:05:08 -0700438 var files []fuzz.FileToZip
Colin Crossf1a035e2020-11-16 17:32:30 -0800439 builder := android.NewRuleBuilder(pctx, ctx)
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800440
hamzeh41ad8812021-07-07 14:00:07 -0700441 // Package the corpus, data, dict and config into a zipfile.
Cory Barkera1da26f2022-06-07 20:12:06 +0000442 files = s.PackageArtifacts(ctx, module, fpm, archDir, builder)
Tri Voad172d82019-11-27 13:45:45 -0800443
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400444 // Package shared libraries
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500445 files = append(files, GetSharedLibsToZip(ccModule.FuzzSharedLibraries(), ccModule, &s.FuzzPackager, archString, sharedLibsInstallDirPrefix, &sharedLibraryInstalled)...)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700446
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700447 // The executable.
Colin Cross80462dc2023-05-08 15:09:31 -0700448 files = append(files, fuzz.FileToZip{SourceFilePath: android.OutputFileForModule(ctx, ccModule, "unstripped")})
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700449
David Fufd121fc2023-07-07 18:11:51 +0000450 if s.onlyIncludePresubmits == true {
451 if fpm.FuzzProperties.Fuzz_config == nil {
452 return
453 }
Cole Faust06ea5312023-10-18 17:38:40 -0700454 if !BoolDefault(fpm.FuzzProperties.Fuzz_config.Use_for_presubmit, false) {
David Fufd121fc2023-07-07 18:11:51 +0000455 return
456 }
457 }
Cory Barkera1da26f2022-06-07 20:12:06 +0000458 archDirs[archOs], ok = s.BuildZipFile(ctx, module, fpm, files, builder, archDir, archString, hostOrTargetString, archOs, archDirs)
hamzeh41ad8812021-07-07 14:00:07 -0700459 if !ok {
460 return
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700461 }
462 })
463
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000464 s.CreateFuzzPackage(ctx, archDirs, fuzz.Cc, pctx)
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700465}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700466
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500467func (s *ccRustFuzzPackager) MakeVars(ctx android.MakeVarsContext) {
hamzeh41ad8812021-07-07 14:00:07 -0700468 packages := s.Packages.Strings()
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700469 sort.Strings(packages)
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400470 sort.Strings(s.FuzzPackager.SharedLibInstallStrings)
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700471 // TODO(mitchp): Migrate this to use MakeVarsContext::DistForGoal() when it's
472 // ready to handle phony targets created in Soong. In the meantime, this
473 // exports the phony 'fuzz' target and dependencies on packages to
474 // core/main.mk so that we can use dist-for-goals.
Cory Barkera1da26f2022-06-07 20:12:06 +0000475
476 ctx.Strict(s.fuzzPackagingArchModules, strings.Join(packages, " "))
477
478 ctx.Strict(s.fuzzTargetSharedDepsInstallPairs,
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400479 strings.Join(s.FuzzPackager.SharedLibInstallStrings, " "))
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700480
481 // Preallocate the slice of fuzz targets to minimise memory allocations.
Cory Barkera1da26f2022-06-07 20:12:06 +0000482 s.PreallocateSlice(ctx, s.allFuzzTargetsName)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700483}
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400484
485// GetSharedLibsToZip finds and marks all the transiently-dependent shared libraries for
486// packaging.
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000487func 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 -0400488 var files []fuzz.FileToZip
489
Cory Barkera1da26f2022-06-07 20:12:06 +0000490 fuzzDir := "fuzz"
Cory Barkera1da26f2022-06-07 20:12:06 +0000491
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000492 for _, ruleBuilderInstall := range sharedLibraries {
493 library := ruleBuilderInstall.From
494 install := ruleBuilderInstall.To
Colin Cross80462dc2023-05-08 15:09:31 -0700495 files = append(files, fuzz.FileToZip{
496 SourceFilePath: library,
497 DestinationPathPrefix: destinationPathPrefix,
498 DestinationPath: install,
499 })
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400500
501 // For each architecture-specific shared library dependency, we need to
502 // install it to the output directory. Setup the install destination here,
503 // which will be used by $(copy-many-files) in the Make backend.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500504 installDestination := SharedLibraryInstallLocation(
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000505 install, module.Host(), fuzzDir, archString)
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400506 if (*sharedLibraryInstalled)[installDestination] {
507 continue
508 }
509 (*sharedLibraryInstalled)[installDestination] = true
510
511 // Escape all the variables, as the install destination here will be called
512 // via. $(eval) in Make.
513 installDestination = strings.ReplaceAll(
514 installDestination, "$", "$$")
515 s.SharedLibInstallStrings = append(s.SharedLibInstallStrings,
516 library.String()+":"+installDestination)
517
518 // Ensure that on device, the library is also reinstalled to the /symbols/
519 // dir. Symbolized DSO's are always installed to the device when fuzzing, but
520 // we want symbolization tools (like `stack`) to be able to find the symbols
521 // in $ANDROID_PRODUCT_OUT/symbols automagically.
522 if !module.Host() {
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000523 symbolsInstallDestination := SharedLibrarySymbolsInstallLocation(install, fuzzDir, archString)
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400524 symbolsInstallDestination = strings.ReplaceAll(symbolsInstallDestination, "$", "$$")
525 s.SharedLibInstallStrings = append(s.SharedLibInstallStrings,
526 library.String()+":"+symbolsInstallDestination)
527 }
528 }
529 return files
530}
Colin Cross31d89b42022-10-04 16:35:39 -0700531
532// CollectAllSharedDependencies search over the provided module's dependencies using
533// VisitDirectDeps and WalkDeps to enumerate all shared library dependencies.
534// VisitDirectDeps is used first to avoid incorrectly using the core libraries (sanitizer
535// runtimes, libc, libdl, etc.) from a dependency. This may cause issues when dependencies
536// have explicit sanitizer tags, as we may get a dependency on an unsanitized libc, etc.
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000537func CollectAllSharedDependencies(ctx android.ModuleContext) (android.RuleBuilderInstalls, []android.Module) {
Colin Cross31d89b42022-10-04 16:35:39 -0700538 seen := make(map[string]bool)
539 recursed := make(map[string]bool)
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000540 deps := []android.Module{}
Colin Cross31d89b42022-10-04 16:35:39 -0700541
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000542 var sharedLibraries android.RuleBuilderInstalls
Colin Cross31d89b42022-10-04 16:35:39 -0700543
544 // Enumerate the first level of dependencies, as we discard all non-library
545 // modules in the BFS loop below.
546 ctx.VisitDirectDeps(func(dep android.Module) {
547 if !IsValidSharedDependency(dep) {
548 return
549 }
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000550 if !ctx.OtherModuleHasProvider(dep, SharedLibraryInfoProvider) {
551 return
552 }
Colin Cross31d89b42022-10-04 16:35:39 -0700553 if seen[ctx.OtherModuleName(dep)] {
554 return
555 }
556 seen[ctx.OtherModuleName(dep)] = true
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000557 deps = append(deps, dep)
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000558
559 sharedLibraryInfo := ctx.OtherModuleProvider(dep, SharedLibraryInfoProvider).(SharedLibraryInfo)
560 installDestination := sharedLibraryInfo.SharedLibrary.Base()
561 ruleBuilderInstall := android.RuleBuilderInstall{android.OutputFileForModule(ctx, dep, "unstripped"), installDestination}
562 sharedLibraries = append(sharedLibraries, ruleBuilderInstall)
Colin Cross31d89b42022-10-04 16:35:39 -0700563 })
564
565 ctx.WalkDeps(func(child, parent android.Module) bool {
Ivan Lozano61c02cc2023-06-09 14:06:44 -0400566
567 // If this is a Rust module which is not rust_ffi_shared, we still want to bundle any transitive
568 // shared dependencies (even for rust_ffi_static)
569 if rustmod, ok := child.(LinkableInterface); ok && rustmod.RustLibraryInterface() && !rustmod.Shared() {
570 if recursed[ctx.OtherModuleName(child)] {
571 return false
572 }
573 recursed[ctx.OtherModuleName(child)] = true
574 return true
575 }
576
Colin Cross31d89b42022-10-04 16:35:39 -0700577 if !IsValidSharedDependency(child) {
578 return false
579 }
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000580 if !ctx.OtherModuleHasProvider(child, SharedLibraryInfoProvider) {
581 return false
582 }
Colin Cross31d89b42022-10-04 16:35:39 -0700583 if !seen[ctx.OtherModuleName(child)] {
584 seen[ctx.OtherModuleName(child)] = true
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000585 deps = append(deps, child)
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000586
587 sharedLibraryInfo := ctx.OtherModuleProvider(child, SharedLibraryInfoProvider).(SharedLibraryInfo)
588 installDestination := sharedLibraryInfo.SharedLibrary.Base()
589 ruleBuilderInstall := android.RuleBuilderInstall{android.OutputFileForModule(ctx, child, "unstripped"), installDestination}
590 sharedLibraries = append(sharedLibraries, ruleBuilderInstall)
Colin Cross31d89b42022-10-04 16:35:39 -0700591 }
592
593 if recursed[ctx.OtherModuleName(child)] {
594 return false
595 }
596 recursed[ctx.OtherModuleName(child)] = true
597 return true
598 })
599
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000600 return sharedLibraries, deps
Colin Cross31d89b42022-10-04 16:35:39 -0700601}