blob: ef7db7981965c2f35566bc1bf720a1f63559d984 [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"`
30 // Boolean specifying whether to disable the fuzz target from running
31 // automatically in continuous fuzzing infrastructure.
32 Disable *bool `json:"disable,omitempty"`
33 // Component in Google's bug tracking system that bugs should be filed to.
34 Componentid *int64 `json:"componentid,omitempty"`
35 // Hotlists in Google's bug tracking system that bugs should be marked with.
36 Hotlists []string `json:"hotlists,omitempty"`
37}
38
39func (f *FuzzConfig) String() string {
40 b, err := json.Marshal(f)
41 if err != nil {
42 panic(err)
43 }
44
45 return string(b)
46}
47
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -070048type FuzzProperties struct {
49 // Optional list of seed files to be installed to the fuzz target's output
50 // directory.
51 Corpus []string `android:"path"`
52 // Optional dictionary to be installed to the fuzz target's output directory.
53 Dictionary *string `android:"path"`
Kris Alderf979ee32019-10-22 10:52:01 -070054 // Config for running the target on fuzzing infrastructure.
55 Fuzz_config *FuzzConfig
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -070056}
57
Mitch Phillipsda9a4632019-07-15 09:34:09 -070058func init() {
59 android.RegisterModuleType("cc_fuzz", FuzzFactory)
Mitch Phillipsd3254b42019-09-24 13:03:28 -070060 android.RegisterSingletonType("cc_fuzz_packaging", fuzzPackagingFactory)
Mitch Phillipsda9a4632019-07-15 09:34:09 -070061}
62
63// cc_fuzz creates a host/device fuzzer binary. Host binaries can be found at
64// $ANDROID_HOST_OUT/fuzz/, and device binaries can be found at /data/fuzz on
65// your device, or $ANDROID_PRODUCT_OUT/data/fuzz in your build tree.
66func FuzzFactory() android.Module {
67 module := NewFuzz(android.HostAndDeviceSupported)
68 return module.Init()
69}
70
71func NewFuzzInstaller() *baseInstaller {
72 return NewBaseInstaller("fuzz", "fuzz", InstallInData)
73}
74
75type fuzzBinary struct {
76 *binaryDecorator
77 *baseCompiler
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -070078
Mitch Phillips8a2bc0b2019-10-17 15:04:01 -070079 Properties FuzzProperties
80 dictionary android.Path
81 corpus android.Paths
82 corpusIntermediateDir android.Path
Kris Alderf979ee32019-10-22 10:52:01 -070083 config android.Path
Mitch Phillipse1ee1a12019-10-17 19:20:41 -070084 installedSharedDeps []string
Mitch Phillipsda9a4632019-07-15 09:34:09 -070085}
86
87func (fuzz *fuzzBinary) linkerProps() []interface{} {
88 props := fuzz.binaryDecorator.linkerProps()
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -070089 props = append(props, &fuzz.Properties)
Mitch Phillipsda9a4632019-07-15 09:34:09 -070090 return props
91}
92
93func (fuzz *fuzzBinary) linkerInit(ctx BaseModuleContext) {
Mitch Phillipsda9a4632019-07-15 09:34:09 -070094 fuzz.binaryDecorator.linkerInit(ctx)
95}
96
97func (fuzz *fuzzBinary) linkerDeps(ctx DepsContext, deps Deps) Deps {
98 deps.StaticLibs = append(deps.StaticLibs,
99 config.LibFuzzerRuntimeLibrary(ctx.toolchain()))
100 deps = fuzz.binaryDecorator.linkerDeps(ctx, deps)
101 return deps
102}
103
104func (fuzz *fuzzBinary) linkerFlags(ctx ModuleContext, flags Flags) Flags {
105 flags = fuzz.binaryDecorator.linkerFlags(ctx, flags)
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700106 // RunPaths on devices isn't instantiated by the base linker.
107 flags.Local.LdFlags = append(flags.Local.LdFlags, `-Wl,-rpath,\$$ORIGIN/../lib`)
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700108 return flags
109}
110
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700111// This function performs a breadth-first search over the provided module's
112// dependencies using `visitDirectDeps` to enumerate all shared library
113// dependencies. We require breadth-first expansion, as otherwise we may
114// incorrectly use the core libraries (sanitizer runtimes, libc, libdl, etc.)
115// from a dependency. This may cause issues when dependencies have explicit
116// sanitizer tags, as we may get a dependency on an unsanitized libc, etc.
117func collectAllSharedDependencies(
118 module android.Module,
119 sharedDeps map[string]android.Path,
120 ctx android.SingletonContext) {
121 var fringe []android.Module
122
123 // Enumerate the first level of dependencies, as we discard all non-library
124 // modules in the BFS loop below.
125 ctx.VisitDirectDeps(module, func(dep android.Module) {
126 fringe = append(fringe, dep)
127 })
128
129 for i := 0; i < len(fringe); i++ {
130 module := fringe[i]
131 if !isValidSharedDependency(module, sharedDeps) {
132 continue
133 }
134
135 ccModule := module.(*Module)
136 sharedDeps[ccModule.Name()] = ccModule.UnstrippedOutputFile()
137 ctx.VisitDirectDeps(module, func(dep android.Module) {
138 fringe = append(fringe, dep)
139 })
140 }
141}
142
143// This function takes a module and determines if it is a unique shared library
144// that should be installed in the fuzz target output directories. This function
145// returns true, unless:
146// - The module already exists in `sharedDeps`, or
147// - The module is not a shared library, or
148// - The module is a header, stub, or vendor-linked library.
149func isValidSharedDependency(
150 dependency android.Module,
151 sharedDeps map[string]android.Path) bool {
152 // TODO(b/144090547): We should be parsing these modules using
153 // ModuleDependencyTag instead of the current brute-force checking.
154
155 if linkable, ok := dependency.(LinkableInterface); !ok || // Discard non-linkables.
156 !linkable.CcLibraryInterface() || !linkable.Shared() || // Discard static libs.
157 linkable.UseVndk() || // Discard vendor linked libraries.
158 !linkable.CcLibrary() || linkable.BuildStubs() { // Discard stubs libs (only CCLibrary variants).
159 return false
160 }
161
162 // If this library has already been traversed, we don't need to do any more work.
163 if _, exists := sharedDeps[dependency.Name()]; exists {
164 return false
165 }
166 return true
167}
168
169func sharedLibraryInstallLocation(
170 libraryPath android.Path, isHost bool, archString string) string {
171 installLocation := "$(PRODUCT_OUT)/data"
172 if isHost {
173 installLocation = "$(HOST_OUT)"
174 }
175 installLocation = filepath.Join(
176 installLocation, "fuzz", archString, "lib", libraryPath.Base())
177 return installLocation
178}
179
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700180func (fuzz *fuzzBinary) install(ctx ModuleContext, file android.Path) {
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -0700181 fuzz.binaryDecorator.baseInstaller.dir = filepath.Join(
182 "fuzz", ctx.Target().Arch.ArchType.String(), ctx.ModuleName())
183 fuzz.binaryDecorator.baseInstaller.dir64 = filepath.Join(
184 "fuzz", ctx.Target().Arch.ArchType.String(), ctx.ModuleName())
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700185 fuzz.binaryDecorator.baseInstaller.install(ctx, file)
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -0700186
187 fuzz.corpus = android.PathsForModuleSrc(ctx, fuzz.Properties.Corpus)
Mitch Phillips8a2bc0b2019-10-17 15:04:01 -0700188 builder := android.NewRuleBuilder()
189 intermediateDir := android.PathForModuleOut(ctx, "corpus")
190 for _, entry := range fuzz.corpus {
191 builder.Command().Text("cp").
192 Input(entry).
193 Output(intermediateDir.Join(ctx, entry.Base()))
194 }
195 builder.Build(pctx, ctx, "copy_corpus", "copy corpus")
196 fuzz.corpusIntermediateDir = intermediateDir
197
Mitch Phillips4e4ab8a2019-09-13 17:32:50 -0700198 if fuzz.Properties.Dictionary != nil {
199 fuzz.dictionary = android.PathForModuleSrc(ctx, *fuzz.Properties.Dictionary)
200 if fuzz.dictionary.Ext() != ".dict" {
201 ctx.PropertyErrorf("dictionary",
202 "Fuzzer dictionary %q does not have '.dict' extension",
203 fuzz.dictionary.String())
204 }
205 }
Kris Alderf979ee32019-10-22 10:52:01 -0700206
207 if fuzz.Properties.Fuzz_config != nil {
Kris Alderdb97af42019-10-30 10:17:04 -0700208 configPath := android.PathForModuleOut(ctx, "config").Join(ctx, "config.json")
Kris Alderf979ee32019-10-22 10:52:01 -0700209 ctx.Build(pctx, android.BuildParams{
210 Rule: android.WriteFile,
211 Description: "fuzzer infrastructure configuration",
212 Output: configPath,
213 Args: map[string]string{
214 "content": fuzz.Properties.Fuzz_config.String(),
215 },
216 })
217 fuzz.config = configPath
218 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700219
220 // Grab the list of required shared libraries.
221 sharedLibraries := make(map[string]android.Path)
222 ctx.WalkDeps(func(child, parent android.Module) bool {
223 if isValidSharedDependency(child, sharedLibraries) {
224 sharedLibraries[child.Name()] = child.(*Module).UnstrippedOutputFile()
225 return true
226 }
227 return false
228 })
229
230 for _, lib := range sharedLibraries {
231 fuzz.installedSharedDeps = append(fuzz.installedSharedDeps,
232 sharedLibraryInstallLocation(
233 lib, ctx.Host(), ctx.Arch().ArchType.String()))
234 }
Mitch Phillips0553ba32019-11-11 07:03:42 -0800235
236 sort.Strings(fuzz.installedSharedDeps)
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700237}
238
239func NewFuzz(hod android.HostOrDeviceSupported) *Module {
240 module, binary := NewBinary(hod)
241
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700242 binary.baseInstaller = NewFuzzInstaller()
243 module.sanitize.SetSanitizer(fuzzer, true)
244
245 fuzz := &fuzzBinary{
246 binaryDecorator: binary,
247 baseCompiler: NewBaseCompiler(),
248 }
249 module.compiler = fuzz
250 module.linker = fuzz
251 module.installer = fuzz
Colin Crosseec9b282019-07-18 16:20:52 -0700252
253 // The fuzzer runtime is not present for darwin host modules, disable cc_fuzz modules when targeting darwin.
254 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
Alex Light71123ec2019-07-24 13:34:19 -0700255 disableDarwinAndLinuxBionic := struct {
Colin Crosseec9b282019-07-18 16:20:52 -0700256 Target struct {
257 Darwin struct {
258 Enabled *bool
259 }
Alex Light71123ec2019-07-24 13:34:19 -0700260 Linux_bionic struct {
261 Enabled *bool
262 }
Colin Crosseec9b282019-07-18 16:20:52 -0700263 }
264 }{}
Alex Light71123ec2019-07-24 13:34:19 -0700265 disableDarwinAndLinuxBionic.Target.Darwin.Enabled = BoolPtr(false)
266 disableDarwinAndLinuxBionic.Target.Linux_bionic.Enabled = BoolPtr(false)
267 ctx.AppendProperties(&disableDarwinAndLinuxBionic)
Colin Crosseec9b282019-07-18 16:20:52 -0700268 })
269
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700270 return module
271}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700272
273// Responsible for generating GNU Make rules that package fuzz targets into
274// their architecture & target/host specific zip file.
275type fuzzPackager struct {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700276 packages android.Paths
277 sharedLibInstallStrings []string
278 fuzzTargets map[string]bool
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700279}
280
281func fuzzPackagingFactory() android.Singleton {
282 return &fuzzPackager{}
283}
284
285type fileToZip struct {
286 SourceFilePath android.Path
287 DestinationPathPrefix string
288}
289
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700290type archAndLibraryKey struct {
291 ArchDir android.OutputPath
292 Library android.Path
293}
294
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700295func (s *fuzzPackager) GenerateBuildActions(ctx android.SingletonContext) {
296 // Map between each architecture + host/device combination, and the files that
297 // need to be packaged (in the tuple of {source file, destination folder in
298 // archive}).
299 archDirs := make(map[android.OutputPath][]fileToZip)
300
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700301 // List of shared library dependencies for each architecture + host/device combo.
302 archSharedLibraryDeps := make(map[archAndLibraryKey]bool)
303
304 // List of individual fuzz targets, so that 'make fuzz' also installs the targets
305 // to the correct output directories as well.
306 s.fuzzTargets = make(map[string]bool)
307
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700308 ctx.VisitAllModules(func(module android.Module) {
309 // Discard non-fuzz targets.
310 ccModule, ok := module.(*Module)
311 if !ok {
312 return
313 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700314
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700315 fuzzModule, ok := ccModule.compiler.(*fuzzBinary)
316 if !ok {
317 return
318 }
319
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800320 // Discard vendor-NDK-linked + recovery modules, they're duplicates of
321 // fuzz targets we're going to package anyway.
322 if !ccModule.Enabled() || ccModule.Properties.PreventInstall ||
323 ccModule.UseVndk() || ccModule.InRecovery() {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700324 return
325 }
326
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700327 s.fuzzTargets[module.Name()] = true
328
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700329 hostOrTargetString := "target"
330 if ccModule.Host() {
331 hostOrTargetString = "host"
332 }
333
334 archString := ccModule.Arch().ArchType.String()
335 archDir := android.PathForIntermediates(ctx, "fuzz", hostOrTargetString, archString)
336
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700337 // Grab the list of required shared libraries.
338 sharedLibraries := make(map[string]android.Path)
339 collectAllSharedDependencies(module, sharedLibraries, ctx)
340
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800341 var files []fileToZip
342 builder := android.NewRuleBuilder()
343
344 // Package the corpora into a zipfile.
345 if fuzzModule.corpus != nil {
346 corpusZip := archDir.Join(ctx, module.Name()+"_seed_corpus.zip")
347 command := builder.Command().BuiltTool(ctx, "soong_zip").
348 Flag("-j").
349 FlagWithOutput("-o ", corpusZip)
350 command.FlagWithRspFileInputList("-l ", fuzzModule.corpus)
351 files = append(files, fileToZip{corpusZip, ""})
352 }
353
354 // Find and mark all the transiently-dependent shared libraries for
355 // packaging.
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700356 for _, library := range sharedLibraries {
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800357 files = append(files, fileToZip{library, "lib"})
Mitch Phillips13ed3f52019-11-12 11:12:10 -0800358
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700359 if _, exists := archSharedLibraryDeps[archAndLibraryKey{archDir, library}]; exists {
360 continue
361 }
362
363 // For each architecture-specific shared library dependency, we need to
364 // install it to the output directory. Setup the install destination here,
365 // which will be used by $(copy-many-files) in the Make backend.
366 archSharedLibraryDeps[archAndLibraryKey{archDir, library}] = true
367 installDestination := sharedLibraryInstallLocation(
368 library, ccModule.Host(), archString)
369 // Escape all the variables, as the install destination here will be called
370 // via. $(eval) in Make.
371 installDestination = strings.ReplaceAll(
372 installDestination, "$", "$$")
373 s.sharedLibInstallStrings = append(s.sharedLibInstallStrings,
374 library.String()+":"+installDestination)
375 }
376
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700377 // The executable.
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800378 files = append(files, fileToZip{ccModule.UnstrippedOutputFile(), ""})
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700379
380 // The dictionary.
381 if fuzzModule.dictionary != nil {
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800382 files = append(files, fileToZip{fuzzModule.dictionary, ""})
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700383 }
Kris Alderf979ee32019-10-22 10:52:01 -0700384
385 // Additional fuzz config.
386 if fuzzModule.config != nil {
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800387 files = append(files, fileToZip{fuzzModule.config, ""})
Kris Alderf979ee32019-10-22 10:52:01 -0700388 }
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800389
390 fuzzZip := archDir.Join(ctx, module.Name()+".zip")
391 command := builder.Command().BuiltTool(ctx, "soong_zip").
392 Flag("-j").
393 FlagWithOutput("-o ", fuzzZip)
394 for _, file := range files {
395 if file.DestinationPathPrefix != "" {
396 command.FlagWithArg("-P ", file.DestinationPathPrefix)
397 } else {
398 command.Flag("-P ''")
399 }
400 command.FlagWithInput("-f ", file.SourceFilePath)
401 }
402
403 builder.Build(pctx, ctx, "create-"+fuzzZip.String(),
404 "Package "+module.Name()+" for "+archString+"-"+hostOrTargetString)
405
406 archDirs[archDir] = append(archDirs[archDir], fileToZip{fuzzZip, ""})
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700407 })
408
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700409 for archDir, filesToZip := range archDirs {
410 arch := archDir.Base()
411 hostOrTarget := filepath.Base(filepath.Dir(archDir.String()))
412 builder := android.NewRuleBuilder()
413 outputFile := android.PathForOutput(ctx, "fuzz-"+hostOrTarget+"-"+arch+".zip")
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700414 s.packages = append(s.packages, outputFile)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700415
416 command := builder.Command().BuiltTool(ctx, "soong_zip").
417 Flag("-j").
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800418 FlagWithOutput("-o ", outputFile).
419 Flag("-L 0") // No need to try and re-compress the zipfiles.
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700420
421 for _, fileToZip := range filesToZip {
Mitch Phillips2edbe8e2019-11-13 08:36:07 -0800422 if fileToZip.DestinationPathPrefix != "" {
423 command.FlagWithArg("-P ", fileToZip.DestinationPathPrefix)
424 } else {
425 command.Flag("-P ''")
426 }
427 command.FlagWithInput("-f ", fileToZip.SourceFilePath)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700428 }
429
430 builder.Build(pctx, ctx, "create-fuzz-package-"+arch+"-"+hostOrTarget,
431 "Create fuzz target packages for "+arch+"-"+hostOrTarget)
432 }
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700433}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700434
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700435func (s *fuzzPackager) MakeVars(ctx android.MakeVarsContext) {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700436 packages := s.packages.Strings()
437 sort.Strings(packages)
438 sort.Strings(s.sharedLibInstallStrings)
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700439 // TODO(mitchp): Migrate this to use MakeVarsContext::DistForGoal() when it's
440 // ready to handle phony targets created in Soong. In the meantime, this
441 // exports the phony 'fuzz' target and dependencies on packages to
442 // core/main.mk so that we can use dist-for-goals.
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700443 ctx.Strict("SOONG_FUZZ_PACKAGING_ARCH_MODULES", strings.Join(packages, " "))
444 ctx.Strict("FUZZ_TARGET_SHARED_DEPS_INSTALL_PAIRS",
445 strings.Join(s.sharedLibInstallStrings, " "))
446
447 // Preallocate the slice of fuzz targets to minimise memory allocations.
448 fuzzTargets := make([]string, 0, len(s.fuzzTargets))
449 for target, _ := range s.fuzzTargets {
450 fuzzTargets = append(fuzzTargets, target)
451 }
452 sort.Strings(fuzzTargets)
453 ctx.Strict("ALL_FUZZ_TARGETS", strings.Join(fuzzTargets, " "))
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700454}