blob: fe3c12bf56c857bed3431d0c3c1af7ae2e671515 [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
Colin Cross31076b32020-10-23 17:22:06 -0700177 linkable, ok := dependency.(LinkableInterface)
178 if !ok || !linkable.CcLibraryInterface() {
179 // Discard non-linkables.
180 return false
181 }
182
183 if !linkable.Shared() {
184 // Discard static libs.
185 return false
186 }
187
188 if linkable.UseVndk() {
189 // Discard vendor linked libraries.
190 return false
191 }
192
193 if lib := moduleLibraryInterface(dependency); lib != nil && lib.buildStubs() && linkable.CcLibrary() {
Mitch Phillipsf50bddb2019-11-12 14:03:31 -0800194 // Discard stubs libs (only CCLibrary variants). Prebuilt libraries should not
195 // be excluded on the basis of they're not CCLibrary()'s.
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700196 return false
197 }
198
Mitch Phillipsf50bddb2019-11-12 14:03:31 -0800199 // We discarded module stubs libraries above, but the LLNDK prebuilts stubs
200 // libraries must be handled differently - by looking for the stubDecorator.
201 // Discard LLNDK prebuilts stubs as well.
202 if ccLibrary, isCcLibrary := dependency.(*Module); isCcLibrary {
203 if _, isLLndkStubLibrary := ccLibrary.linker.(*stubDecorator); isLLndkStubLibrary {
204 return false
205 }
206 }
207
Martin Stjernholm02460ab2020-10-06 02:36:43 +0100208 // If the same library is present both as source and a prebuilt we must pick
209 // only one to avoid a conflict. Always prefer the source since the prebuilt
210 // probably won't be built with sanitizers enabled.
211 if prebuilt, ok := dependency.(android.PrebuiltInterface); ok &&
212 prebuilt.Prebuilt() != nil && prebuilt.Prebuilt().SourceExists() {
213 return false
214 }
215
216 // Discard versioned members of SDK snapshots, because they will conflict with
217 // unversioned ones.
218 if sdkMember, ok := dependency.(android.SdkAware); ok && !sdkMember.ContainingSdk().Unversioned() {
219 return false
220 }
221
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700222 return true
223}
224
225func sharedLibraryInstallLocation(
226 libraryPath android.Path, isHost bool, archString string) string {
227 installLocation := "$(PRODUCT_OUT)/data"
228 if isHost {
229 installLocation = "$(HOST_OUT)"
230 }
231 installLocation = filepath.Join(
232 installLocation, "fuzz", archString, "lib", libraryPath.Base())
233 return installLocation
234}
235
Mitch Phillips0bf97132020-03-06 09:38:12 -0800236// Get the device-only shared library symbols install directory.
237func sharedLibrarySymbolsInstallLocation(libraryPath android.Path, archString string) string {
238 return filepath.Join("$(PRODUCT_OUT)/symbols/data/fuzz/", archString, "/lib/", libraryPath.Base())
239}
240
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700241func (fuzz *fuzzBinary) install(ctx ModuleContext, file android.Path) {
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -0700242 fuzz.binaryDecorator.baseInstaller.dir = filepath.Join(
243 "fuzz", ctx.Target().Arch.ArchType.String(), ctx.ModuleName())
244 fuzz.binaryDecorator.baseInstaller.dir64 = filepath.Join(
245 "fuzz", ctx.Target().Arch.ArchType.String(), ctx.ModuleName())
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700246 fuzz.binaryDecorator.baseInstaller.install(ctx, file)
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -0700247
248 fuzz.corpus = android.PathsForModuleSrc(ctx, fuzz.Properties.Corpus)
Mitch Phillips8a2bc0b2019-10-17 15:04:01 -0700249 builder := android.NewRuleBuilder()
250 intermediateDir := android.PathForModuleOut(ctx, "corpus")
251 for _, entry := range fuzz.corpus {
252 builder.Command().Text("cp").
253 Input(entry).
254 Output(intermediateDir.Join(ctx, entry.Base()))
255 }
256 builder.Build(pctx, ctx, "copy_corpus", "copy corpus")
257 fuzz.corpusIntermediateDir = intermediateDir
258
Tri Voad172d82019-11-27 13:45:45 -0800259 fuzz.data = android.PathsForModuleSrc(ctx, fuzz.Properties.Data)
260 builder = android.NewRuleBuilder()
261 intermediateDir = android.PathForModuleOut(ctx, "data")
262 for _, entry := range fuzz.data {
263 builder.Command().Text("cp").
264 Input(entry).
265 Output(intermediateDir.Join(ctx, entry.Rel()))
266 }
267 builder.Build(pctx, ctx, "copy_data", "copy data")
268 fuzz.dataIntermediateDir = intermediateDir
269
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -0700270 if fuzz.Properties.Dictionary != nil {
271 fuzz.dictionary = android.PathForModuleSrc(ctx, *fuzz.Properties.Dictionary)
272 if fuzz.dictionary.Ext() != ".dict" {
273 ctx.PropertyErrorf("dictionary",
274 "Fuzzer dictionary %q does not have '.dict' extension",
275 fuzz.dictionary.String())
276 }
277 }
Kris Alderf979ee32019-10-22 10:52:01 -0700278
279 if fuzz.Properties.Fuzz_config != nil {
Kris Alderdb97af42019-10-30 10:17:04 -0700280 configPath := android.PathForModuleOut(ctx, "config").Join(ctx, "config.json")
Kris Alderf979ee32019-10-22 10:52:01 -0700281 ctx.Build(pctx, android.BuildParams{
282 Rule: android.WriteFile,
283 Description: "fuzzer infrastructure configuration",
284 Output: configPath,
285 Args: map[string]string{
286 "content": fuzz.Properties.Fuzz_config.String(),
287 },
288 })
289 fuzz.config = configPath
290 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700291
292 // Grab the list of required shared libraries.
Mitch Phillipsc0b442f2020-04-27 16:44:58 -0700293 seen := make(map[string]bool)
Colin Crossdc809f92019-11-20 15:58:32 -0800294 var sharedLibraries android.Paths
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700295 ctx.WalkDeps(func(child, parent android.Module) bool {
Mitch Phillipsc0b442f2020-04-27 16:44:58 -0700296 if seen[child.Name()] {
Colin Crossdc809f92019-11-20 15:58:32 -0800297 return false
298 }
Mitch Phillipsc0b442f2020-04-27 16:44:58 -0700299 seen[child.Name()] = true
Colin Crossdc809f92019-11-20 15:58:32 -0800300
301 if isValidSharedDependency(child) {
302 sharedLibraries = append(sharedLibraries, child.(*Module).UnstrippedOutputFile())
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700303 return true
304 }
305 return false
306 })
307
308 for _, lib := range sharedLibraries {
309 fuzz.installedSharedDeps = append(fuzz.installedSharedDeps,
310 sharedLibraryInstallLocation(
311 lib, ctx.Host(), ctx.Arch().ArchType.String()))
Mitch Phillips0bf97132020-03-06 09:38:12 -0800312
313 // Also add the dependency on the shared library symbols dir.
314 if !ctx.Host() {
315 fuzz.installedSharedDeps = append(fuzz.installedSharedDeps,
316 sharedLibrarySymbolsInstallLocation(lib, ctx.Arch().ArchType.String()))
317 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700318 }
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700319}
320
321func NewFuzz(hod android.HostOrDeviceSupported) *Module {
322 module, binary := NewBinary(hod)
323
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700324 binary.baseInstaller = NewFuzzInstaller()
325 module.sanitize.SetSanitizer(fuzzer, true)
326
327 fuzz := &fuzzBinary{
328 binaryDecorator: binary,
329 baseCompiler: NewBaseCompiler(),
330 }
331 module.compiler = fuzz
332 module.linker = fuzz
333 module.installer = fuzz
Colin Crosseec9b282019-07-18 16:20:52 -0700334
335 // The fuzzer runtime is not present for darwin host modules, disable cc_fuzz modules when targeting darwin.
336 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
Alex Light71123ec2019-07-24 13:34:19 -0700337 disableDarwinAndLinuxBionic := struct {
Colin Crosseec9b282019-07-18 16:20:52 -0700338 Target struct {
339 Darwin struct {
340 Enabled *bool
341 }
Alex Light71123ec2019-07-24 13:34:19 -0700342 Linux_bionic struct {
343 Enabled *bool
344 }
Colin Crosseec9b282019-07-18 16:20:52 -0700345 }
346 }{}
Alex Light71123ec2019-07-24 13:34:19 -0700347 disableDarwinAndLinuxBionic.Target.Darwin.Enabled = BoolPtr(false)
348 disableDarwinAndLinuxBionic.Target.Linux_bionic.Enabled = BoolPtr(false)
349 ctx.AppendProperties(&disableDarwinAndLinuxBionic)
Colin Crosseec9b282019-07-18 16:20:52 -0700350 })
351
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.
357type fuzzPackager struct {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700358 packages android.Paths
359 sharedLibInstallStrings []string
360 fuzzTargets map[string]bool
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700361}
362
363func fuzzPackagingFactory() android.Singleton {
364 return &fuzzPackager{}
365}
366
367type fileToZip struct {
368 SourceFilePath android.Path
369 DestinationPathPrefix string
370}
371
Colin Crossdc809f92019-11-20 15:58:32 -0800372type archOs struct {
373 hostOrTarget string
374 arch string
375 dir string
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700376}
377
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700378func (s *fuzzPackager) GenerateBuildActions(ctx android.SingletonContext) {
379 // Map between each architecture + host/device combination, and the files that
380 // need to be packaged (in the tuple of {source file, destination folder in
381 // archive}).
Colin Crossdc809f92019-11-20 15:58:32 -0800382 archDirs := make(map[archOs][]fileToZip)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700383
Colin Crossdc809f92019-11-20 15:58:32 -0800384 // 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)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700387
388 // List of individual fuzz targets, so that 'make fuzz' also installs the targets
389 // to the correct output directories as well.
390 s.fuzzTargets = make(map[string]bool)
391
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700392 ctx.VisitAllModules(func(module android.Module) {
393 // Discard non-fuzz targets.
394 ccModule, ok := module.(*Module)
395 if !ok {
396 return
397 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700398
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700399 fuzzModule, ok := ccModule.compiler.(*fuzzBinary)
400 if !ok {
401 return
402 }
403
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700404 // Discard ramdisk + vendor_ramdisk + recovery modules, they're duplicates of
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800405 // fuzz targets we're going to package anyway.
406 if !ccModule.Enabled() || ccModule.Properties.PreventInstall ||
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700407 ccModule.InRamdisk() || ccModule.InVendorRamdisk() || ccModule.InRecovery() {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700408 return
409 }
410
Mitch Phillips6a9bf212019-12-05 07:36:11 -0800411 // Discard modules that are in an unavailable namespace.
412 if !ccModule.ExportedToMake() {
413 return
414 }
415
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700416 hostOrTargetString := "target"
417 if ccModule.Host() {
418 hostOrTargetString = "host"
419 }
420
421 archString := ccModule.Arch().ArchType.String()
422 archDir := android.PathForIntermediates(ctx, "fuzz", hostOrTargetString, archString)
Colin Crossdc809f92019-11-20 15:58:32 -0800423 archOs := archOs{hostOrTarget: hostOrTargetString, arch: archString, dir: archDir.String()}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700424
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700425 // Grab the list of required shared libraries.
Colin Crossdc809f92019-11-20 15:58:32 -0800426 sharedLibraries := collectAllSharedDependencies(ctx, module)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700427
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800428 var files []fileToZip
429 builder := android.NewRuleBuilder()
430
431 // Package the corpora into a zipfile.
432 if fuzzModule.corpus != nil {
433 corpusZip := archDir.Join(ctx, module.Name()+"_seed_corpus.zip")
434 command := builder.Command().BuiltTool(ctx, "soong_zip").
435 Flag("-j").
436 FlagWithOutput("-o ", corpusZip)
Colin Cross053fca12020-08-19 13:51:47 -0700437 command.FlagWithRspFileInputList("-r ", fuzzModule.corpus)
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800438 files = append(files, fileToZip{corpusZip, ""})
439 }
440
Tri Voad172d82019-11-27 13:45:45 -0800441 // Package the data into a zipfile.
442 if fuzzModule.data != nil {
443 dataZip := archDir.Join(ctx, module.Name()+"_data.zip")
444 command := builder.Command().BuiltTool(ctx, "soong_zip").
445 FlagWithOutput("-o ", dataZip)
446 for _, f := range fuzzModule.data {
447 intermediateDir := strings.TrimSuffix(f.String(), f.Rel())
448 command.FlagWithArg("-C ", intermediateDir)
449 command.FlagWithInput("-f ", f)
450 }
451 files = append(files, fileToZip{dataZip, ""})
452 }
453
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800454 // Find and mark all the transiently-dependent shared libraries for
455 // packaging.
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700456 for _, library := range sharedLibraries {
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800457 files = append(files, fileToZip{library, "lib"})
Mitch Phillips13ed3f52019-11-12 11:12:10 -0800458
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700459 // For each architecture-specific shared library dependency, we need to
460 // install it to the output directory. Setup the install destination here,
461 // which will be used by $(copy-many-files) in the Make backend.
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700462 installDestination := sharedLibraryInstallLocation(
463 library, ccModule.Host(), archString)
Colin Crossdc809f92019-11-20 15:58:32 -0800464 if sharedLibraryInstalled[installDestination] {
465 continue
466 }
467 sharedLibraryInstalled[installDestination] = true
Mitch Phillips0bf97132020-03-06 09:38:12 -0800468
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700469 // Escape all the variables, as the install destination here will be called
470 // via. $(eval) in Make.
471 installDestination = strings.ReplaceAll(
472 installDestination, "$", "$$")
473 s.sharedLibInstallStrings = append(s.sharedLibInstallStrings,
474 library.String()+":"+installDestination)
Mitch Phillips0bf97132020-03-06 09:38:12 -0800475
476 // Ensure that on device, the library is also reinstalled to the /symbols/
477 // dir. Symbolized DSO's are always installed to the device when fuzzing, but
478 // we want symbolization tools (like `stack`) to be able to find the symbols
479 // in $ANDROID_PRODUCT_OUT/symbols automagically.
480 if !ccModule.Host() {
481 symbolsInstallDestination := sharedLibrarySymbolsInstallLocation(library, archString)
482 symbolsInstallDestination = strings.ReplaceAll(symbolsInstallDestination, "$", "$$")
483 s.sharedLibInstallStrings = append(s.sharedLibInstallStrings,
484 library.String()+":"+symbolsInstallDestination)
485 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700486 }
487
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700488 // The executable.
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800489 files = append(files, fileToZip{ccModule.UnstrippedOutputFile(), ""})
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700490
491 // The dictionary.
492 if fuzzModule.dictionary != nil {
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800493 files = append(files, fileToZip{fuzzModule.dictionary, ""})
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700494 }
Kris Alderf979ee32019-10-22 10:52:01 -0700495
496 // Additional fuzz config.
497 if fuzzModule.config != nil {
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800498 files = append(files, fileToZip{fuzzModule.config, ""})
Kris Alderf979ee32019-10-22 10:52:01 -0700499 }
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800500
501 fuzzZip := archDir.Join(ctx, module.Name()+".zip")
502 command := builder.Command().BuiltTool(ctx, "soong_zip").
503 Flag("-j").
504 FlagWithOutput("-o ", fuzzZip)
505 for _, file := range files {
506 if file.DestinationPathPrefix != "" {
507 command.FlagWithArg("-P ", file.DestinationPathPrefix)
508 } else {
509 command.Flag("-P ''")
510 }
511 command.FlagWithInput("-f ", file.SourceFilePath)
512 }
513
514 builder.Build(pctx, ctx, "create-"+fuzzZip.String(),
515 "Package "+module.Name()+" for "+archString+"-"+hostOrTargetString)
516
Mitch Phillips18e67192020-02-24 08:26:20 -0800517 // Don't add modules to 'make haiku' that are set to not be exported to the
518 // fuzzing infrastructure.
519 if config := fuzzModule.Properties.Fuzz_config; config != nil {
520 if ccModule.Host() && !BoolDefault(config.Fuzz_on_haiku_host, true) {
521 return
522 } else if !BoolDefault(config.Fuzz_on_haiku_device, true) {
523 return
524 }
525 }
526
527 s.fuzzTargets[module.Name()] = true
Colin Crossdc809f92019-11-20 15:58:32 -0800528 archDirs[archOs] = append(archDirs[archOs], fileToZip{fuzzZip, ""})
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700529 })
530
Colin Crossdc809f92019-11-20 15:58:32 -0800531 var archOsList []archOs
532 for archOs := range archDirs {
533 archOsList = append(archOsList, archOs)
534 }
535 sort.Slice(archOsList, func(i, j int) bool { return archOsList[i].dir < archOsList[j].dir })
536
537 for _, archOs := range archOsList {
538 filesToZip := archDirs[archOs]
539 arch := archOs.arch
540 hostOrTarget := archOs.hostOrTarget
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700541 builder := android.NewRuleBuilder()
542 outputFile := android.PathForOutput(ctx, "fuzz-"+hostOrTarget+"-"+arch+".zip")
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700543 s.packages = append(s.packages, outputFile)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700544
545 command := builder.Command().BuiltTool(ctx, "soong_zip").
546 Flag("-j").
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800547 FlagWithOutput("-o ", outputFile).
548 Flag("-L 0") // No need to try and re-compress the zipfiles.
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700549
550 for _, fileToZip := range filesToZip {
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800551 if fileToZip.DestinationPathPrefix != "" {
552 command.FlagWithArg("-P ", fileToZip.DestinationPathPrefix)
553 } else {
554 command.Flag("-P ''")
555 }
556 command.FlagWithInput("-f ", fileToZip.SourceFilePath)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700557 }
558
559 builder.Build(pctx, ctx, "create-fuzz-package-"+arch+"-"+hostOrTarget,
560 "Create fuzz target packages for "+arch+"-"+hostOrTarget)
561 }
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700562}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700563
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700564func (s *fuzzPackager) MakeVars(ctx android.MakeVarsContext) {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700565 packages := s.packages.Strings()
566 sort.Strings(packages)
567 sort.Strings(s.sharedLibInstallStrings)
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700568 // TODO(mitchp): Migrate this to use MakeVarsContext::DistForGoal() when it's
569 // ready to handle phony targets created in Soong. In the meantime, this
570 // exports the phony 'fuzz' target and dependencies on packages to
571 // core/main.mk so that we can use dist-for-goals.
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700572 ctx.Strict("SOONG_FUZZ_PACKAGING_ARCH_MODULES", strings.Join(packages, " "))
573 ctx.Strict("FUZZ_TARGET_SHARED_DEPS_INSTALL_PAIRS",
574 strings.Join(s.sharedLibInstallStrings, " "))
575
576 // Preallocate the slice of fuzz targets to minimise memory allocations.
577 fuzzTargets := make([]string, 0, len(s.fuzzTargets))
578 for target, _ := range s.fuzzTargets {
579 fuzzTargets = append(fuzzTargets, target)
580 }
581 sort.Strings(fuzzTargets)
582 ctx.Strict("ALL_FUZZ_TARGETS", strings.Join(fuzzTargets, " "))
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700583}