blob: 4b537c0a8dec0d4e6a275a40f4a71816e88f7000 [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
320 // Discard vendor-NDK-linked modules, they're duplicates of fuzz targets
321 // we're going to package anyway.
Ivan Lozano52767be2019-10-18 14:49:46 -0700322 if ccModule.UseVndk() || !ccModule.Enabled() {
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700323 return
324 }
325
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700326 s.fuzzTargets[module.Name()] = true
327
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700328 hostOrTargetString := "target"
329 if ccModule.Host() {
330 hostOrTargetString = "host"
331 }
332
333 archString := ccModule.Arch().ArchType.String()
334 archDir := android.PathForIntermediates(ctx, "fuzz", hostOrTargetString, archString)
335
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700336 // Grab the list of required shared libraries.
337 sharedLibraries := make(map[string]android.Path)
338 collectAllSharedDependencies(module, sharedLibraries, ctx)
339
340 for _, library := range sharedLibraries {
Mitch Phillips13ed3f52019-11-12 11:12:10 -0800341 archDirs[archDir] = append(archDirs[archDir],
342 fileToZip{library, ccModule.Name() + "/lib"})
343
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700344 if _, exists := archSharedLibraryDeps[archAndLibraryKey{archDir, library}]; exists {
345 continue
346 }
347
348 // For each architecture-specific shared library dependency, we need to
349 // install it to the output directory. Setup the install destination here,
350 // which will be used by $(copy-many-files) in the Make backend.
351 archSharedLibraryDeps[archAndLibraryKey{archDir, library}] = true
352 installDestination := sharedLibraryInstallLocation(
353 library, ccModule.Host(), archString)
354 // Escape all the variables, as the install destination here will be called
355 // via. $(eval) in Make.
356 installDestination = strings.ReplaceAll(
357 installDestination, "$", "$$")
358 s.sharedLibInstallStrings = append(s.sharedLibInstallStrings,
359 library.String()+":"+installDestination)
360 }
361
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700362 // The executable.
363 archDirs[archDir] = append(archDirs[archDir],
Mitch Phillipsd5bd5772019-10-29 17:04:22 -0700364 fileToZip{ccModule.UnstrippedOutputFile(), ccModule.Name()})
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700365
366 // The corpora.
367 for _, corpusEntry := range fuzzModule.corpus {
368 archDirs[archDir] = append(archDirs[archDir],
Mitch Phillips641575a2019-10-09 17:34:42 -0700369 fileToZip{corpusEntry, ccModule.Name() + "/corpus"})
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700370 }
371
372 // The dictionary.
373 if fuzzModule.dictionary != nil {
374 archDirs[archDir] = append(archDirs[archDir],
375 fileToZip{fuzzModule.dictionary, ccModule.Name()})
376 }
Kris Alderf979ee32019-10-22 10:52:01 -0700377
378 // Additional fuzz config.
379 if fuzzModule.config != nil {
380 archDirs[archDir] = append(archDirs[archDir],
381 fileToZip{fuzzModule.config, ccModule.Name()})
382 }
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700383 })
384
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700385 for archDir, filesToZip := range archDirs {
386 arch := archDir.Base()
387 hostOrTarget := filepath.Base(filepath.Dir(archDir.String()))
388 builder := android.NewRuleBuilder()
389 outputFile := android.PathForOutput(ctx, "fuzz-"+hostOrTarget+"-"+arch+".zip")
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700390 s.packages = append(s.packages, outputFile)
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700391
392 command := builder.Command().BuiltTool(ctx, "soong_zip").
393 Flag("-j").
394 FlagWithOutput("-o ", outputFile)
395
396 for _, fileToZip := range filesToZip {
397 command.FlagWithArg("-P ", fileToZip.DestinationPathPrefix).
398 FlagWithInput("-f ", fileToZip.SourceFilePath)
399 }
400
401 builder.Build(pctx, ctx, "create-fuzz-package-"+arch+"-"+hostOrTarget,
402 "Create fuzz target packages for "+arch+"-"+hostOrTarget)
403 }
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700404}
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700405
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700406func (s *fuzzPackager) MakeVars(ctx android.MakeVarsContext) {
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700407 packages := s.packages.Strings()
408 sort.Strings(packages)
409 sort.Strings(s.sharedLibInstallStrings)
Mitch Phillipsa0a5e192019-09-27 14:00:06 -0700410 // TODO(mitchp): Migrate this to use MakeVarsContext::DistForGoal() when it's
411 // ready to handle phony targets created in Soong. In the meantime, this
412 // exports the phony 'fuzz' target and dependencies on packages to
413 // core/main.mk so that we can use dist-for-goals.
Mitch Phillipse1ee1a12019-10-17 19:20:41 -0700414 ctx.Strict("SOONG_FUZZ_PACKAGING_ARCH_MODULES", strings.Join(packages, " "))
415 ctx.Strict("FUZZ_TARGET_SHARED_DEPS_INSTALL_PAIRS",
416 strings.Join(s.sharedLibInstallStrings, " "))
417
418 // Preallocate the slice of fuzz targets to minimise memory allocations.
419 fuzzTargets := make([]string, 0, len(s.fuzzTargets))
420 for target, _ := range s.fuzzTargets {
421 fuzzTargets = append(fuzzTargets, target)
422 }
423 sort.Strings(fuzzTargets)
424 ctx.Strict("ALL_FUZZ_TARGETS", strings.Join(fuzzTargets, " "))
Mitch Phillipsd3254b42019-09-24 13:03:28 -0700425}