blob: 1f06fb03c1b0f08bed17268aeeab30ecb838db4a [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 Phillipsda9a4632019-07-15 09:34:09 -0700235}
236
237func NewFuzz(hod android.HostOrDeviceSupported) *Module {
238 module, binary := NewBinary(hod)
239
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700240 binary.baseInstaller = NewFuzzInstaller()
241 module.sanitize.SetSanitizer(fuzzer, true)
242
243 fuzz := &fuzzBinary{
244 binaryDecorator: binary,
245 baseCompiler: NewBaseCompiler(),
246 }
247 module.compiler = fuzz
248 module.linker = fuzz
249 module.installer = fuzz
Colin Crosseec9b282019-07-18 16:20:52 -0700250
251 // The fuzzer runtime is not present for darwin host modules, disable cc_fuzz modules when targeting darwin.
252 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
Alex Light71123ec2019-07-24 13:34:19 -0700253 disableDarwinAndLinuxBionic := struct {
Colin Crosseec9b282019-07-18 16:20:52 -0700254 Target struct {
255 Darwin struct {
256 Enabled *bool
257 }
Alex Light71123ec2019-07-24 13:34:19 -0700258 Linux_bionic struct {
259 Enabled *bool
260 }
Colin Crosseec9b282019-07-18 16:20:52 -0700261 }
262 }{}
Alex Light71123ec2019-07-24 13:34:19 -0700263 disableDarwinAndLinuxBionic.Target.Darwin.Enabled = BoolPtr(false)
264 disableDarwinAndLinuxBionic.Target.Linux_bionic.Enabled = BoolPtr(false)
265 ctx.AppendProperties(&disableDarwinAndLinuxBionic)
Colin Crosseec9b282019-07-18 16:20:52 -0700266 })
267
Mitch Phillipsda9a4632019-07-15 09:34:09 -0700268 return module
269}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700270
271// Responsible for generating GNU Make rules that package fuzz targets into
272// their architecture & target/host specific zip file.
273type fuzzPackager struct {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700274 packages android.Paths
275 sharedLibInstallStrings []string
276 fuzzTargets map[string]bool
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700277}
278
279func fuzzPackagingFactory() android.Singleton {
280 return &fuzzPackager{}
281}
282
283type fileToZip struct {
284 SourceFilePath android.Path
285 DestinationPathPrefix string
286}
287
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700288type archAndLibraryKey struct {
289 ArchDir android.OutputPath
290 Library android.Path
291}
292
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700293func (s *fuzzPackager) GenerateBuildActions(ctx android.SingletonContext) {
294 // Map between each architecture + host/device combination, and the files that
295 // need to be packaged (in the tuple of {source file, destination folder in
296 // archive}).
297 archDirs := make(map[android.OutputPath][]fileToZip)
298
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700299 // List of shared library dependencies for each architecture + host/device combo.
300 archSharedLibraryDeps := make(map[archAndLibraryKey]bool)
301
302 // List of individual fuzz targets, so that 'make fuzz' also installs the targets
303 // to the correct output directories as well.
304 s.fuzzTargets = make(map[string]bool)
305
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700306 ctx.VisitAllModules(func(module android.Module) {
307 // Discard non-fuzz targets.
308 ccModule, ok := module.(*Module)
309 if !ok {
310 return
311 }
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700312
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700313 fuzzModule, ok := ccModule.compiler.(*fuzzBinary)
314 if !ok {
315 return
316 }
317
318 // Discard vendor-NDK-linked modules, they're duplicates of fuzz targets
319 // we're going to package anyway.
Ivan Lozano52767be2019-10-18 14:49:46 -0700320 if ccModule.UseVndk() || !ccModule.Enabled() {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700321 return
322 }
323
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700324 s.fuzzTargets[module.Name()] = true
325
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700326 hostOrTargetString := "target"
327 if ccModule.Host() {
328 hostOrTargetString = "host"
329 }
330
331 archString := ccModule.Arch().ArchType.String()
332 archDir := android.PathForIntermediates(ctx, "fuzz", hostOrTargetString, archString)
333
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700334 // Grab the list of required shared libraries.
335 sharedLibraries := make(map[string]android.Path)
336 collectAllSharedDependencies(module, sharedLibraries, ctx)
337
338 for _, library := range sharedLibraries {
339 if _, exists := archSharedLibraryDeps[archAndLibraryKey{archDir, library}]; exists {
340 continue
341 }
342
343 // For each architecture-specific shared library dependency, we need to
344 // install it to the output directory. Setup the install destination here,
345 // which will be used by $(copy-many-files) in the Make backend.
346 archSharedLibraryDeps[archAndLibraryKey{archDir, library}] = true
347 installDestination := sharedLibraryInstallLocation(
348 library, ccModule.Host(), archString)
349 // Escape all the variables, as the install destination here will be called
350 // via. $(eval) in Make.
351 installDestination = strings.ReplaceAll(
352 installDestination, "$", "$$")
353 s.sharedLibInstallStrings = append(s.sharedLibInstallStrings,
354 library.String()+":"+installDestination)
355 }
356
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700357 // The executable.
358 archDirs[archDir] = append(archDirs[archDir],
Mitch Phillipsd5bd5772019-10-29 17:04:22 -0700359 fileToZip{ccModule.UnstrippedOutputFile(), ccModule.Name()})
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700360
361 // The corpora.
362 for _, corpusEntry := range fuzzModule.corpus {
363 archDirs[archDir] = append(archDirs[archDir],
Mitch Phillips641575a2019-10-09 17:34:42 -0700364 fileToZip{corpusEntry, ccModule.Name() + "/corpus"})
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700365 }
366
367 // The dictionary.
368 if fuzzModule.dictionary != nil {
369 archDirs[archDir] = append(archDirs[archDir],
370 fileToZip{fuzzModule.dictionary, ccModule.Name()})
371 }
Kris Alderf979ee32019-10-22 10:52:01 -0700372
373 // Additional fuzz config.
374 if fuzzModule.config != nil {
375 archDirs[archDir] = append(archDirs[archDir],
376 fileToZip{fuzzModule.config, ccModule.Name()})
377 }
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700378 })
379
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700380 // Add the shared library deps for packaging.
381 for key, _ := range archSharedLibraryDeps {
382 archDirs[key.ArchDir] = append(archDirs[key.ArchDir],
383 fileToZip{key.Library, "lib"})
384 }
385
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700386 for archDir, filesToZip := range archDirs {
387 arch := archDir.Base()
388 hostOrTarget := filepath.Base(filepath.Dir(archDir.String()))
389 builder := android.NewRuleBuilder()
390 outputFile := android.PathForOutput(ctx, "fuzz-"+hostOrTarget+"-"+arch+".zip")
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700391 s.packages = append(s.packages, outputFile)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700392
393 command := builder.Command().BuiltTool(ctx, "soong_zip").
394 Flag("-j").
395 FlagWithOutput("-o ", outputFile)
396
397 for _, fileToZip := range filesToZip {
398 command.FlagWithArg("-P ", fileToZip.DestinationPathPrefix).
399 FlagWithInput("-f ", fileToZip.SourceFilePath)
400 }
401
402 builder.Build(pctx, ctx, "create-fuzz-package-"+arch+"-"+hostOrTarget,
403 "Create fuzz target packages for "+arch+"-"+hostOrTarget)
404 }
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700405}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700406
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700407func (s *fuzzPackager) MakeVars(ctx android.MakeVarsContext) {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700408 packages := s.packages.Strings()
409 sort.Strings(packages)
410 sort.Strings(s.sharedLibInstallStrings)
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700411 // TODO(mitchp): Migrate this to use MakeVarsContext::DistForGoal() when it's
412 // ready to handle phony targets created in Soong. In the meantime, this
413 // exports the phony 'fuzz' target and dependencies on packages to
414 // core/main.mk so that we can use dist-for-goals.
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700415 ctx.Strict("SOONG_FUZZ_PACKAGING_ARCH_MODULES", strings.Join(packages, " "))
416 ctx.Strict("FUZZ_TARGET_SHARED_DEPS_INSTALL_PAIRS",
417 strings.Join(s.sharedLibInstallStrings, " "))
418
419 // Preallocate the slice of fuzz targets to minimise memory allocations.
420 fuzzTargets := make([]string, 0, len(s.fuzzTargets))
421 for target, _ := range s.fuzzTargets {
422 fuzzTargets = append(fuzzTargets, target)
423 }
424 sort.Strings(fuzzTargets)
425 ctx.Strict("ALL_FUZZ_TARGETS", strings.Join(fuzzTargets, " "))
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700426}