blob: e81b40f54ea5f6164512ff62b9de61ee83365410 [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 (
Kris Alderf979ee32019-10-22 10:52:01 -070018 "encoding/json"
Mitch Phillips4de896e2019-08-28 16:04:36 -070019 "path/filepath"
Mitch Phillipse1ee1a12019-10-17 19:20:41 -070020 "sort"
Mitch Phillipsa0a5e192019-09-27 14:00:06 -070021 "strings"
Mitch Phillips4de896e2019-08-28 16:04:36 -070022
Mitch Phillipsda9a4632019-07-15 09:34:09 -070023 "android/soong/android"
24 "android/soong/cc/config"
25)
26
Kris Alderf979ee32019-10-22 10:52:01 -070027type FuzzConfig struct {
28 // Email address of people to CC on bugs or contact about this fuzz target.
29 Cc []string `json:"cc,omitempty"`
hamzeh3478a0d2019-12-16 16:25:50 -080030 // Specify whether to enable continuous fuzzing on devices. Defaults to true.
31 Fuzz_on_haiku_device *bool `json:"fuzz_on_haiku_device,omitempty"`
32 // Specify whether to enable continuous fuzzing on host. Defaults to true.
33 Fuzz_on_haiku_host *bool `json:"fuzz_on_haiku_host,omitempty"`
Kris Alderf979ee32019-10-22 10:52:01 -070034 // Component in Google's bug tracking system that bugs should be filed to.
35 Componentid *int64 `json:"componentid,omitempty"`
36 // Hotlists in Google's bug tracking system that bugs should be marked with.
37 Hotlists []string `json:"hotlists,omitempty"`
Kris Aldere051d0d2020-04-28 18:32:23 +000038 // Specify whether this fuzz target was submitted by a researcher. Defaults
39 // to false.
40 Researcher_submitted *bool `json:"researcher_submitted,omitempty"`
Kris Alder2598c9b2020-09-29 22:09:36 +000041 // Specify who should be acknowledged for CVEs in the Android Security
42 // Bulletin.
43 Acknowledgement []string `json:"acknowledgement,omitempty"`
Kris Alderf979ee32019-10-22 10:52:01 -070044}
45
46func (f *FuzzConfig) String() string {
47 b, err := json.Marshal(f)
48 if err != nil {
49 panic(err)
50 }
51
52 return string(b)
53}
54
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -070055type FuzzProperties struct {
56 // Optional list of seed files to be installed to the fuzz target's output
57 // directory.
58 Corpus []string `android:"path"`
Tri Voad172d82019-11-27 13:45:45 -080059 // Optional list of data files to be installed to the fuzz target's output
60 // directory. Directory structure relative to the module is preserved.
61 Data []string `android:"path"`
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -070062 // Optional dictionary to be installed to the fuzz target's output directory.
63 Dictionary *string `android:"path"`
Kris Alderf979ee32019-10-22 10:52:01 -070064 // Config for running the target on fuzzing infrastructure.
65 Fuzz_config *FuzzConfig
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -070066}
67
Mitch Phillipsda9a4632019-07-15 09:34:09 -070068func init() {
69 android.RegisterModuleType("cc_fuzz", FuzzFactory)
Mitch Phillipsd3254b42019-09-24 13:03:28 -070070 android.RegisterSingletonType("cc_fuzz_packaging", fuzzPackagingFactory)
Mitch Phillipsda9a4632019-07-15 09:34:09 -070071}
72
73// cc_fuzz creates a host/device fuzzer binary. Host binaries can be found at
74// $ANDROID_HOST_OUT/fuzz/, and device binaries can be found at /data/fuzz on
75// your device, or $ANDROID_PRODUCT_OUT/data/fuzz in your build tree.
76func FuzzFactory() android.Module {
77 module := NewFuzz(android.HostAndDeviceSupported)
78 return module.Init()
79}
80
81func NewFuzzInstaller() *baseInstaller {
82 return NewBaseInstaller("fuzz", "fuzz", InstallInData)
83}
84
85type fuzzBinary struct {
86 *binaryDecorator
87 *baseCompiler
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -070088
Mitch Phillips8a2bc0b2019-10-17 15:04:01 -070089 Properties FuzzProperties
90 dictionary android.Path
91 corpus android.Paths
92 corpusIntermediateDir android.Path
Kris Alderf979ee32019-10-22 10:52:01 -070093 config android.Path
Tri Voad172d82019-11-27 13:45:45 -080094 data android.Paths
95 dataIntermediateDir android.Path
Mitch Phillipse1ee1a12019-10-17 19:20:41 -070096 installedSharedDeps []string
Mitch Phillipsda9a4632019-07-15 09:34:09 -070097}
98
99func (fuzz *fuzzBinary) linkerProps() []interface{} {
100 props := fuzz.binaryDecorator.linkerProps()
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -0700101 props = append(props, &fuzz.Properties)
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700102 return props
103}
104
105func (fuzz *fuzzBinary) linkerInit(ctx BaseModuleContext) {
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700106 fuzz.binaryDecorator.linkerInit(ctx)
107}
108
109func (fuzz *fuzzBinary) linkerDeps(ctx DepsContext, deps Deps) Deps {
110 deps.StaticLibs = append(deps.StaticLibs,
111 config.LibFuzzerRuntimeLibrary(ctx.toolchain()))
112 deps = fuzz.binaryDecorator.linkerDeps(ctx, deps)
113 return deps
114}
115
116func (fuzz *fuzzBinary) linkerFlags(ctx ModuleContext, flags Flags) Flags {
117 flags = fuzz.binaryDecorator.linkerFlags(ctx, flags)
Mitch Phillips1f7f54f2019-11-14 14:50:47 -0800118 // RunPaths on devices isn't instantiated by the base linker. `../lib` for
119 // installed fuzz targets (both host and device), and `./lib` for fuzz
120 // target packages.
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700121 flags.Local.LdFlags = append(flags.Local.LdFlags, `-Wl,-rpath,\$$ORIGIN/../lib`)
Mitch Phillips1f7f54f2019-11-14 14:50:47 -0800122 flags.Local.LdFlags = append(flags.Local.LdFlags, `-Wl,-rpath,\$$ORIGIN/lib`)
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700123 return flags
124}
125
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700126// This function performs a breadth-first search over the provided module's
127// dependencies using `visitDirectDeps` to enumerate all shared library
128// dependencies. We require breadth-first expansion, as otherwise we may
129// incorrectly use the core libraries (sanitizer runtimes, libc, libdl, etc.)
130// from a dependency. This may cause issues when dependencies have explicit
131// sanitizer tags, as we may get a dependency on an unsanitized libc, etc.
Colin Crossdc809f92019-11-20 15:58:32 -0800132func collectAllSharedDependencies(ctx android.SingletonContext, module android.Module) android.Paths {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700133 var fringe []android.Module
134
Mitch Phillipsc0b442f2020-04-27 16:44:58 -0700135 seen := make(map[string]bool)
Colin Crossdc809f92019-11-20 15:58:32 -0800136
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700137 // Enumerate the first level of dependencies, as we discard all non-library
138 // modules in the BFS loop below.
139 ctx.VisitDirectDeps(module, func(dep android.Module) {
Colin Crossdc809f92019-11-20 15:58:32 -0800140 if isValidSharedDependency(dep) {
Mitch Phillipsf50bddb2019-11-12 14:03:31 -0800141 fringe = append(fringe, dep)
142 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700143 })
144
Colin Crossdc809f92019-11-20 15:58:32 -0800145 var sharedLibraries android.Paths
146
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700147 for i := 0; i < len(fringe); i++ {
148 module := fringe[i]
Mitch Phillipsc0b442f2020-04-27 16:44:58 -0700149 if seen[module.Name()] {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700150 continue
151 }
Mitch Phillipsc0b442f2020-04-27 16:44:58 -0700152 seen[module.Name()] = true
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700153
154 ccModule := module.(*Module)
Colin Crossdc809f92019-11-20 15:58:32 -0800155 sharedLibraries = append(sharedLibraries, ccModule.UnstrippedOutputFile())
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700156 ctx.VisitDirectDeps(module, func(dep android.Module) {
Mitch Phillipsc0b442f2020-04-27 16:44:58 -0700157 if isValidSharedDependency(dep) && !seen[dep.Name()] {
Mitch Phillipsf50bddb2019-11-12 14:03:31 -0800158 fringe = append(fringe, dep)
159 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700160 })
161 }
Colin Crossdc809f92019-11-20 15:58:32 -0800162
163 return sharedLibraries
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700164}
165
166// This function takes a module and determines if it is a unique shared library
167// that should be installed in the fuzz target output directories. This function
168// returns true, unless:
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700169// - The module is not a shared library, or
Martin Stjernholm02460ab2020-10-06 02:36:43 +0100170// - The module is a header, stub, or vendor-linked library, or
171// - The module is a prebuilt and its source is available, or
172// - The module is a versioned member of an SDK snapshot.
Colin Crossdc809f92019-11-20 15:58:32 -0800173func isValidSharedDependency(dependency android.Module) bool {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700174 // TODO(b/144090547): We should be parsing these modules using
175 // ModuleDependencyTag instead of the current brute-force checking.
176
177 if linkable, ok := dependency.(LinkableInterface); !ok || // Discard non-linkables.
178 !linkable.CcLibraryInterface() || !linkable.Shared() || // Discard static libs.
179 linkable.UseVndk() || // Discard vendor linked libraries.
Mitch Phillipsf50bddb2019-11-12 14:03:31 -0800180 // Discard stubs libs (only CCLibrary variants). Prebuilt libraries should not
181 // be excluded on the basis of they're not CCLibrary()'s.
182 (linkable.CcLibrary() && linkable.BuildStubs()) {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700183 return false
184 }
185
Mitch Phillipsf50bddb2019-11-12 14:03:31 -0800186 // We discarded module stubs libraries above, but the LLNDK prebuilts stubs
187 // libraries must be handled differently - by looking for the stubDecorator.
188 // Discard LLNDK prebuilts stubs as well.
189 if ccLibrary, isCcLibrary := dependency.(*Module); isCcLibrary {
190 if _, isLLndkStubLibrary := ccLibrary.linker.(*stubDecorator); isLLndkStubLibrary {
191 return false
192 }
193 }
194
Martin Stjernholm02460ab2020-10-06 02:36:43 +0100195 // If the same library is present both as source and a prebuilt we must pick
196 // only one to avoid a conflict. Always prefer the source since the prebuilt
197 // probably won't be built with sanitizers enabled.
198 if prebuilt, ok := dependency.(android.PrebuiltInterface); ok &&
199 prebuilt.Prebuilt() != nil && prebuilt.Prebuilt().SourceExists() {
200 return false
201 }
202
203 // Discard versioned members of SDK snapshots, because they will conflict with
204 // unversioned ones.
205 if sdkMember, ok := dependency.(android.SdkAware); ok && !sdkMember.ContainingSdk().Unversioned() {
206 return false
207 }
208
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700209 return true
210}
211
212func sharedLibraryInstallLocation(
213 libraryPath android.Path, isHost bool, archString string) string {
214 installLocation := "$(PRODUCT_OUT)/data"
215 if isHost {
216 installLocation = "$(HOST_OUT)"
217 }
218 installLocation = filepath.Join(
219 installLocation, "fuzz", archString, "lib", libraryPath.Base())
220 return installLocation
221}
222
Mitch Phillips0bf97132020-03-06 09:38:12 -0800223// Get the device-only shared library symbols install directory.
224func sharedLibrarySymbolsInstallLocation(libraryPath android.Path, archString string) string {
225 return filepath.Join("$(PRODUCT_OUT)/symbols/data/fuzz/", archString, "/lib/", libraryPath.Base())
226}
227
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700228func (fuzz *fuzzBinary) install(ctx ModuleContext, file android.Path) {
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -0700229 fuzz.binaryDecorator.baseInstaller.dir = filepath.Join(
230 "fuzz", ctx.Target().Arch.ArchType.String(), ctx.ModuleName())
231 fuzz.binaryDecorator.baseInstaller.dir64 = filepath.Join(
232 "fuzz", ctx.Target().Arch.ArchType.String(), ctx.ModuleName())
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700233 fuzz.binaryDecorator.baseInstaller.install(ctx, file)
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -0700234
235 fuzz.corpus = android.PathsForModuleSrc(ctx, fuzz.Properties.Corpus)
Mitch Phillips8a2bc0b2019-10-17 15:04:01 -0700236 builder := android.NewRuleBuilder()
237 intermediateDir := android.PathForModuleOut(ctx, "corpus")
238 for _, entry := range fuzz.corpus {
239 builder.Command().Text("cp").
240 Input(entry).
241 Output(intermediateDir.Join(ctx, entry.Base()))
242 }
243 builder.Build(pctx, ctx, "copy_corpus", "copy corpus")
244 fuzz.corpusIntermediateDir = intermediateDir
245
Tri Voad172d82019-11-27 13:45:45 -0800246 fuzz.data = android.PathsForModuleSrc(ctx, fuzz.Properties.Data)
247 builder = android.NewRuleBuilder()
248 intermediateDir = android.PathForModuleOut(ctx, "data")
249 for _, entry := range fuzz.data {
250 builder.Command().Text("cp").
251 Input(entry).
252 Output(intermediateDir.Join(ctx, entry.Rel()))
253 }
254 builder.Build(pctx, ctx, "copy_data", "copy data")
255 fuzz.dataIntermediateDir = intermediateDir
256
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -0700257 if fuzz.Properties.Dictionary != nil {
258 fuzz.dictionary = android.PathForModuleSrc(ctx, *fuzz.Properties.Dictionary)
259 if fuzz.dictionary.Ext() != ".dict" {
260 ctx.PropertyErrorf("dictionary",
261 "Fuzzer dictionary %q does not have '.dict' extension",
262 fuzz.dictionary.String())
263 }
264 }
Kris Alderf979ee32019-10-22 10:52:01 -0700265
266 if fuzz.Properties.Fuzz_config != nil {
Kris Alderdb97af42019-10-30 10:17:04 -0700267 configPath := android.PathForModuleOut(ctx, "config").Join(ctx, "config.json")
Kris Alderf979ee32019-10-22 10:52:01 -0700268 ctx.Build(pctx, android.BuildParams{
269 Rule: android.WriteFile,
270 Description: "fuzzer infrastructure configuration",
271 Output: configPath,
272 Args: map[string]string{
273 "content": fuzz.Properties.Fuzz_config.String(),
274 },
275 })
276 fuzz.config = configPath
277 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700278
279 // Grab the list of required shared libraries.
Mitch Phillipsc0b442f2020-04-27 16:44:58 -0700280 seen := make(map[string]bool)
Colin Crossdc809f92019-11-20 15:58:32 -0800281 var sharedLibraries android.Paths
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700282 ctx.WalkDeps(func(child, parent android.Module) bool {
Mitch Phillipsc0b442f2020-04-27 16:44:58 -0700283 if seen[child.Name()] {
Colin Crossdc809f92019-11-20 15:58:32 -0800284 return false
285 }
Mitch Phillipsc0b442f2020-04-27 16:44:58 -0700286 seen[child.Name()] = true
Colin Crossdc809f92019-11-20 15:58:32 -0800287
288 if isValidSharedDependency(child) {
289 sharedLibraries = append(sharedLibraries, child.(*Module).UnstrippedOutputFile())
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700290 return true
291 }
292 return false
293 })
294
295 for _, lib := range sharedLibraries {
296 fuzz.installedSharedDeps = append(fuzz.installedSharedDeps,
297 sharedLibraryInstallLocation(
298 lib, ctx.Host(), ctx.Arch().ArchType.String()))
Mitch Phillips0bf97132020-03-06 09:38:12 -0800299
300 // Also add the dependency on the shared library symbols dir.
301 if !ctx.Host() {
302 fuzz.installedSharedDeps = append(fuzz.installedSharedDeps,
303 sharedLibrarySymbolsInstallLocation(lib, ctx.Arch().ArchType.String()))
304 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700305 }
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700306}
307
308func NewFuzz(hod android.HostOrDeviceSupported) *Module {
309 module, binary := NewBinary(hod)
310
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700311 binary.baseInstaller = NewFuzzInstaller()
312 module.sanitize.SetSanitizer(fuzzer, true)
313
314 fuzz := &fuzzBinary{
315 binaryDecorator: binary,
316 baseCompiler: NewBaseCompiler(),
317 }
318 module.compiler = fuzz
319 module.linker = fuzz
320 module.installer = fuzz
Colin Crosseec9b282019-07-18 16:20:52 -0700321
322 // The fuzzer runtime is not present for darwin host modules, disable cc_fuzz modules when targeting darwin.
323 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
Alex Light71123ec2019-07-24 13:34:19 -0700324 disableDarwinAndLinuxBionic := struct {
Colin Crosseec9b282019-07-18 16:20:52 -0700325 Target struct {
326 Darwin struct {
327 Enabled *bool
328 }
Alex Light71123ec2019-07-24 13:34:19 -0700329 Linux_bionic struct {
330 Enabled *bool
331 }
Colin Crosseec9b282019-07-18 16:20:52 -0700332 }
333 }{}
Alex Light71123ec2019-07-24 13:34:19 -0700334 disableDarwinAndLinuxBionic.Target.Darwin.Enabled = BoolPtr(false)
335 disableDarwinAndLinuxBionic.Target.Linux_bionic.Enabled = BoolPtr(false)
336 ctx.AppendProperties(&disableDarwinAndLinuxBionic)
Colin Crosseec9b282019-07-18 16:20:52 -0700337 })
338
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700339 return module
340}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700341
342// Responsible for generating GNU Make rules that package fuzz targets into
343// their architecture & target/host specific zip file.
344type fuzzPackager struct {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700345 packages android.Paths
346 sharedLibInstallStrings []string
347 fuzzTargets map[string]bool
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700348}
349
350func fuzzPackagingFactory() android.Singleton {
351 return &fuzzPackager{}
352}
353
354type fileToZip struct {
355 SourceFilePath android.Path
356 DestinationPathPrefix string
357}
358
Colin Crossdc809f92019-11-20 15:58:32 -0800359type archOs struct {
360 hostOrTarget string
361 arch string
362 dir string
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700363}
364
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700365func (s *fuzzPackager) GenerateBuildActions(ctx android.SingletonContext) {
366 // Map between each architecture + host/device combination, and the files that
367 // need to be packaged (in the tuple of {source file, destination folder in
368 // archive}).
Colin Crossdc809f92019-11-20 15:58:32 -0800369 archDirs := make(map[archOs][]fileToZip)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700370
Colin Crossdc809f92019-11-20 15:58:32 -0800371 // Map tracking whether each shared library has an install rule to avoid duplicate install rules from
372 // multiple fuzzers that depend on the same shared library.
373 sharedLibraryInstalled := make(map[string]bool)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700374
375 // List of individual fuzz targets, so that 'make fuzz' also installs the targets
376 // to the correct output directories as well.
377 s.fuzzTargets = make(map[string]bool)
378
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700379 ctx.VisitAllModules(func(module android.Module) {
380 // Discard non-fuzz targets.
381 ccModule, ok := module.(*Module)
382 if !ok {
383 return
384 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700385
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700386 fuzzModule, ok := ccModule.compiler.(*fuzzBinary)
387 if !ok {
388 return
389 }
390
Hamzeh Zawawy0540ae72020-04-25 16:14:52 +0000391 // Discard ramdisk + recovery modules, they're duplicates of
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800392 // fuzz targets we're going to package anyway.
393 if !ccModule.Enabled() || ccModule.Properties.PreventInstall ||
Hamzeh Zawawy0540ae72020-04-25 16:14:52 +0000394 ccModule.InRamdisk() || ccModule.InRecovery() {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700395 return
396 }
397
Mitch Phillips6a9bf212019-12-05 07:36:11 -0800398 // Discard modules that are in an unavailable namespace.
399 if !ccModule.ExportedToMake() {
400 return
401 }
402
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700403 hostOrTargetString := "target"
404 if ccModule.Host() {
405 hostOrTargetString = "host"
406 }
407
408 archString := ccModule.Arch().ArchType.String()
409 archDir := android.PathForIntermediates(ctx, "fuzz", hostOrTargetString, archString)
Colin Crossdc809f92019-11-20 15:58:32 -0800410 archOs := archOs{hostOrTarget: hostOrTargetString, arch: archString, dir: archDir.String()}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700411
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700412 // Grab the list of required shared libraries.
Colin Crossdc809f92019-11-20 15:58:32 -0800413 sharedLibraries := collectAllSharedDependencies(ctx, module)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700414
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800415 var files []fileToZip
416 builder := android.NewRuleBuilder()
417
418 // Package the corpora into a zipfile.
419 if fuzzModule.corpus != nil {
420 corpusZip := archDir.Join(ctx, module.Name()+"_seed_corpus.zip")
421 command := builder.Command().BuiltTool(ctx, "soong_zip").
422 Flag("-j").
423 FlagWithOutput("-o ", corpusZip)
Colin Cross053fca12020-08-19 13:51:47 -0700424 command.FlagWithRspFileInputList("-r ", fuzzModule.corpus)
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800425 files = append(files, fileToZip{corpusZip, ""})
426 }
427
Tri Voad172d82019-11-27 13:45:45 -0800428 // Package the data into a zipfile.
429 if fuzzModule.data != nil {
430 dataZip := archDir.Join(ctx, module.Name()+"_data.zip")
431 command := builder.Command().BuiltTool(ctx, "soong_zip").
432 FlagWithOutput("-o ", dataZip)
433 for _, f := range fuzzModule.data {
434 intermediateDir := strings.TrimSuffix(f.String(), f.Rel())
435 command.FlagWithArg("-C ", intermediateDir)
436 command.FlagWithInput("-f ", f)
437 }
438 files = append(files, fileToZip{dataZip, ""})
439 }
440
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800441 // Find and mark all the transiently-dependent shared libraries for
442 // packaging.
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700443 for _, library := range sharedLibraries {
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800444 files = append(files, fileToZip{library, "lib"})
Mitch Phillips13ed3f52019-11-12 11:12:10 -0800445
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700446 // For each architecture-specific shared library dependency, we need to
447 // install it to the output directory. Setup the install destination here,
448 // which will be used by $(copy-many-files) in the Make backend.
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700449 installDestination := sharedLibraryInstallLocation(
450 library, ccModule.Host(), archString)
Colin Crossdc809f92019-11-20 15:58:32 -0800451 if sharedLibraryInstalled[installDestination] {
452 continue
453 }
454 sharedLibraryInstalled[installDestination] = true
Mitch Phillips0bf97132020-03-06 09:38:12 -0800455
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700456 // Escape all the variables, as the install destination here will be called
457 // via. $(eval) in Make.
458 installDestination = strings.ReplaceAll(
459 installDestination, "$", "$$")
460 s.sharedLibInstallStrings = append(s.sharedLibInstallStrings,
461 library.String()+":"+installDestination)
Mitch Phillips0bf97132020-03-06 09:38:12 -0800462
463 // Ensure that on device, the library is also reinstalled to the /symbols/
464 // dir. Symbolized DSO's are always installed to the device when fuzzing, but
465 // we want symbolization tools (like `stack`) to be able to find the symbols
466 // in $ANDROID_PRODUCT_OUT/symbols automagically.
467 if !ccModule.Host() {
468 symbolsInstallDestination := sharedLibrarySymbolsInstallLocation(library, archString)
469 symbolsInstallDestination = strings.ReplaceAll(symbolsInstallDestination, "$", "$$")
470 s.sharedLibInstallStrings = append(s.sharedLibInstallStrings,
471 library.String()+":"+symbolsInstallDestination)
472 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700473 }
474
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700475 // The executable.
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800476 files = append(files, fileToZip{ccModule.UnstrippedOutputFile(), ""})
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700477
478 // The dictionary.
479 if fuzzModule.dictionary != nil {
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800480 files = append(files, fileToZip{fuzzModule.dictionary, ""})
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700481 }
Kris Alderf979ee32019-10-22 10:52:01 -0700482
483 // Additional fuzz config.
484 if fuzzModule.config != nil {
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800485 files = append(files, fileToZip{fuzzModule.config, ""})
Kris Alderf979ee32019-10-22 10:52:01 -0700486 }
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800487
488 fuzzZip := archDir.Join(ctx, module.Name()+".zip")
489 command := builder.Command().BuiltTool(ctx, "soong_zip").
490 Flag("-j").
491 FlagWithOutput("-o ", fuzzZip)
492 for _, file := range files {
493 if file.DestinationPathPrefix != "" {
494 command.FlagWithArg("-P ", file.DestinationPathPrefix)
495 } else {
496 command.Flag("-P ''")
497 }
498 command.FlagWithInput("-f ", file.SourceFilePath)
499 }
500
501 builder.Build(pctx, ctx, "create-"+fuzzZip.String(),
502 "Package "+module.Name()+" for "+archString+"-"+hostOrTargetString)
503
Mitch Phillips18e67192020-02-24 08:26:20 -0800504 // Don't add modules to 'make haiku' that are set to not be exported to the
505 // fuzzing infrastructure.
506 if config := fuzzModule.Properties.Fuzz_config; config != nil {
507 if ccModule.Host() && !BoolDefault(config.Fuzz_on_haiku_host, true) {
508 return
509 } else if !BoolDefault(config.Fuzz_on_haiku_device, true) {
510 return
511 }
512 }
513
514 s.fuzzTargets[module.Name()] = true
Colin Crossdc809f92019-11-20 15:58:32 -0800515 archDirs[archOs] = append(archDirs[archOs], fileToZip{fuzzZip, ""})
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700516 })
517
Colin Crossdc809f92019-11-20 15:58:32 -0800518 var archOsList []archOs
519 for archOs := range archDirs {
520 archOsList = append(archOsList, archOs)
521 }
522 sort.Slice(archOsList, func(i, j int) bool { return archOsList[i].dir < archOsList[j].dir })
523
524 for _, archOs := range archOsList {
525 filesToZip := archDirs[archOs]
526 arch := archOs.arch
527 hostOrTarget := archOs.hostOrTarget
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700528 builder := android.NewRuleBuilder()
529 outputFile := android.PathForOutput(ctx, "fuzz-"+hostOrTarget+"-"+arch+".zip")
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700530 s.packages = append(s.packages, outputFile)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700531
532 command := builder.Command().BuiltTool(ctx, "soong_zip").
533 Flag("-j").
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800534 FlagWithOutput("-o ", outputFile).
535 Flag("-L 0") // No need to try and re-compress the zipfiles.
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700536
537 for _, fileToZip := range filesToZip {
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800538 if fileToZip.DestinationPathPrefix != "" {
539 command.FlagWithArg("-P ", fileToZip.DestinationPathPrefix)
540 } else {
541 command.Flag("-P ''")
542 }
543 command.FlagWithInput("-f ", fileToZip.SourceFilePath)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700544 }
545
546 builder.Build(pctx, ctx, "create-fuzz-package-"+arch+"-"+hostOrTarget,
547 "Create fuzz target packages for "+arch+"-"+hostOrTarget)
548 }
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700549}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700550
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700551func (s *fuzzPackager) MakeVars(ctx android.MakeVarsContext) {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700552 packages := s.packages.Strings()
553 sort.Strings(packages)
554 sort.Strings(s.sharedLibInstallStrings)
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700555 // TODO(mitchp): Migrate this to use MakeVarsContext::DistForGoal() when it's
556 // ready to handle phony targets created in Soong. In the meantime, this
557 // exports the phony 'fuzz' target and dependencies on packages to
558 // core/main.mk so that we can use dist-for-goals.
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700559 ctx.Strict("SOONG_FUZZ_PACKAGING_ARCH_MODULES", strings.Join(packages, " "))
560 ctx.Strict("FUZZ_TARGET_SHARED_DEPS_INSTALL_PAIRS",
561 strings.Join(s.sharedLibInstallStrings, " "))
562
563 // Preallocate the slice of fuzz targets to minimise memory allocations.
564 fuzzTargets := make([]string, 0, len(s.fuzzTargets))
565 for target, _ := range s.fuzzTargets {
566 fuzzTargets = append(fuzzTargets, target)
567 }
568 sort.Strings(fuzzTargets)
569 ctx.Strict("ALL_FUZZ_TARGETS", strings.Join(fuzzTargets, " "))
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700570}