blob: 700cdf0a7b4cd4107c6de313f9b6a756fb37dd85 [file] [log] [blame]
hamzeh41ad8812021-07-07 14:00:07 -07001// Copyright 2021 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
hamzehc0a671f2021-07-22 12:05:08 -070015package fuzz
hamzeh41ad8812021-07-07 14:00:07 -070016
17// This file contains the common code for compiling C/C++ and Rust fuzzers for Android.
18
19import (
hamzehc0a671f2021-07-22 12:05:08 -070020 "encoding/json"
hamzeh41ad8812021-07-07 14:00:07 -070021 "sort"
22 "strings"
23
hamzehc0a671f2021-07-22 12:05:08 -070024 "github.com/google/blueprint/proptools"
25
hamzeh41ad8812021-07-07 14:00:07 -070026 "android/soong/android"
27)
28
29type Lang string
30
31const (
32 Cc Lang = ""
33 Rust Lang = "rust"
Muhammad Haseeb Ahmade3803102022-01-10 21:37:07 +000034 Java Lang = "java"
hamzeh41ad8812021-07-07 14:00:07 -070035)
36
hamzehc0a671f2021-07-22 12:05:08 -070037var BoolDefault = proptools.BoolDefault
38
hamzeh41ad8812021-07-07 14:00:07 -070039type FuzzModule struct {
40 android.ModuleBase
41 android.DefaultableModuleBase
42 android.ApexModuleBase
43}
44
45type FuzzPackager struct {
Ivan Lozano39b0bf02021-10-14 12:22:09 -040046 Packages android.Paths
47 FuzzTargets map[string]bool
48 SharedLibInstallStrings []string
hamzeh41ad8812021-07-07 14:00:07 -070049}
50
51type FileToZip struct {
52 SourceFilePath android.Path
53 DestinationPathPrefix string
54}
55
56type ArchOs struct {
57 HostOrTarget string
58 Arch string
59 Dir string
60}
61
hamzehc0a671f2021-07-22 12:05:08 -070062type FuzzConfig struct {
63 // Email address of people to CC on bugs or contact about this fuzz target.
64 Cc []string `json:"cc,omitempty"`
65 // Specify whether to enable continuous fuzzing on devices. Defaults to true.
66 Fuzz_on_haiku_device *bool `json:"fuzz_on_haiku_device,omitempty"`
67 // Specify whether to enable continuous fuzzing on host. Defaults to true.
68 Fuzz_on_haiku_host *bool `json:"fuzz_on_haiku_host,omitempty"`
69 // Component in Google's bug tracking system that bugs should be filed to.
70 Componentid *int64 `json:"componentid,omitempty"`
71 // Hotlists in Google's bug tracking system that bugs should be marked with.
72 Hotlists []string `json:"hotlists,omitempty"`
73 // Specify whether this fuzz target was submitted by a researcher. Defaults
74 // to false.
75 Researcher_submitted *bool `json:"researcher_submitted,omitempty"`
76 // Specify who should be acknowledged for CVEs in the Android Security
77 // Bulletin.
78 Acknowledgement []string `json:"acknowledgement,omitempty"`
79 // Additional options to be passed to libfuzzer when run in Haiku.
80 Libfuzzer_options []string `json:"libfuzzer_options,omitempty"`
81 // Additional options to be passed to HWASAN when running on-device in Haiku.
82 Hwasan_options []string `json:"hwasan_options,omitempty"`
83 // Additional options to be passed to HWASAN when running on host in Haiku.
84 Asan_options []string `json:"asan_options,omitempty"`
Muhammad Haseeb Ahmad7e744052022-03-25 22:50:53 +000085 // If there's a Java fuzzer with JNI, a different version of Jazzer would
86 // need to be added to the fuzzer package than one without JNI
87 IsJni *bool `json:"is_jni,omitempty"`
hamzehc0a671f2021-07-22 12:05:08 -070088}
89
90type FuzzProperties struct {
91 // Optional list of seed files to be installed to the fuzz target's output
92 // directory.
93 Corpus []string `android:"path"`
94 // Optional list of data files to be installed to the fuzz target's output
95 // directory. Directory structure relative to the module is preserved.
96 Data []string `android:"path"`
97 // Optional dictionary to be installed to the fuzz target's output directory.
98 Dictionary *string `android:"path"`
99 // Config for running the target on fuzzing infrastructure.
100 Fuzz_config *FuzzConfig
101}
102
hamzeh41ad8812021-07-07 14:00:07 -0700103type FuzzPackagedModule struct {
104 FuzzProperties FuzzProperties
105 Dictionary android.Path
106 Corpus android.Paths
107 CorpusIntermediateDir android.Path
108 Config android.Path
109 Data android.Paths
110 DataIntermediateDir android.Path
111}
112
113func IsValid(fuzzModule FuzzModule) bool {
114 // Discard ramdisk + vendor_ramdisk + recovery modules, they're duplicates of
115 // fuzz targets we're going to package anyway.
116 if !fuzzModule.Enabled() || fuzzModule.InRamdisk() || fuzzModule.InVendorRamdisk() || fuzzModule.InRecovery() {
117 return false
118 }
119
120 // Discard modules that are in an unavailable namespace.
121 if !fuzzModule.ExportedToMake() {
122 return false
123 }
124
125 return true
126}
127
128func (s *FuzzPackager) PackageArtifacts(ctx android.SingletonContext, module android.Module, fuzzModule FuzzPackagedModule, archDir android.OutputPath, builder *android.RuleBuilder) []FileToZip {
129 // Package the corpora into a zipfile.
130 var files []FileToZip
131 if fuzzModule.Corpus != nil {
132 corpusZip := archDir.Join(ctx, module.Name()+"_seed_corpus.zip")
133 command := builder.Command().BuiltTool("soong_zip").
134 Flag("-j").
135 FlagWithOutput("-o ", corpusZip)
136 rspFile := corpusZip.ReplaceExtension(ctx, "rsp")
137 command.FlagWithRspFileInputList("-r ", rspFile, fuzzModule.Corpus)
138 files = append(files, FileToZip{corpusZip, ""})
139 }
140
141 // Package the data into a zipfile.
142 if fuzzModule.Data != nil {
143 dataZip := archDir.Join(ctx, module.Name()+"_data.zip")
144 command := builder.Command().BuiltTool("soong_zip").
145 FlagWithOutput("-o ", dataZip)
146 for _, f := range fuzzModule.Data {
147 intermediateDir := strings.TrimSuffix(f.String(), f.Rel())
148 command.FlagWithArg("-C ", intermediateDir)
149 command.FlagWithInput("-f ", f)
150 }
151 files = append(files, FileToZip{dataZip, ""})
152 }
153
154 // The dictionary.
155 if fuzzModule.Dictionary != nil {
156 files = append(files, FileToZip{fuzzModule.Dictionary, ""})
157 }
158
159 // Additional fuzz config.
160 if fuzzModule.Config != nil {
161 files = append(files, FileToZip{fuzzModule.Config, ""})
162 }
163
164 return files
165}
166
167func (s *FuzzPackager) BuildZipFile(ctx android.SingletonContext, module android.Module, fuzzModule FuzzPackagedModule, files []FileToZip, builder *android.RuleBuilder, archDir android.OutputPath, archString string, hostOrTargetString string, archOs ArchOs, archDirs map[ArchOs][]FileToZip) ([]FileToZip, bool) {
168 fuzzZip := archDir.Join(ctx, module.Name()+".zip")
169
170 command := builder.Command().BuiltTool("soong_zip").
171 Flag("-j").
172 FlagWithOutput("-o ", fuzzZip)
173
174 for _, file := range files {
175 if file.DestinationPathPrefix != "" {
176 command.FlagWithArg("-P ", file.DestinationPathPrefix)
177 } else {
178 command.Flag("-P ''")
179 }
180 command.FlagWithInput("-f ", file.SourceFilePath)
181 }
182
183 builder.Build("create-"+fuzzZip.String(),
184 "Package "+module.Name()+" for "+archString+"-"+hostOrTargetString)
185
186 // Don't add modules to 'make haiku-rust' that are set to not be
187 // exported to the fuzzing infrastructure.
188 if config := fuzzModule.FuzzProperties.Fuzz_config; config != nil {
189 if strings.Contains(hostOrTargetString, "host") && !BoolDefault(config.Fuzz_on_haiku_host, true) {
190 return archDirs[archOs], false
191 } else if !BoolDefault(config.Fuzz_on_haiku_device, true) {
192 return archDirs[archOs], false
193 }
194 }
195
196 s.FuzzTargets[module.Name()] = true
197 archDirs[archOs] = append(archDirs[archOs], FileToZip{fuzzZip, ""})
198
199 return archDirs[archOs], true
200}
201
hamzehc0a671f2021-07-22 12:05:08 -0700202func (f *FuzzConfig) String() string {
203 b, err := json.Marshal(f)
204 if err != nil {
205 panic(err)
206 }
207
208 return string(b)
209}
210
211func (s *FuzzPackager) CreateFuzzPackage(ctx android.SingletonContext, archDirs map[ArchOs][]FileToZip, lang Lang, pctx android.PackageContext) {
hamzeh41ad8812021-07-07 14:00:07 -0700212 var archOsList []ArchOs
213 for archOs := range archDirs {
214 archOsList = append(archOsList, archOs)
215 }
216 sort.Slice(archOsList, func(i, j int) bool { return archOsList[i].Dir < archOsList[j].Dir })
217
218 for _, archOs := range archOsList {
219 filesToZip := archDirs[archOs]
220 arch := archOs.Arch
221 hostOrTarget := archOs.HostOrTarget
222 builder := android.NewRuleBuilder(pctx, ctx)
223 zipFileName := "fuzz-" + hostOrTarget + "-" + arch + ".zip"
224 if lang == Rust {
225 zipFileName = "fuzz-rust-" + hostOrTarget + "-" + arch + ".zip"
226 }
Muhammad Haseeb Ahmade3803102022-01-10 21:37:07 +0000227 if lang == Java {
228 zipFileName = "fuzz-java-" + hostOrTarget + "-" + arch + ".zip"
229 }
hamzeh41ad8812021-07-07 14:00:07 -0700230 outputFile := android.PathForOutput(ctx, zipFileName)
231
232 s.Packages = append(s.Packages, outputFile)
233
234 command := builder.Command().BuiltTool("soong_zip").
235 Flag("-j").
236 FlagWithOutput("-o ", outputFile).
237 Flag("-L 0") // No need to try and re-compress the zipfiles.
238
239 for _, fileToZip := range filesToZip {
240
241 if fileToZip.DestinationPathPrefix != "" {
242 command.FlagWithArg("-P ", fileToZip.DestinationPathPrefix)
243 } else {
244 command.Flag("-P ''")
245 }
246 command.FlagWithInput("-f ", fileToZip.SourceFilePath)
247
248 }
249 builder.Build("create-fuzz-package-"+arch+"-"+hostOrTarget,
250 "Create fuzz target packages for "+arch+"-"+hostOrTarget)
251 }
252}
253
254func (s *FuzzPackager) PreallocateSlice(ctx android.MakeVarsContext, targets string) {
255 fuzzTargets := make([]string, 0, len(s.FuzzTargets))
256 for target, _ := range s.FuzzTargets {
257 fuzzTargets = append(fuzzTargets, target)
258 }
259 sort.Strings(fuzzTargets)
260 ctx.Strict(targets, strings.Join(fuzzTargets, " "))
261}
Ivan Lozano39b0bf02021-10-14 12:22:09 -0400262
263// CollectAllSharedDependencies performs a breadth-first search over the provided module's
264// dependencies using `visitDirectDeps` to enumerate all shared library
265// dependencies. We require breadth-first expansion, as otherwise we may
266// incorrectly use the core libraries (sanitizer runtimes, libc, libdl, etc.)
267// from a dependency. This may cause issues when dependencies have explicit
268// sanitizer tags, as we may get a dependency on an unsanitized libc, etc.
269func CollectAllSharedDependencies(ctx android.SingletonContext, module android.Module, unstrippedOutputFile func(module android.Module) android.Path, isValidSharedDependency func(dependency android.Module) bool) android.Paths {
270 var fringe []android.Module
271
272 seen := make(map[string]bool)
273
274 // Enumerate the first level of dependencies, as we discard all non-library
275 // modules in the BFS loop below.
276 ctx.VisitDirectDeps(module, func(dep android.Module) {
277 if isValidSharedDependency(dep) {
278 fringe = append(fringe, dep)
279 }
280 })
281
282 var sharedLibraries android.Paths
283
284 for i := 0; i < len(fringe); i++ {
285 module := fringe[i]
286 if seen[module.Name()] {
287 continue
288 }
289 seen[module.Name()] = true
290
291 sharedLibraries = append(sharedLibraries, unstrippedOutputFile(module))
292 ctx.VisitDirectDeps(module, func(dep android.Module) {
293 if isValidSharedDependency(dep) && !seen[dep.Name()] {
294 fringe = append(fringe, dep)
295 }
296 })
297 }
298
299 return sharedLibraries
300}