blob: 7f0a5021b1ff49ba37958f5854feefcd81ee1aa0 [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)
Cory Barkera1da26f2022-06-07 20:12:06 +000032}
33
34type FuzzProperties struct {
Cory Barker9cfcf6d2022-07-22 17:22:02 +000035 FuzzFramework fuzz.Framework `blueprint:"mutated"`
Cory Barkera1da26f2022-06-07 20:12:06 +000036}
37
38type fuzzer struct {
39 Properties FuzzProperties
40}
41
42func (fuzzer *fuzzer) flags(ctx ModuleContext, flags Flags) Flags {
Cory Barker9cfcf6d2022-07-22 17:22:02 +000043 if fuzzer.Properties.FuzzFramework == fuzz.AFL {
44 flags.Local.CFlags = append(flags.Local.CFlags, []string{
45 "-fsanitize-coverage=trace-pc-guard",
46 "-Wno-unused-result",
47 "-Wno-unused-parameter",
48 "-Wno-unused-function",
49 }...)
Cory Barkera1da26f2022-06-07 20:12:06 +000050 }
51
52 return flags
53}
54
55func (fuzzer *fuzzer) props() []interface{} {
56 return []interface{}{&fuzzer.Properties}
57}
58
59func fuzzMutatorDeps(mctx android.TopDownMutatorContext) {
60 currentModule, ok := mctx.Module().(*Module)
61 if !ok {
62 return
63 }
64
Cory Barker9cfcf6d2022-07-22 17:22:02 +000065 if currentModule.fuzzer == nil {
Cory Barkera1da26f2022-06-07 20:12:06 +000066 return
67 }
68
69 mctx.WalkDeps(func(child android.Module, parent android.Module) bool {
70 c, ok := child.(*Module)
71 if !ok {
72 return false
73 }
74
75 if c.sanitize == nil {
76 return false
77 }
78
79 isFuzzerPointer := c.sanitize.getSanitizerBoolPtr(Fuzzer)
80 if isFuzzerPointer == nil || !*isFuzzerPointer {
81 return false
82 }
83
84 if c.fuzzer == nil {
85 return false
86 }
87
Cory Barker9cfcf6d2022-07-22 17:22:02 +000088 c.fuzzer.Properties.FuzzFramework = currentModule.fuzzer.Properties.FuzzFramework
Cory Barkera1da26f2022-06-07 20:12:06 +000089 return true
90 })
91}
92
Mitch Phillipsda9a4632019-07-15 09:34:09 -070093// cc_fuzz creates a host/device fuzzer binary. Host binaries can be found at
94// $ANDROID_HOST_OUT/fuzz/, and device binaries can be found at /data/fuzz on
95// your device, or $ANDROID_PRODUCT_OUT/data/fuzz in your build tree.
Cory Barkera1da26f2022-06-07 20:12:06 +000096func LibFuzzFactory() android.Module {
Cory Barker9cfcf6d2022-07-22 17:22:02 +000097 module := NewFuzzer(android.HostAndDeviceSupported)
Cory Barkera1da26f2022-06-07 20:12:06 +000098 return module.Init()
Mitch Phillipsda9a4632019-07-15 09:34:09 -070099}
100
101type fuzzBinary struct {
102 *binaryDecorator
103 *baseCompiler
Cory Barkera1da26f2022-06-07 20:12:06 +0000104 fuzzPackagedModule fuzz.FuzzPackagedModule
hamzeh41ad8812021-07-07 14:00:07 -0700105 installedSharedDeps []string
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000106 sharedLibraries android.RuleBuilderInstalls
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700107}
108
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400109func (fuzz *fuzzBinary) fuzzBinary() bool {
110 return true
111}
112
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700113func (fuzz *fuzzBinary) linkerProps() []interface{} {
114 props := fuzz.binaryDecorator.linkerProps()
hamzeh41ad8812021-07-07 14:00:07 -0700115 props = append(props, &fuzz.fuzzPackagedModule.FuzzProperties)
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000116
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700117 return props
118}
119
120func (fuzz *fuzzBinary) linkerInit(ctx BaseModuleContext) {
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700121 fuzz.binaryDecorator.linkerInit(ctx)
122}
123
Cory Barkera1da26f2022-06-07 20:12:06 +0000124func (fuzzBin *fuzzBinary) linkerDeps(ctx DepsContext, deps Deps) Deps {
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000125 if ctx.Config().Getenv("FUZZ_FRAMEWORK") == "AFL" {
Cory Barkera1da26f2022-06-07 20:12:06 +0000126 deps.HeaderLibs = append(deps.HeaderLibs, "libafl_headers")
Cory Barkera1da26f2022-06-07 20:12:06 +0000127 } else {
128 deps.StaticLibs = append(deps.StaticLibs, config.LibFuzzerRuntimeLibrary(ctx.toolchain()))
Kris Alderd406da12022-10-21 09:34:21 -0700129 // Fuzzers built with HWASAN should use the interceptors for better
130 // mutation based on signals in strcmp, memcpy, etc. This is only needed for
131 // fuzz targets, not generic HWASAN-ified binaries or libraries.
132 if module, ok := ctx.Module().(*Module); ok {
133 if module.IsSanitizerEnabled(Hwasan) {
134 deps.StaticLibs = append(deps.StaticLibs, config.LibFuzzerRuntimeInterceptors(ctx.toolchain()))
135 }
136 }
Cory Barkera1da26f2022-06-07 20:12:06 +0000137 }
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000138
139 deps = fuzzBin.binaryDecorator.linkerDeps(ctx, deps)
140 return deps
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700141}
142
143func (fuzz *fuzzBinary) linkerFlags(ctx ModuleContext, flags Flags) Flags {
144 flags = fuzz.binaryDecorator.linkerFlags(ctx, flags)
Mitch Phillips1f7f54f2019-11-14 14:50:47 -0800145 // RunPaths on devices isn't instantiated by the base linker. `../lib` for
146 // installed fuzz targets (both host and device), and `./lib` for fuzz
147 // target packages.
Mitch Phillips1f7f54f2019-11-14 14:50:47 -0800148 flags.Local.LdFlags = append(flags.Local.LdFlags, `-Wl,-rpath,\$$ORIGIN/lib`)
Cory Barkera1da26f2022-06-07 20:12:06 +0000149
Kris Alderc2634812022-10-25 10:58:59 -0700150 // When running on device, fuzz targets with vendor: true set will be in
151 // fuzzer_name/vendor/fuzzer_name (note the extra 'vendor' and thus need to
152 // link with libraries in ../../lib/. Non-vendor binaries only need to look
153 // one level up, in ../lib/.
154 if ctx.inVendor() {
155 flags.Local.LdFlags = append(flags.Local.LdFlags, `-Wl,-rpath,\$$ORIGIN/../../lib`)
156 } else {
157 flags.Local.LdFlags = append(flags.Local.LdFlags, `-Wl,-rpath,\$$ORIGIN/../lib`)
158 }
159
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700160 return flags
161}
162
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400163// IsValidSharedDependency takes a module and determines if it is a unique shared library
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700164// that should be installed in the fuzz target output directories. This function
165// returns true, unless:
Colin Crossd079e0b2022-08-16 10:27:33 -0700166// - The module is not an installable shared library, or
167// - The module is a header or stub, or
168// - The module is a prebuilt and its source is available, or
169// - The module is a versioned member of an SDK snapshot.
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400170func IsValidSharedDependency(dependency android.Module) bool {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700171 // TODO(b/144090547): We should be parsing these modules using
172 // ModuleDependencyTag instead of the current brute-force checking.
173
Colin Cross31076b32020-10-23 17:22:06 -0700174 linkable, ok := dependency.(LinkableInterface)
175 if !ok || !linkable.CcLibraryInterface() {
176 // Discard non-linkables.
177 return false
178 }
179
180 if !linkable.Shared() {
181 // Discard static libs.
182 return false
183 }
184
Colin Cross31076b32020-10-23 17:22:06 -0700185 if lib := moduleLibraryInterface(dependency); lib != nil && lib.buildStubs() && linkable.CcLibrary() {
Mitch Phillipsf50bddb2019-11-12 14:03:31 -0800186 // Discard stubs libs (only CCLibrary variants). Prebuilt libraries should not
187 // be excluded on the basis of they're not CCLibrary()'s.
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700188 return false
189 }
190
Mitch Phillipsf50bddb2019-11-12 14:03:31 -0800191 // We discarded module stubs libraries above, but the LLNDK prebuilts stubs
192 // libraries must be handled differently - by looking for the stubDecorator.
193 // Discard LLNDK prebuilts stubs as well.
194 if ccLibrary, isCcLibrary := dependency.(*Module); isCcLibrary {
195 if _, isLLndkStubLibrary := ccLibrary.linker.(*stubDecorator); isLLndkStubLibrary {
196 return false
197 }
Victor Chang00c144f2021-02-09 12:30:33 +0000198 // Discard installable:false libraries because they are expected to be absent
199 // in runtime.
Colin Cross1bc94122021-10-28 13:25:54 -0700200 if !proptools.BoolDefault(ccLibrary.Installable(), true) {
Victor Chang00c144f2021-02-09 12:30:33 +0000201 return false
202 }
Mitch Phillipsf50bddb2019-11-12 14:03:31 -0800203 }
204
Martin Stjernholm02460ab2020-10-06 02:36:43 +0100205 // If the same library is present both as source and a prebuilt we must pick
206 // only one to avoid a conflict. Always prefer the source since the prebuilt
207 // probably won't be built with sanitizers enabled.
Paul Duffinf7c99f52021-04-28 10:41:21 +0100208 if prebuilt := android.GetEmbeddedPrebuilt(dependency); prebuilt != nil && prebuilt.SourceExists() {
Martin Stjernholm02460ab2020-10-06 02:36:43 +0100209 return false
210 }
211
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700212 return true
213}
214
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500215func SharedLibraryInstallLocation(
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000216 libraryBase string, isHost bool, fuzzDir string, archString string) string {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700217 installLocation := "$(PRODUCT_OUT)/data"
218 if isHost {
219 installLocation = "$(HOST_OUT)"
220 }
221 installLocation = filepath.Join(
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000222 installLocation, fuzzDir, archString, "lib", libraryBase)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700223 return installLocation
224}
225
Mitch Phillips0bf97132020-03-06 09:38:12 -0800226// Get the device-only shared library symbols install directory.
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000227func SharedLibrarySymbolsInstallLocation(libraryBase string, fuzzDir string, archString string) string {
228 return filepath.Join("$(PRODUCT_OUT)/symbols/data/", fuzzDir, archString, "/lib/", libraryBase)
Mitch Phillips0bf97132020-03-06 09:38:12 -0800229}
230
Cory Barkera1da26f2022-06-07 20:12:06 +0000231func (fuzzBin *fuzzBinary) install(ctx ModuleContext, file android.Path) {
232 installBase := "fuzz"
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -0700233
Cory Barkera1da26f2022-06-07 20:12:06 +0000234 fuzzBin.binaryDecorator.baseInstaller.dir = filepath.Join(
235 installBase, ctx.Target().Arch.ArchType.String(), ctx.ModuleName())
236 fuzzBin.binaryDecorator.baseInstaller.dir64 = filepath.Join(
237 installBase, ctx.Target().Arch.ArchType.String(), ctx.ModuleName())
238 fuzzBin.binaryDecorator.baseInstaller.install(ctx, file)
239
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500240 fuzzBin.fuzzPackagedModule = PackageFuzzModule(ctx, fuzzBin.fuzzPackagedModule, pctx)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700241
242 // Grab the list of required shared libraries.
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000243 fuzzBin.sharedLibraries, _ = CollectAllSharedDependencies(ctx)
Colin Crossdc809f92019-11-20 15:58:32 -0800244
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000245 for _, ruleBuilderInstall := range fuzzBin.sharedLibraries {
246 install := ruleBuilderInstall.To
Cory Barkera1da26f2022-06-07 20:12:06 +0000247 fuzzBin.installedSharedDeps = append(fuzzBin.installedSharedDeps,
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500248 SharedLibraryInstallLocation(
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000249 install, ctx.Host(), installBase, ctx.Arch().ArchType.String()))
Mitch Phillips0bf97132020-03-06 09:38:12 -0800250
251 // Also add the dependency on the shared library symbols dir.
252 if !ctx.Host() {
Cory Barkera1da26f2022-06-07 20:12:06 +0000253 fuzzBin.installedSharedDeps = append(fuzzBin.installedSharedDeps,
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000254 SharedLibrarySymbolsInstallLocation(install, installBase, ctx.Arch().ArchType.String()))
Mitch Phillips0bf97132020-03-06 09:38:12 -0800255 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700256 }
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700257}
258
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500259func PackageFuzzModule(ctx android.ModuleContext, fuzzPackagedModule fuzz.FuzzPackagedModule, pctx android.PackageContext) fuzz.FuzzPackagedModule {
260 fuzzPackagedModule.Corpus = android.PathsForModuleSrc(ctx, fuzzPackagedModule.FuzzProperties.Corpus)
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500261 intermediateDir := android.PathForModuleOut(ctx, "corpus")
Inseob Kim3b244062023-07-11 13:31:36 +0900262
263 // Create one rule per file to avoid MAX_ARG_STRLEN hardlimit.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500264 for _, entry := range fuzzPackagedModule.Corpus {
Inseob Kim3b244062023-07-11 13:31:36 +0900265 ctx.Build(pctx, android.BuildParams{
266 Rule: android.Cp,
267 Output: intermediateDir.Join(ctx, entry.Base()),
268 Input: entry,
269 })
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500270 }
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500271 fuzzPackagedModule.CorpusIntermediateDir = intermediateDir
272
273 fuzzPackagedModule.Data = android.PathsForModuleSrc(ctx, fuzzPackagedModule.FuzzProperties.Data)
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500274 intermediateDir = android.PathForModuleOut(ctx, "data")
Inseob Kim3b244062023-07-11 13:31:36 +0900275
276 // Create one rule per file to avoid MAX_ARG_STRLEN hardlimit.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500277 for _, entry := range fuzzPackagedModule.Data {
Inseob Kim3b244062023-07-11 13:31:36 +0900278 ctx.Build(pctx, android.BuildParams{
279 Rule: android.Cp,
280 Output: intermediateDir.Join(ctx, entry.Rel()),
281 Input: entry,
282 })
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500283 }
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500284 fuzzPackagedModule.DataIntermediateDir = intermediateDir
285
286 if fuzzPackagedModule.FuzzProperties.Dictionary != nil {
287 fuzzPackagedModule.Dictionary = android.PathForModuleSrc(ctx, *fuzzPackagedModule.FuzzProperties.Dictionary)
288 if fuzzPackagedModule.Dictionary.Ext() != ".dict" {
289 ctx.PropertyErrorf("dictionary",
290 "Fuzzer dictionary %q does not have '.dict' extension",
291 fuzzPackagedModule.Dictionary.String())
292 }
293 }
294
295 if fuzzPackagedModule.FuzzProperties.Fuzz_config != nil {
296 configPath := android.PathForModuleOut(ctx, "config").Join(ctx, "config.json")
297 android.WriteFileRule(ctx, configPath, fuzzPackagedModule.FuzzProperties.Fuzz_config.String())
298 fuzzPackagedModule.Config = configPath
299 }
300 return fuzzPackagedModule
301}
302
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000303func NewFuzzer(hod android.HostOrDeviceSupported) *Module {
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400304 module, binary := newBinary(hod, false)
Cory Barkera1da26f2022-06-07 20:12:06 +0000305 baseInstallerPath := "fuzz"
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700306
Cory Barkera1da26f2022-06-07 20:12:06 +0000307 binary.baseInstaller = NewBaseInstaller(baseInstallerPath, baseInstallerPath, InstallInData)
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700308
Cory Barkera1da26f2022-06-07 20:12:06 +0000309 fuzzBin := &fuzzBinary{
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700310 binaryDecorator: binary,
311 baseCompiler: NewBaseCompiler(),
312 }
Cory Barkera1da26f2022-06-07 20:12:06 +0000313 module.compiler = fuzzBin
314 module.linker = fuzzBin
315 module.installer = fuzzBin
Colin Crosseec9b282019-07-18 16:20:52 -0700316
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000317 module.fuzzer.Properties.FuzzFramework = fuzz.LibFuzzer
318
Colin Crosseec9b282019-07-18 16:20:52 -0700319 // The fuzzer runtime is not present for darwin host modules, disable cc_fuzz modules when targeting darwin.
320 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400321
322 extraProps := struct {
323 Sanitize struct {
324 Fuzzer *bool
325 }
Colin Crosseec9b282019-07-18 16:20:52 -0700326 Target struct {
327 Darwin struct {
328 Enabled *bool
329 }
Alex Light71123ec2019-07-24 13:34:19 -0700330 Linux_bionic struct {
331 Enabled *bool
332 }
Colin Crosseec9b282019-07-18 16:20:52 -0700333 }
334 }{}
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400335 extraProps.Sanitize.Fuzzer = BoolPtr(true)
336 extraProps.Target.Darwin.Enabled = BoolPtr(false)
337 extraProps.Target.Linux_bionic.Enabled = BoolPtr(false)
338 ctx.AppendProperties(&extraProps)
Cory Barkera1da26f2022-06-07 20:12:06 +0000339
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000340 targetFramework := fuzz.GetFramework(ctx, fuzz.Cc)
341 if !fuzz.IsValidFrameworkForModule(targetFramework, fuzz.Cc, fuzzBin.fuzzPackagedModule.FuzzProperties.Fuzzing_frameworks) {
342 ctx.Module().Disable()
343 return
344 }
345
346 if targetFramework == fuzz.AFL {
347 fuzzBin.baseCompiler.Properties.Srcs = append(fuzzBin.baseCompiler.Properties.Srcs, ":aflpp_driver", ":afl-compiler-rt")
348 module.fuzzer.Properties.FuzzFramework = fuzz.AFL
349 }
350 })
Cory Barker74aea6c2022-08-08 15:55:12 +0000351
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700352 return module
353}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700354
355// Responsible for generating GNU Make rules that package fuzz targets into
356// their architecture & target/host specific zip file.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500357type ccRustFuzzPackager struct {
hamzehc0a671f2021-07-22 12:05:08 -0700358 fuzz.FuzzPackager
Cory Barkera1da26f2022-06-07 20:12:06 +0000359 fuzzPackagingArchModules string
360 fuzzTargetSharedDepsInstallPairs string
361 allFuzzTargetsName string
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700362}
363
364func fuzzPackagingFactory() android.Singleton {
Cory Barkera1da26f2022-06-07 20:12:06 +0000365
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500366 fuzzPackager := &ccRustFuzzPackager{
Cory Barkera1da26f2022-06-07 20:12:06 +0000367 fuzzPackagingArchModules: "SOONG_FUZZ_PACKAGING_ARCH_MODULES",
368 fuzzTargetSharedDepsInstallPairs: "FUZZ_TARGET_SHARED_DEPS_INSTALL_PAIRS",
369 allFuzzTargetsName: "ALL_FUZZ_TARGETS",
370 }
Cory Barkera1da26f2022-06-07 20:12:06 +0000371 return fuzzPackager
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700372}
373
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500374func (s *ccRustFuzzPackager) GenerateBuildActions(ctx android.SingletonContext) {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700375 // Map between each architecture + host/device combination, and the files that
376 // need to be packaged (in the tuple of {source file, destination folder in
377 // archive}).
hamzehc0a671f2021-07-22 12:05:08 -0700378 archDirs := make(map[fuzz.ArchOs][]fuzz.FileToZip)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700379
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700380 // List of individual fuzz targets, so that 'make fuzz' also installs the targets
381 // to the correct output directories as well.
hamzeh41ad8812021-07-07 14:00:07 -0700382 s.FuzzTargets = make(map[string]bool)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700383
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400384 // Map tracking whether each shared library has an install rule to avoid duplicate install rules from
385 // multiple fuzzers that depend on the same shared library.
386 sharedLibraryInstalled := make(map[string]bool)
387
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700388 ctx.VisitAllModules(func(module android.Module) {
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500389 ccModule, ok := module.(LinkableInterface)
390 if !ok || ccModule.PreventInstall() {
hamzeh41ad8812021-07-07 14:00:07 -0700391 return
392 }
393
394 // Discard non-fuzz targets.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500395 if ok := fuzz.IsValid(ccModule.FuzzModuleStruct()); !ok {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700396 return
397 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700398
Cory Barkera1da26f2022-06-07 20:12:06 +0000399 sharedLibsInstallDirPrefix := "lib"
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500400 if !ccModule.IsFuzzModule() {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700401 return
402 }
403
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700404 hostOrTargetString := "target"
Colin Cross64a4a5f2023-05-16 17:54:27 -0700405 if ccModule.Target().HostCross {
406 hostOrTargetString = "host_cross"
407 } else if ccModule.Host() {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700408 hostOrTargetString = "host"
409 }
410
Cory Barkera1da26f2022-06-07 20:12:06 +0000411 fpm := fuzz.FuzzPackagedModule{}
412 if ok {
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500413 fpm = ccModule.FuzzPackagedModule()
Cory Barkera1da26f2022-06-07 20:12:06 +0000414 }
415
416 intermediatePath := "fuzz"
Cory Barkera1da26f2022-06-07 20:12:06 +0000417
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500418 archString := ccModule.Target().Arch.ArchType.String()
Cory Barkera1da26f2022-06-07 20:12:06 +0000419 archDir := android.PathForIntermediates(ctx, intermediatePath, hostOrTargetString, archString)
hamzehc0a671f2021-07-22 12:05:08 -0700420 archOs := fuzz.ArchOs{HostOrTarget: hostOrTargetString, Arch: archString, Dir: archDir.String()}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700421
hamzehc0a671f2021-07-22 12:05:08 -0700422 var files []fuzz.FileToZip
Colin Crossf1a035e2020-11-16 17:32:30 -0800423 builder := android.NewRuleBuilder(pctx, ctx)
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800424
hamzeh41ad8812021-07-07 14:00:07 -0700425 // Package the corpus, data, dict and config into a zipfile.
Cory Barkera1da26f2022-06-07 20:12:06 +0000426 files = s.PackageArtifacts(ctx, module, fpm, archDir, builder)
Tri Voad172d82019-11-27 13:45:45 -0800427
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400428 // Package shared libraries
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500429 files = append(files, GetSharedLibsToZip(ccModule.FuzzSharedLibraries(), ccModule, &s.FuzzPackager, archString, sharedLibsInstallDirPrefix, &sharedLibraryInstalled)...)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700430
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700431 // The executable.
Colin Cross80462dc2023-05-08 15:09:31 -0700432 files = append(files, fuzz.FileToZip{SourceFilePath: android.OutputFileForModule(ctx, ccModule, "unstripped")})
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700433
Cory Barkera1da26f2022-06-07 20:12:06 +0000434 archDirs[archOs], ok = s.BuildZipFile(ctx, module, fpm, files, builder, archDir, archString, hostOrTargetString, archOs, archDirs)
hamzeh41ad8812021-07-07 14:00:07 -0700435 if !ok {
436 return
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700437 }
438 })
439
Cory Barker9cfcf6d2022-07-22 17:22:02 +0000440 s.CreateFuzzPackage(ctx, archDirs, fuzz.Cc, pctx)
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700441}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700442
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500443func (s *ccRustFuzzPackager) MakeVars(ctx android.MakeVarsContext) {
hamzeh41ad8812021-07-07 14:00:07 -0700444 packages := s.Packages.Strings()
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700445 sort.Strings(packages)
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400446 sort.Strings(s.FuzzPackager.SharedLibInstallStrings)
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700447 // TODO(mitchp): Migrate this to use MakeVarsContext::DistForGoal() when it's
448 // ready to handle phony targets created in Soong. In the meantime, this
449 // exports the phony 'fuzz' target and dependencies on packages to
450 // core/main.mk so that we can use dist-for-goals.
Cory Barkera1da26f2022-06-07 20:12:06 +0000451
452 ctx.Strict(s.fuzzPackagingArchModules, strings.Join(packages, " "))
453
454 ctx.Strict(s.fuzzTargetSharedDepsInstallPairs,
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400455 strings.Join(s.FuzzPackager.SharedLibInstallStrings, " "))
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700456
457 // Preallocate the slice of fuzz targets to minimise memory allocations.
Cory Barkera1da26f2022-06-07 20:12:06 +0000458 s.PreallocateSlice(ctx, s.allFuzzTargetsName)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700459}
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400460
461// GetSharedLibsToZip finds and marks all the transiently-dependent shared libraries for
462// packaging.
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000463func 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 -0400464 var files []fuzz.FileToZip
465
Cory Barkera1da26f2022-06-07 20:12:06 +0000466 fuzzDir := "fuzz"
Cory Barkera1da26f2022-06-07 20:12:06 +0000467
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000468 for _, ruleBuilderInstall := range sharedLibraries {
469 library := ruleBuilderInstall.From
470 install := ruleBuilderInstall.To
Colin Cross80462dc2023-05-08 15:09:31 -0700471 files = append(files, fuzz.FileToZip{
472 SourceFilePath: library,
473 DestinationPathPrefix: destinationPathPrefix,
474 DestinationPath: install,
475 })
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400476
477 // For each architecture-specific shared library dependency, we need to
478 // install it to the output directory. Setup the install destination here,
479 // which will be used by $(copy-many-files) in the Make backend.
Ivan Lozano0f9963e2023-02-06 13:31:02 -0500480 installDestination := SharedLibraryInstallLocation(
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000481 install, module.Host(), fuzzDir, archString)
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400482 if (*sharedLibraryInstalled)[installDestination] {
483 continue
484 }
485 (*sharedLibraryInstalled)[installDestination] = true
486
487 // Escape all the variables, as the install destination here will be called
488 // via. $(eval) in Make.
489 installDestination = strings.ReplaceAll(
490 installDestination, "$", "$$")
491 s.SharedLibInstallStrings = append(s.SharedLibInstallStrings,
492 library.String()+":"+installDestination)
493
494 // Ensure that on device, the library is also reinstalled to the /symbols/
495 // dir. Symbolized DSO's are always installed to the device when fuzzing, but
496 // we want symbolization tools (like `stack`) to be able to find the symbols
497 // in $ANDROID_PRODUCT_OUT/symbols automagically.
498 if !module.Host() {
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000499 symbolsInstallDestination := SharedLibrarySymbolsInstallLocation(install, fuzzDir, archString)
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400500 symbolsInstallDestination = strings.ReplaceAll(symbolsInstallDestination, "$", "$$")
501 s.SharedLibInstallStrings = append(s.SharedLibInstallStrings,
502 library.String()+":"+symbolsInstallDestination)
503 }
504 }
505 return files
506}
Colin Cross31d89b42022-10-04 16:35:39 -0700507
508// CollectAllSharedDependencies search over the provided module's dependencies using
509// VisitDirectDeps and WalkDeps to enumerate all shared library dependencies.
510// VisitDirectDeps is used first to avoid incorrectly using the core libraries (sanitizer
511// runtimes, libc, libdl, etc.) from a dependency. This may cause issues when dependencies
512// have explicit sanitizer tags, as we may get a dependency on an unsanitized libc, etc.
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000513func CollectAllSharedDependencies(ctx android.ModuleContext) (android.RuleBuilderInstalls, []android.Module) {
Colin Cross31d89b42022-10-04 16:35:39 -0700514 seen := make(map[string]bool)
515 recursed := make(map[string]bool)
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000516 deps := []android.Module{}
Colin Cross31d89b42022-10-04 16:35:39 -0700517
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000518 var sharedLibraries android.RuleBuilderInstalls
Colin Cross31d89b42022-10-04 16:35:39 -0700519
520 // Enumerate the first level of dependencies, as we discard all non-library
521 // modules in the BFS loop below.
522 ctx.VisitDirectDeps(func(dep android.Module) {
523 if !IsValidSharedDependency(dep) {
524 return
525 }
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000526 if !ctx.OtherModuleHasProvider(dep, SharedLibraryInfoProvider) {
527 return
528 }
Colin Cross31d89b42022-10-04 16:35:39 -0700529 if seen[ctx.OtherModuleName(dep)] {
530 return
531 }
532 seen[ctx.OtherModuleName(dep)] = true
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000533 deps = append(deps, dep)
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000534
535 sharedLibraryInfo := ctx.OtherModuleProvider(dep, SharedLibraryInfoProvider).(SharedLibraryInfo)
536 installDestination := sharedLibraryInfo.SharedLibrary.Base()
537 ruleBuilderInstall := android.RuleBuilderInstall{android.OutputFileForModule(ctx, dep, "unstripped"), installDestination}
538 sharedLibraries = append(sharedLibraries, ruleBuilderInstall)
Colin Cross31d89b42022-10-04 16:35:39 -0700539 })
540
541 ctx.WalkDeps(func(child, parent android.Module) bool {
Ivan Lozano61c02cc2023-06-09 14:06:44 -0400542
543 // If this is a Rust module which is not rust_ffi_shared, we still want to bundle any transitive
544 // shared dependencies (even for rust_ffi_static)
545 if rustmod, ok := child.(LinkableInterface); ok && rustmod.RustLibraryInterface() && !rustmod.Shared() {
546 if recursed[ctx.OtherModuleName(child)] {
547 return false
548 }
549 recursed[ctx.OtherModuleName(child)] = true
550 return true
551 }
552
Colin Cross31d89b42022-10-04 16:35:39 -0700553 if !IsValidSharedDependency(child) {
554 return false
555 }
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000556 if !ctx.OtherModuleHasProvider(child, SharedLibraryInfoProvider) {
557 return false
558 }
Colin Cross31d89b42022-10-04 16:35:39 -0700559 if !seen[ctx.OtherModuleName(child)] {
560 seen[ctx.OtherModuleName(child)] = true
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000561 deps = append(deps, child)
Hamzeh Zawawy38917492023-04-05 22:08:46 +0000562
563 sharedLibraryInfo := ctx.OtherModuleProvider(child, SharedLibraryInfoProvider).(SharedLibraryInfo)
564 installDestination := sharedLibraryInfo.SharedLibrary.Base()
565 ruleBuilderInstall := android.RuleBuilderInstall{android.OutputFileForModule(ctx, child, "unstripped"), installDestination}
566 sharedLibraries = append(sharedLibraries, ruleBuilderInstall)
Colin Cross31d89b42022-10-04 16:35:39 -0700567 }
568
569 if recursed[ctx.OtherModuleName(child)] {
570 return false
571 }
572 recursed[ctx.OtherModuleName(child)] = true
573 return true
574 })
575
Muhammad Haseeb Ahmad431ddf92022-10-20 00:55:58 +0000576 return sharedLibraries, deps
Colin Cross31d89b42022-10-04 16:35:39 -0700577}