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