blob: d44573239e538ca612f27f637410794be57ec90f [file] [log] [blame]
Colin Cross16b23492016-01-06 14:41:07 -08001// 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 (
18 "fmt"
Jeff Gaston72765392017-11-28 16:37:53 -080019 "sort"
Colin Cross16b23492016-01-06 14:41:07 -080020 "strings"
Vishwath Mohane7128792017-11-17 11:08:10 -080021 "sync"
Colin Cross16b23492016-01-06 14:41:07 -080022
Colin Cross6b753602018-06-21 13:03:07 -070023 "github.com/google/blueprint"
Liz Kammerb2fc4702021-06-25 14:53:40 -040024 "github.com/google/blueprint/proptools"
Colin Cross6b753602018-06-21 13:03:07 -070025
Colin Cross635c3b02016-05-18 15:37:25 -070026 "android/soong/android"
Evgenii Stepanovaf36db12016-08-15 14:18:24 -070027 "android/soong/cc/config"
Kiyoung Kim48f37782021-07-07 12:42:39 +090028 "android/soong/snapshot"
Colin Cross16b23492016-01-06 14:41:07 -080029)
30
Jayant Chowdhary9677e8c2017-06-15 14:45:18 -070031var (
32 // Any C flags added by sanitizer which libTooling tools may not
33 // understand also need to be added to ClangLibToolingUnknownCflags in
34 // cc/config/clang.go
Vishwath Mohanf3918d32017-02-14 07:59:33 -080035
Yi Kong20233a42019-08-21 01:38:40 -070036 asanCflags = []string{
37 "-fno-omit-frame-pointer",
Yi Kong20233a42019-08-21 01:38:40 -070038 }
Jayant Chowdhary9677e8c2017-06-15 14:45:18 -070039 asanLdflags = []string{"-Wl,-u,__asan_preinit"}
Jayant Chowdhary9677e8c2017-06-15 14:45:18 -070040
Yi Kong286abc62021-11-04 16:14:14 +080041 hwasanCflags = []string{
42 "-fno-omit-frame-pointer",
43 "-Wno-frame-larger-than=",
Evgenii Stepanov96fa3dd2020-03-27 19:38:42 +000044 "-fsanitize-hwaddress-abi=platform",
Florian Mayer0b981f52022-02-16 23:46:53 +000045 "-mllvm", "-hwasan-use-after-scope=1",
Yi Kong286abc62021-11-04 16:14:14 +080046 }
47
48 // ThinLTO performs codegen during link time, thus these flags need to
49 // passed to both CFLAGS and LDFLAGS.
50 hwasanCommonflags = []string{
Evgenii Stepanov64bee4d2019-11-22 18:37:10 -080051 // The following improves debug location information
52 // availability at the cost of its accuracy. It increases
53 // the likelihood of a stack variable's frame offset
54 // to be recorded in the debug info, which is important
55 // for the quality of hwasan reports. The downside is a
56 // higher number of "optimized out" stack variables.
57 // b/112437883.
Yi Kong286abc62021-11-04 16:14:14 +080058 "-instcombine-lower-dbg-declare=0",
Mitch Phillipsb1c574f2020-06-22 13:28:23 -070059 // TODO(b/159343917): HWASan and GlobalISel don't play nicely, and
60 // GlobalISel is the default at -O0 on aarch64.
Yi Kong286abc62021-11-04 16:14:14 +080061 "--aarch64-enable-global-isel-at-O=-1",
62 "-fast-isel=false",
Evgenii Stepanov64bee4d2019-11-22 18:37:10 -080063 }
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -070064
Vishwath Mohanb743e9c2017-11-01 09:20:21 +000065 cfiCflags = []string{"-flto", "-fsanitize-cfi-cross-dso",
Pirama Arumuga Nainar582fc2d2021-08-27 15:12:56 -070066 "-fsanitize-ignorelist=external/compiler-rt/lib/cfi/cfi_blocklist.txt"}
Evgenii Stepanovdbf1d4f2018-08-31 12:54:33 -070067 // -flto and -fvisibility are required by clang when -fsanitize=cfi is
68 // used, but have no effect on assembly files
69 cfiAsflags = []string{"-flto", "-fvisibility=default"}
Jayant Chowdhary9677e8c2017-06-15 14:45:18 -070070 cfiLdflags = []string{"-flto", "-fsanitize-cfi-cross-dso", "-fsanitize=cfi",
Pirama Arumuga Nainarbdb17f02017-08-28 21:50:17 -070071 "-Wl,-plugin-opt,O1"}
Inseob Kim74d25562020-08-04 00:41:38 +090072 cfiExportsMapPath = "build/soong/cc/config/cfi_exports.map"
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -070073
Pirama Arumuga Nainar582fc2d2021-08-27 15:12:56 -070074 intOverflowCflags = []string{"-fsanitize-ignorelist=build/soong/cc/config/integer_overflow_blocklist.txt"}
Peter Collingbourne8c7e6e22018-11-19 16:03:58 -080075
Peter Collingbournebd19db02019-03-06 10:38:48 -080076 minimalRuntimeFlags = []string{"-fsanitize-minimal-runtime", "-fno-sanitize-trap=integer,undefined",
Ivan Lozanoae6ae1d2018-10-08 09:29:39 -070077 "-fno-sanitize-recover=integer,undefined"}
Evgenii Stepanov2c6484e2019-05-15 12:49:54 -070078 hwasanGlobalOptions = []string{"heap_history_size=1023", "stack_history_size=512",
Christopher Ferris2fc8e032023-01-26 14:19:27 -080079 "export_memory_stats=0", "max_malloc_fill_size=131072", "malloc_fill_byte=0"}
Florian Mayer1866bbe2023-03-11 01:07:40 +000080 memtagStackCommonFlags = []string{"-march=armv8-a+memtag", "-mllvm", "-dom-tree-reachability-max-bbs-to-explore=128"}
Trevor Radcliffe4f95ee92023-01-19 16:02:47 +000081
82 hostOnlySanitizeFlags = []string{"-fno-sanitize-recover=all"}
83 deviceOnlySanitizeFlags = []string{"-fsanitize-trap=all", "-ftrap-function=abort"}
Dan Willemsencbceaab2016-10-13 16:44:07 -070084)
85
Ivan Lozano3968d8f2020-12-14 11:27:52 -050086type SanitizerType int
Colin Cross16b23492016-01-06 14:41:07 -080087
Colin Cross16b23492016-01-06 14:41:07 -080088const (
Ivan Lozano3968d8f2020-12-14 11:27:52 -050089 Asan SanitizerType = iota + 1
Tri Vo6eafc362021-04-01 11:29:09 -070090 Hwasan
Colin Cross16b23492016-01-06 14:41:07 -080091 tsan
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -070092 intOverflow
Peter Collingbourne8c7e6e22018-11-19 16:03:58 -080093 scs
Ivan Lozano3968d8f2020-12-14 11:27:52 -050094 Fuzzer
Ivan Lozano62cd0382021-11-01 10:27:54 -040095 Memtag_heap
Florian Mayerd8434a42022-08-31 20:57:03 +000096 Memtag_stack
Liz Kammer75db9312021-07-07 16:41:50 -040097 cfi // cfi is last to prevent it running before incompatible mutators
Colin Cross16b23492016-01-06 14:41:07 -080098)
99
Liz Kammer75db9312021-07-07 16:41:50 -0400100var Sanitizers = []SanitizerType{
101 Asan,
102 Hwasan,
103 tsan,
104 intOverflow,
105 scs,
106 Fuzzer,
Ivan Lozano62cd0382021-11-01 10:27:54 -0400107 Memtag_heap,
Florian Mayerd8434a42022-08-31 20:57:03 +0000108 Memtag_stack,
Liz Kammer75db9312021-07-07 16:41:50 -0400109 cfi, // cfi is last to prevent it running before incompatible mutators
110}
111
Jiyong Park82226632019-02-01 10:50:50 +0900112// Name of the sanitizer variation for this sanitizer type
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500113func (t SanitizerType) variationName() string {
Colin Cross16b23492016-01-06 14:41:07 -0800114 switch t {
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500115 case Asan:
Colin Cross16b23492016-01-06 14:41:07 -0800116 return "asan"
Tri Vo6eafc362021-04-01 11:29:09 -0700117 case Hwasan:
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700118 return "hwasan"
Colin Cross16b23492016-01-06 14:41:07 -0800119 case tsan:
120 return "tsan"
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700121 case intOverflow:
122 return "intOverflow"
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000123 case cfi:
124 return "cfi"
Peter Collingbourne8c7e6e22018-11-19 16:03:58 -0800125 case scs:
126 return "scs"
Ivan Lozano62cd0382021-11-01 10:27:54 -0400127 case Memtag_heap:
Evgenii Stepanov193ac2e2020-04-28 15:09:12 -0700128 return "memtag_heap"
Florian Mayerd8434a42022-08-31 20:57:03 +0000129 case Memtag_stack:
130 return "memtag_stack"
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500131 case Fuzzer:
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700132 return "fuzzer"
Colin Cross16b23492016-01-06 14:41:07 -0800133 default:
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500134 panic(fmt.Errorf("unknown SanitizerType %d", t))
Colin Cross16b23492016-01-06 14:41:07 -0800135 }
136}
137
Jiyong Park82226632019-02-01 10:50:50 +0900138// This is the sanitizer names in SANITIZE_[TARGET|HOST]
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500139func (t SanitizerType) name() string {
Jiyong Park82226632019-02-01 10:50:50 +0900140 switch t {
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500141 case Asan:
Jiyong Park82226632019-02-01 10:50:50 +0900142 return "address"
Tri Vo6eafc362021-04-01 11:29:09 -0700143 case Hwasan:
Jiyong Park82226632019-02-01 10:50:50 +0900144 return "hwaddress"
Ivan Lozano62cd0382021-11-01 10:27:54 -0400145 case Memtag_heap:
Evgenii Stepanov193ac2e2020-04-28 15:09:12 -0700146 return "memtag_heap"
Florian Mayerd8434a42022-08-31 20:57:03 +0000147 case Memtag_stack:
148 return "memtag_stack"
Jiyong Park82226632019-02-01 10:50:50 +0900149 case tsan:
150 return "thread"
151 case intOverflow:
152 return "integer_overflow"
153 case cfi:
154 return "cfi"
155 case scs:
156 return "shadow-call-stack"
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500157 case Fuzzer:
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700158 return "fuzzer"
Jiyong Park82226632019-02-01 10:50:50 +0900159 default:
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500160 panic(fmt.Errorf("unknown SanitizerType %d", t))
Jiyong Park82226632019-02-01 10:50:50 +0900161 }
162}
163
Liz Kammer75db9312021-07-07 16:41:50 -0400164func (t SanitizerType) registerMutators(ctx android.RegisterMutatorsContext) {
165 switch t {
Lukacs T. Berki6c716762022-06-13 20:50:39 +0200166 case cfi, Hwasan, Asan, tsan, Fuzzer, scs:
167 sanitizer := &sanitizerSplitMutator{t}
168 ctx.TopDown(t.variationName()+"_markapexes", sanitizer.markSanitizableApexesMutator)
169 ctx.Transition(t.variationName(), sanitizer)
Florian Mayerd8434a42022-08-31 20:57:03 +0000170 case Memtag_heap, Memtag_stack, intOverflow:
Liz Kammer75db9312021-07-07 16:41:50 -0400171 // do nothing
172 default:
173 panic(fmt.Errorf("unknown SanitizerType %d", t))
174 }
175}
176
Liz Kammerfd8a49f2022-10-31 10:31:11 -0400177// shouldPropagateToSharedLibraryDeps returns whether a sanitizer type should propagate to share
178// dependencies. In most cases, sanitizers only propagate to static dependencies; however, some
179// sanitizers also must be enabled for shared libraries for linking.
180func (t SanitizerType) shouldPropagateToSharedLibraryDeps() bool {
181 switch t {
182 case Fuzzer:
183 // Typically, shared libs are not split. However, for fuzzer, we split even for shared libs
184 // because a library sanitized for fuzzer can't be linked from a library that isn't sanitized
185 // for fuzzer.
186 return true
187 default:
188 return false
189 }
190}
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500191func (*Module) SanitizerSupported(t SanitizerType) bool {
192 switch t {
193 case Asan:
194 return true
Tri Vo6eafc362021-04-01 11:29:09 -0700195 case Hwasan:
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500196 return true
197 case tsan:
198 return true
199 case intOverflow:
200 return true
201 case cfi:
202 return true
203 case scs:
204 return true
205 case Fuzzer:
206 return true
Ivan Lozano62cd0382021-11-01 10:27:54 -0400207 case Memtag_heap:
208 return true
Florian Mayerd8434a42022-08-31 20:57:03 +0000209 case Memtag_stack:
210 return true
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500211 default:
212 return false
213 }
214}
215
216// incompatibleWithCfi returns true if a sanitizer is incompatible with CFI.
217func (t SanitizerType) incompatibleWithCfi() bool {
Tri Vo6eafc362021-04-01 11:29:09 -0700218 return t == Asan || t == Fuzzer || t == Hwasan
Jiyong Park1d1119f2019-07-29 21:27:18 +0900219}
220
Martin Stjernholmb0249572020-09-15 02:32:35 +0100221type SanitizeUserProps struct {
Liz Kammer75b9b402021-06-25 15:19:27 -0400222 // Prevent use of any sanitizers on this module
Martin Stjernholmb0249572020-09-15 02:32:35 +0100223 Never *bool `android:"arch_variant"`
Colin Cross16b23492016-01-06 14:41:07 -0800224
Liz Kammer75b9b402021-06-25 15:19:27 -0400225 // ASan (Address sanitizer), incompatible with static binaries.
226 // Always runs in a diagnostic mode.
227 // Use of address sanitizer disables cfi sanitizer.
228 // Hwaddress sanitizer takes precedence over this sanitizer.
229 Address *bool `android:"arch_variant"`
230 // TSan (Thread sanitizer), incompatible with static binaries and 32 bit architectures.
231 // Always runs in a diagnostic mode.
232 // Use of thread sanitizer disables cfi and scudo sanitizers.
233 // Hwaddress sanitizer takes precedence over this sanitizer.
234 Thread *bool `android:"arch_variant"`
235 // HWASan (Hardware Address sanitizer).
236 // Use of hwasan sanitizer disables cfi, address, thread, and scudo sanitizers.
Martin Stjernholmb0249572020-09-15 02:32:35 +0100237 Hwaddress *bool `android:"arch_variant"`
Colin Cross16b23492016-01-06 14:41:07 -0800238
Liz Kammer75b9b402021-06-25 15:19:27 -0400239 // Undefined behavior sanitizer
240 All_undefined *bool `android:"arch_variant"`
241 // Subset of undefined behavior sanitizer
242 Undefined *bool `android:"arch_variant"`
243 // List of specific undefined behavior sanitizers to enable
244 Misc_undefined []string `android:"arch_variant"`
245 // Fuzzer, incompatible with static binaries.
246 Fuzzer *bool `android:"arch_variant"`
247 // safe-stack sanitizer, incompatible with 32-bit architectures.
248 Safestack *bool `android:"arch_variant"`
249 // cfi sanitizer, incompatible with asan, hwasan, fuzzer, or Darwin
250 Cfi *bool `android:"arch_variant"`
251 // signed/unsigned integer overflow sanitizer, incompatible with Darwin.
252 Integer_overflow *bool `android:"arch_variant"`
253 // scudo sanitizer, incompatible with asan, hwasan, tsan
254 // This should not be used in Android 11+ : https://source.android.com/devices/tech/debug/scudo
255 // deprecated
256 Scudo *bool `android:"arch_variant"`
257 // shadow-call-stack sanitizer, only available on arm64
258 Scs *bool `android:"arch_variant"`
259 // Memory-tagging, only available on arm64
260 // if diag.memtag unset or false, enables async memory tagging
Florian Mayer00ab5cf2022-08-31 18:30:18 +0000261 Memtag_heap *bool `android:"arch_variant"`
Florian Mayerd8434a42022-08-31 20:57:03 +0000262 // Memory-tagging stack instrumentation, only available on arm64
263 // Adds instrumentation to detect stack buffer overflows and use-after-scope using MTE.
264 Memtag_stack *bool `android:"arch_variant"`
Martin Stjernholmb0249572020-09-15 02:32:35 +0100265
266 // A modifier for ASAN and HWASAN for write only instrumentation
267 Writeonly *bool `android:"arch_variant"`
268
269 // Sanitizers to run in the diagnostic mode (as opposed to the release mode).
270 // Replaces abort() on error with a human-readable error message.
271 // Address and Thread sanitizers always run in diagnostic mode.
272 Diag struct {
Liz Kammer75b9b402021-06-25 15:19:27 -0400273 // Undefined behavior sanitizer, diagnostic mode
274 Undefined *bool `android:"arch_variant"`
275 // cfi sanitizer, diagnostic mode, incompatible with asan, hwasan, fuzzer, or Darwin
276 Cfi *bool `android:"arch_variant"`
277 // signed/unsigned integer overflow sanitizer, diagnostic mode, incompatible with Darwin.
278 Integer_overflow *bool `android:"arch_variant"`
279 // Memory-tagging, only available on arm64
280 // requires sanitizer.memtag: true
281 // if set, enables sync memory tagging
282 Memtag_heap *bool `android:"arch_variant"`
283 // List of specific undefined behavior sanitizers to enable in diagnostic mode
284 Misc_undefined []string `android:"arch_variant"`
285 // List of sanitizers to pass to -fno-sanitize-recover
286 // results in only the first detected error for these sanitizers being reported and program then
287 // exits with a non-zero exit code.
288 No_recover []string `android:"arch_variant"`
Cindy Zhoud3fe4922020-12-01 11:14:30 -0800289 } `android:"arch_variant"`
Colin Cross16b23492016-01-06 14:41:07 -0800290
Cindy Zhou8cd45de2020-11-16 08:41:00 -0800291 // Sanitizers to run with flag configuration specified
292 Config struct {
293 // Enables CFI support flags for assembly-heavy libraries
294 Cfi_assembly_support *bool `android:"arch_variant"`
Cindy Zhoud3fe4922020-12-01 11:14:30 -0800295 } `android:"arch_variant"`
Cindy Zhou8cd45de2020-11-16 08:41:00 -0800296
Liz Kammer75b9b402021-06-25 15:19:27 -0400297 // List of sanitizers to pass to -fsanitize-recover
298 // allows execution to continue for these sanitizers to detect multiple errors rather than only
299 // the first one
Martin Stjernholmb0249572020-09-15 02:32:35 +0100300 Recover []string
Jasraj Bedibb4511d2020-07-23 22:58:17 +0000301
Pirama Arumuga Nainar582fc2d2021-08-27 15:12:56 -0700302 // value to pass to -fsanitize-ignorelist
Martin Stjernholmb0249572020-09-15 02:32:35 +0100303 Blocklist *string
304}
Evgenii Stepanov1e405e12016-08-16 15:39:54 -0700305
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400306type sanitizeMutatedProperties struct {
307 // Whether sanitizers can be enabled on this module
308 Never *bool `blueprint:"mutated"`
309
310 // Whether ASan (Address sanitizer) is enabled for this module.
311 // Hwaddress sanitizer takes precedence over this sanitizer.
312 Address *bool `blueprint:"mutated"`
313 // Whether TSan (Thread sanitizer) is enabled for this module
314 Thread *bool `blueprint:"mutated"`
315 // Whether HWASan (Hardware Address sanitizer) is enabled for this module
316 Hwaddress *bool `blueprint:"mutated"`
317
318 // Whether Undefined behavior sanitizer is enabled for this module
319 All_undefined *bool `blueprint:"mutated"`
320 // Whether undefined behavior sanitizer subset is enabled for this module
321 Undefined *bool `blueprint:"mutated"`
322 // List of specific undefined behavior sanitizers enabled for this module
323 Misc_undefined []string `blueprint:"mutated"`
324 // Whether Fuzzeris enabled for this module
325 Fuzzer *bool `blueprint:"mutated"`
326 // whether safe-stack sanitizer is enabled for this module
327 Safestack *bool `blueprint:"mutated"`
328 // Whether cfi sanitizer is enabled for this module
329 Cfi *bool `blueprint:"mutated"`
330 // Whether signed/unsigned integer overflow sanitizer is enabled for this module
331 Integer_overflow *bool `blueprint:"mutated"`
332 // Whether scudo sanitizer is enabled for this module
333 Scudo *bool `blueprint:"mutated"`
334 // Whether shadow-call-stack sanitizer is enabled for this module.
335 Scs *bool `blueprint:"mutated"`
336 // Whether Memory-tagging is enabled for this module
337 Memtag_heap *bool `blueprint:"mutated"`
338 // Whether Memory-tagging stack instrumentation is enabled for this module
339 Memtag_stack *bool `blueprint:"mutated"`
340
341 // Whether a modifier for ASAN and HWASAN for write only instrumentation is enabled for this
342 // module
343 Writeonly *bool `blueprint:"mutated"`
344
345 // Sanitizers to run in the diagnostic mode (as opposed to the release mode).
346 Diag struct {
347 // Whether Undefined behavior sanitizer, diagnostic mode is enabled for this module
348 Undefined *bool `blueprint:"mutated"`
349 // Whether cfi sanitizer, diagnostic mode is enabled for this module
350 Cfi *bool `blueprint:"mutated"`
351 // Whether signed/unsigned integer overflow sanitizer, diagnostic mode is enabled for this
352 // module
353 Integer_overflow *bool `blueprint:"mutated"`
354 // Whether Memory-tagging, diagnostic mode is enabled for this module
355 Memtag_heap *bool `blueprint:"mutated"`
356 // List of specific undefined behavior sanitizers enabled in diagnostic mode
357 Misc_undefined []string `blueprint:"mutated"`
358 } `blueprint:"mutated"`
359}
360
Martin Stjernholmb0249572020-09-15 02:32:35 +0100361type SanitizeProperties struct {
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400362 Sanitize SanitizeUserProps `android:"arch_variant"`
363 SanitizeMutated sanitizeMutatedProperties `blueprint:"mutated"`
364
365 SanitizerEnabled bool `blueprint:"mutated"`
366 MinimalRuntimeDep bool `blueprint:"mutated"`
367 BuiltinsDep bool `blueprint:"mutated"`
368 UbsanRuntimeDep bool `blueprint:"mutated"`
369 InSanitizerDir bool `blueprint:"mutated"`
370 Sanitizers []string `blueprint:"mutated"`
371 DiagSanitizers []string `blueprint:"mutated"`
Colin Cross16b23492016-01-06 14:41:07 -0800372}
373
374type sanitize struct {
375 Properties SanitizeProperties
376}
377
Cindy Zhou18417cb2020-12-10 07:12:38 -0800378// Mark this tag with a check to see if apex dependency check should be skipped
379func (t libraryDependencyTag) SkipApexAllowedDependenciesCheck() bool {
380 return t.skipApexAllowedDependenciesCheck
381}
382
383var _ android.SkipApexAllowedDependenciesCheck = (*libraryDependencyTag)(nil)
384
Trevor Radcliffe4f95ee92023-01-19 16:02:47 +0000385var exportedVars = android.NewExportedVariables(pctx)
386
Vishwath Mohane7128792017-11-17 11:08:10 -0800387func init() {
Trevor Radcliffe4f95ee92023-01-19 16:02:47 +0000388 exportedVars.ExportStringListStaticVariable("HostOnlySanitizeFlags", hostOnlySanitizeFlags)
389 exportedVars.ExportStringList("DeviceOnlySanitizeFlags", deviceOnlySanitizeFlags)
390
Vishwath Mohane7128792017-11-17 11:08:10 -0800391 android.RegisterMakeVarsProvider(pctx, cfiMakeVarsProvider)
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700392 android.RegisterMakeVarsProvider(pctx, hwasanMakeVarsProvider)
Vishwath Mohane7128792017-11-17 11:08:10 -0800393}
394
Colin Cross16b23492016-01-06 14:41:07 -0800395func (sanitize *sanitize) props() []interface{} {
396 return []interface{}{&sanitize.Properties}
397}
398
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400399func (p *sanitizeMutatedProperties) copyUserPropertiesToMutated(userProps *SanitizeUserProps) {
400 p.Never = userProps.Never
401 p.Address = userProps.Address
402 p.All_undefined = userProps.All_undefined
403 p.Cfi = userProps.Cfi
404 p.Fuzzer = userProps.Fuzzer
405 p.Hwaddress = userProps.Hwaddress
406 p.Integer_overflow = userProps.Integer_overflow
407 p.Memtag_heap = userProps.Memtag_heap
408 p.Memtag_stack = userProps.Memtag_stack
409 p.Safestack = userProps.Safestack
410 p.Scs = userProps.Scs
411 p.Scudo = userProps.Scudo
412 p.Thread = userProps.Thread
413 p.Undefined = userProps.Undefined
414 p.Writeonly = userProps.Writeonly
415
416 p.Misc_undefined = make([]string, 0, len(userProps.Misc_undefined))
417 for _, v := range userProps.Misc_undefined {
418 p.Misc_undefined = append(p.Misc_undefined, v)
419 }
420
421 p.Diag.Cfi = userProps.Diag.Cfi
422 p.Diag.Integer_overflow = userProps.Diag.Integer_overflow
423 p.Diag.Memtag_heap = userProps.Diag.Memtag_heap
424 p.Diag.Undefined = userProps.Diag.Undefined
425
426 p.Diag.Misc_undefined = make([]string, 0, len(userProps.Diag.Misc_undefined))
427 for _, v := range userProps.Diag.Misc_undefined {
428 p.Diag.Misc_undefined = append(p.Diag.Misc_undefined, v)
429 }
430}
431
Colin Cross16b23492016-01-06 14:41:07 -0800432func (sanitize *sanitize) begin(ctx BaseModuleContext) {
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400433 s := &sanitize.Properties.SanitizeMutated
434 s.copyUserPropertiesToMutated(&sanitize.Properties.Sanitize)
Evgenii Stepanovfcfe56d2016-07-07 10:54:07 -0700435
Colin Cross16b23492016-01-06 14:41:07 -0800436 // Don't apply sanitizers to NDK code.
Jeff Gastonaf3cc2d2017-09-27 17:01:44 -0700437 if ctx.useSdk() {
Nan Zhang0007d812017-11-07 10:57:05 -0800438 s.Never = BoolPtr(true)
Colin Cross16b23492016-01-06 14:41:07 -0800439 }
440
441 // Never always wins.
Nan Zhang0007d812017-11-07 10:57:05 -0800442 if Bool(s.Never) {
Colin Cross16b23492016-01-06 14:41:07 -0800443 return
444 }
445
Florian Mayerd8434a42022-08-31 20:57:03 +0000446 // cc_test targets default to SYNC MemTag unless explicitly set to ASYNC (via diag: {memtag_heap: false}).
Liz Kammer7b920b42021-06-22 16:57:27 -0400447 if ctx.testBinary() {
448 if s.Memtag_heap == nil {
449 s.Memtag_heap = proptools.BoolPtr(true)
450 }
451 if s.Diag.Memtag_heap == nil {
452 s.Diag.Memtag_heap = proptools.BoolPtr(true)
453 }
Evgenii Stepanov04896ca2021-01-12 18:28:33 -0800454 }
455
Colin Cross16b23492016-01-06 14:41:07 -0800456 var globalSanitizers []string
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700457 var globalSanitizersDiag []string
458
Dan Willemsen8536d6b2018-10-07 20:54:34 -0700459 if ctx.Host() {
460 if !ctx.Windows() {
461 globalSanitizers = ctx.Config().SanitizeHost()
462 }
463 } else {
464 arches := ctx.Config().SanitizeDeviceArch()
465 if len(arches) == 0 || inList(ctx.Arch().ArchType.Name, arches) {
466 globalSanitizers = ctx.Config().SanitizeDevice()
467 globalSanitizersDiag = ctx.Config().SanitizeDeviceDiag()
Colin Cross16b23492016-01-06 14:41:07 -0800468 }
469 }
470
Colin Cross16b23492016-01-06 14:41:07 -0800471 if len(globalSanitizers) > 0 {
Evgenii Stepanov05bafd32016-07-07 17:38:41 +0000472 var found bool
Evgenii Stepanovfcfe56d2016-07-07 10:54:07 -0700473 if found, globalSanitizers = removeFromList("undefined", globalSanitizers); found && s.All_undefined == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400474 s.All_undefined = proptools.BoolPtr(true)
Evgenii Stepanov05bafd32016-07-07 17:38:41 +0000475 }
Colin Cross16b23492016-01-06 14:41:07 -0800476
Evgenii Stepanovfcfe56d2016-07-07 10:54:07 -0700477 if found, globalSanitizers = removeFromList("default-ub", globalSanitizers); found && s.Undefined == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400478 s.Undefined = proptools.BoolPtr(true)
Evgenii Stepanov05bafd32016-07-07 17:38:41 +0000479 }
480
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700481 if found, globalSanitizers = removeFromList("address", globalSanitizers); found && s.Address == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400482 s.Address = proptools.BoolPtr(true)
Evgenii Stepanov05bafd32016-07-07 17:38:41 +0000483 }
484
Evgenii Stepanovfcfe56d2016-07-07 10:54:07 -0700485 if found, globalSanitizers = removeFromList("thread", globalSanitizers); found && s.Thread == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400486 s.Thread = proptools.BoolPtr(true)
Evgenii Stepanov05bafd32016-07-07 17:38:41 +0000487 }
488
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700489 if found, globalSanitizers = removeFromList("fuzzer", globalSanitizers); found && s.Fuzzer == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400490 s.Fuzzer = proptools.BoolPtr(true)
Evgenii Stepanovfcfe56d2016-07-07 10:54:07 -0700491 }
492
493 if found, globalSanitizers = removeFromList("safe-stack", globalSanitizers); found && s.Safestack == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400494 s.Safestack = proptools.BoolPtr(true)
Evgenii Stepanov05bafd32016-07-07 17:38:41 +0000495 }
496
Evgenii Stepanov1e405e12016-08-16 15:39:54 -0700497 if found, globalSanitizers = removeFromList("cfi", globalSanitizers); found && s.Cfi == nil {
Colin Cross6510f912017-11-29 00:27:14 -0800498 if !ctx.Config().CFIDisabledForPath(ctx.ModuleDir()) {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400499 s.Cfi = proptools.BoolPtr(true)
Vishwath Mohan1fa3ac52017-10-31 02:26:14 -0700500 }
Evgenii Stepanov1e405e12016-08-16 15:39:54 -0700501 }
502
Ivan Lozanoa9255a82018-03-13 10:41:07 -0700503 // Global integer_overflow builds do not support static libraries.
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700504 if found, globalSanitizers = removeFromList("integer_overflow", globalSanitizers); found && s.Integer_overflow == nil {
Ivan Lozanoa9255a82018-03-13 10:41:07 -0700505 if !ctx.Config().IntegerOverflowDisabledForPath(ctx.ModuleDir()) && !ctx.static() {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400506 s.Integer_overflow = proptools.BoolPtr(true)
Ivan Lozano5f595532017-07-13 14:46:05 -0700507 }
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700508 }
509
Kostya Kortchinskyd18ae5c2018-06-12 14:46:54 -0700510 if found, globalSanitizers = removeFromList("scudo", globalSanitizers); found && s.Scudo == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400511 s.Scudo = proptools.BoolPtr(true)
Kostya Kortchinskyd18ae5c2018-06-12 14:46:54 -0700512 }
513
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700514 if found, globalSanitizers = removeFromList("hwaddress", globalSanitizers); found && s.Hwaddress == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400515 s.Hwaddress = proptools.BoolPtr(true)
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700516 }
517
Jasraj Bedibb4511d2020-07-23 22:58:17 +0000518 if found, globalSanitizers = removeFromList("writeonly", globalSanitizers); found && s.Writeonly == nil {
519 // Hwaddress and Address are set before, so we can check them here
520 // If they aren't explicitly set in the blueprint/SANITIZE_(HOST|TARGET), they would be nil instead of false
521 if s.Address == nil && s.Hwaddress == nil {
522 ctx.ModuleErrorf("writeonly modifier cannot be used without 'address' or 'hwaddress'")
523 }
Liz Kammerb2fc4702021-06-25 14:53:40 -0400524 s.Writeonly = proptools.BoolPtr(true)
Jasraj Bedibb4511d2020-07-23 22:58:17 +0000525 }
Evgenii Stepanov193ac2e2020-04-28 15:09:12 -0700526 if found, globalSanitizers = removeFromList("memtag_heap", globalSanitizers); found && s.Memtag_heap == nil {
Evgenii Stepanov4beaa0c2021-01-05 16:41:26 -0800527 if !ctx.Config().MemtagHeapDisabledForPath(ctx.ModuleDir()) {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400528 s.Memtag_heap = proptools.BoolPtr(true)
Evgenii Stepanov4beaa0c2021-01-05 16:41:26 -0800529 }
Evgenii Stepanov193ac2e2020-04-28 15:09:12 -0700530 }
Jasraj Bedibb4511d2020-07-23 22:58:17 +0000531
Florian Mayerd8434a42022-08-31 20:57:03 +0000532 if found, globalSanitizers = removeFromList("memtag_stack", globalSanitizers); found && s.Memtag_stack == nil {
533 s.Memtag_stack = proptools.BoolPtr(true)
534 }
535
Evgenii Stepanov05bafd32016-07-07 17:38:41 +0000536 if len(globalSanitizers) > 0 {
537 ctx.ModuleErrorf("unknown global sanitizer option %s", globalSanitizers[0])
538 }
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700539
Ivan Lozanoa9255a82018-03-13 10:41:07 -0700540 // Global integer_overflow builds do not support static library diagnostics.
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700541 if found, globalSanitizersDiag = removeFromList("integer_overflow", globalSanitizersDiag); found &&
Ivan Lozanoa9255a82018-03-13 10:41:07 -0700542 s.Diag.Integer_overflow == nil && Bool(s.Integer_overflow) && !ctx.static() {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400543 s.Diag.Integer_overflow = proptools.BoolPtr(true)
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700544 }
545
Vishwath Mohan1fa3ac52017-10-31 02:26:14 -0700546 if found, globalSanitizersDiag = removeFromList("cfi", globalSanitizersDiag); found &&
547 s.Diag.Cfi == nil && Bool(s.Cfi) {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400548 s.Diag.Cfi = proptools.BoolPtr(true)
Vishwath Mohan1fa3ac52017-10-31 02:26:14 -0700549 }
550
Evgenii Stepanov04896ca2021-01-12 18:28:33 -0800551 if found, globalSanitizersDiag = removeFromList("memtag_heap", globalSanitizersDiag); found &&
552 s.Diag.Memtag_heap == nil && Bool(s.Memtag_heap) {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400553 s.Diag.Memtag_heap = proptools.BoolPtr(true)
Evgenii Stepanov04896ca2021-01-12 18:28:33 -0800554 }
555
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700556 if len(globalSanitizersDiag) > 0 {
557 ctx.ModuleErrorf("unknown global sanitizer diagnostics option %s", globalSanitizersDiag[0])
558 }
Evgenii Stepanovfcfe56d2016-07-07 10:54:07 -0700559 }
Colin Cross3c344ef2016-07-18 15:44:56 -0700560
Evgenii Stepanov4beaa0c2021-01-05 16:41:26 -0800561 // Enable Memtag for all components in the include paths (for Aarch64 only)
Colin Cross88a029f2022-06-23 14:51:20 -0700562 if ctx.Arch().ArchType == android.Arm64 && ctx.toolchain().Bionic() {
Evgenii Stepanov4beaa0c2021-01-05 16:41:26 -0800563 if ctx.Config().MemtagHeapSyncEnabledForPath(ctx.ModuleDir()) {
Evgenii Stepanov04896ca2021-01-12 18:28:33 -0800564 if s.Memtag_heap == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400565 s.Memtag_heap = proptools.BoolPtr(true)
Evgenii Stepanov04896ca2021-01-12 18:28:33 -0800566 }
567 if s.Diag.Memtag_heap == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400568 s.Diag.Memtag_heap = proptools.BoolPtr(true)
Evgenii Stepanov04896ca2021-01-12 18:28:33 -0800569 }
Evgenii Stepanov4beaa0c2021-01-05 16:41:26 -0800570 } else if ctx.Config().MemtagHeapAsyncEnabledForPath(ctx.ModuleDir()) {
Evgenii Stepanov04896ca2021-01-12 18:28:33 -0800571 if s.Memtag_heap == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400572 s.Memtag_heap = proptools.BoolPtr(true)
Evgenii Stepanov04896ca2021-01-12 18:28:33 -0800573 }
Evgenii Stepanov4beaa0c2021-01-05 16:41:26 -0800574 }
Evgenii Stepanov193ac2e2020-04-28 15:09:12 -0700575 }
576
Elvis Chien9c993542021-06-25 01:15:17 +0800577 // Enable CFI for non-host components in the include paths
578 if s.Cfi == nil && ctx.Config().CFIEnabledForPath(ctx.ModuleDir()) && !ctx.Host() {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400579 s.Cfi = proptools.BoolPtr(true)
Vishwath Mohan3af8ee02018-03-30 02:55:23 +0000580 if inList("cfi", ctx.Config().SanitizeDeviceDiag()) {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400581 s.Diag.Cfi = proptools.BoolPtr(true)
Vishwath Mohan1fa3ac52017-10-31 02:26:14 -0700582 }
583 }
584
Elliott Hughesda3a0712020-03-06 16:55:28 -0800585 // Is CFI actually enabled?
586 if !ctx.Config().EnableCFI() {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400587 s.Cfi = nil
588 s.Diag.Cfi = nil
Vishwath Mohan1b017a72017-01-19 13:54:55 -0800589 }
590
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700591 // HWASan requires AArch64 hardware feature (top-byte-ignore).
Colin Cross88a029f2022-06-23 14:51:20 -0700592 if ctx.Arch().ArchType != android.Arm64 || !ctx.toolchain().Bionic() {
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700593 s.Hwaddress = nil
594 }
595
Peter Collingbourne8c7e6e22018-11-19 16:03:58 -0800596 // SCS is only implemented on AArch64.
Colin Cross88a029f2022-06-23 14:51:20 -0700597 if ctx.Arch().ArchType != android.Arm64 || !ctx.toolchain().Bionic() {
Peter Collingbourne8c7e6e22018-11-19 16:03:58 -0800598 s.Scs = nil
599 }
600
Ivan Lozano62cd0382021-11-01 10:27:54 -0400601 // Memtag_heap is only implemented on AArch64.
Florian Mayerd8434a42022-08-31 20:57:03 +0000602 // Memtag ABI is Android specific for now, so disable for host.
603 if ctx.Arch().ArchType != android.Arm64 || !ctx.toolchain().Bionic() || ctx.Host() {
Evgenii Stepanov193ac2e2020-04-28 15:09:12 -0700604 s.Memtag_heap = nil
Florian Mayerd8434a42022-08-31 20:57:03 +0000605 s.Memtag_stack = nil
Evgenii Stepanov193ac2e2020-04-28 15:09:12 -0700606 }
607
Vishwath Mohan8f4fdd82017-04-20 07:42:52 -0700608 // Also disable CFI if ASAN is enabled.
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700609 if Bool(s.Address) || Bool(s.Hwaddress) {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400610 s.Cfi = nil
611 s.Diag.Cfi = nil
Florian Mayerd8434a42022-08-31 20:57:03 +0000612 // HWASAN and ASAN win against MTE.
613 s.Memtag_heap = nil
614 s.Memtag_stack = nil
Vishwath Mohan8f4fdd82017-04-20 07:42:52 -0700615 }
616
Colin Crossed12a042022-02-07 13:55:55 -0800617 // Disable sanitizers that depend on the UBSan runtime for windows/darwin builds.
618 if !ctx.Os().Linux() {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400619 s.Cfi = nil
620 s.Diag.Cfi = nil
Ivan Lozanoa9255a82018-03-13 10:41:07 -0700621 s.Misc_undefined = nil
622 s.Undefined = nil
623 s.All_undefined = nil
624 s.Integer_overflow = nil
Vishwath Mohane7128792017-11-17 11:08:10 -0800625 }
626
Colin Cross2c435a02022-10-20 13:55:53 -0700627 // TODO(b/254713216): CFI doesn't work for riscv64 yet because LTO doesn't work.
Colin Crossecf4e662022-10-20 13:59:17 -0700628 if ctx.Arch().ArchType == android.Riscv64 {
629 s.Cfi = nil
630 s.Diag.Cfi = nil
631 }
632
Colin Crossed12a042022-02-07 13:55:55 -0800633 // Disable CFI for musl
634 if ctx.toolchain().Musl() {
635 s.Cfi = nil
636 s.Diag.Cfi = nil
637 }
638
Vishwath Mohan9ccbba02018-05-28 13:54:48 -0700639 // Also disable CFI for VNDK variants of components
640 if ctx.isVndk() && ctx.useVndk() {
Justin Yun08270c62022-12-19 17:01:26 +0900641 s.Cfi = nil
642 s.Diag.Cfi = nil
Inseob Kimeec88e12020-01-22 11:11:29 +0900643 }
644
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700645 // HWASan ramdisk (which is built from recovery) goes over some bootloader limit.
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700646 // Keep libc instrumented so that ramdisk / vendor_ramdisk / recovery can run hwasan-instrumented code if necessary.
647 if (ctx.inRamdisk() || ctx.inVendorRamdisk() || ctx.inRecovery()) && !strings.HasPrefix(ctx.ModuleDir(), "bionic/libc") {
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700648 s.Hwaddress = nil
649 }
650
Colin Cross3c344ef2016-07-18 15:44:56 -0700651 if ctx.staticBinary() {
652 s.Address = nil
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700653 s.Fuzzer = nil
Colin Cross3c344ef2016-07-18 15:44:56 -0700654 s.Thread = nil
Colin Cross16b23492016-01-06 14:41:07 -0800655 }
656
Evgenii Stepanovfcfe56d2016-07-07 10:54:07 -0700657 if Bool(s.All_undefined) {
658 s.Undefined = nil
659 }
660
Evgenii Stepanov0a8a0d02016-05-12 13:54:53 -0700661 if !ctx.toolchain().Is64Bit() {
662 // TSAN and SafeStack are not supported on 32-bit architectures
Evgenii Stepanovfcfe56d2016-07-07 10:54:07 -0700663 s.Thread = nil
664 s.Safestack = nil
Colin Cross16b23492016-01-06 14:41:07 -0800665 // TODO(ccross): error for compile_multilib = "32"?
666 }
667
Evgenii Stepanov76cee232017-01-27 15:44:44 -0800668 if ctx.Os() != android.Windows && (Bool(s.All_undefined) || Bool(s.Undefined) || Bool(s.Address) || Bool(s.Thread) ||
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700669 Bool(s.Fuzzer) || Bool(s.Safestack) || Bool(s.Cfi) || Bool(s.Integer_overflow) || len(s.Misc_undefined) > 0 ||
Florian Mayerd8434a42022-08-31 20:57:03 +0000670 Bool(s.Scudo) || Bool(s.Hwaddress) || Bool(s.Scs) || Bool(s.Memtag_heap) || Bool(s.Memtag_stack)) {
Colin Cross3c344ef2016-07-18 15:44:56 -0700671 sanitize.Properties.SanitizerEnabled = true
672 }
673
Kostya Kortchinskyd5275c82019-02-01 08:42:56 -0800674 // Disable Scudo if ASan or TSan is enabled, or if it's disabled globally.
675 if Bool(s.Address) || Bool(s.Thread) || Bool(s.Hwaddress) || ctx.Config().DisableScudo() {
Kostya Kortchinskyd18ae5c2018-06-12 14:46:54 -0700676 s.Scudo = nil
677 }
678
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700679 if Bool(s.Hwaddress) {
680 s.Address = nil
681 s.Thread = nil
682 }
Mitch Phillips5007c4a2022-03-02 01:25:22 +0000683
684 // TODO(b/131771163): CFI transiently depends on LTO, and thus Fuzzer is
685 // mutually incompatible.
686 if Bool(s.Fuzzer) {
687 s.Cfi = nil
688 }
Colin Cross16b23492016-01-06 14:41:07 -0800689}
690
Chih-Hung Hsieh3567e622018-11-15 14:01:36 -0800691func toDisableImplicitIntegerChange(flags []string) bool {
692 // Returns true if any flag is fsanitize*integer, and there is
693 // no explicit flag about sanitize=implicit-integer-sign-change.
694 for _, f := range flags {
695 if strings.Contains(f, "sanitize=implicit-integer-sign-change") {
696 return false
697 }
698 }
699 for _, f := range flags {
700 if strings.HasPrefix(f, "-fsanitize") && strings.Contains(f, "integer") {
701 return true
702 }
703 }
704 return false
705}
706
Yabin Cuidb7dda82020-11-30 15:47:45 -0800707func toDisableUnsignedShiftBaseChange(flags []string) bool {
708 // Returns true if any flag is fsanitize*integer, and there is
709 // no explicit flag about sanitize=unsigned-shift-base.
710 for _, f := range flags {
711 if strings.Contains(f, "sanitize=unsigned-shift-base") {
712 return false
713 }
714 }
715 for _, f := range flags {
716 if strings.HasPrefix(f, "-fsanitize") && strings.Contains(f, "integer") {
717 return true
718 }
719 }
720 return false
721}
722
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400723func (s *sanitize) flags(ctx ModuleContext, flags Flags) Flags {
724 if !s.Properties.SanitizerEnabled && !s.Properties.UbsanRuntimeDep {
Colin Cross16b23492016-01-06 14:41:07 -0800725 return flags
726 }
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400727 sanProps := &s.Properties.SanitizeMutated
Colin Cross16b23492016-01-06 14:41:07 -0800728
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400729 if Bool(sanProps.Address) {
Colin Cross635c3b02016-05-18 15:37:25 -0700730 if ctx.Arch().ArchType == android.Arm {
Colin Cross16b23492016-01-06 14:41:07 -0800731 // Frame pointer based unwinder in ASan requires ARM frame setup.
732 // TODO: put in flags?
733 flags.RequiredInstructionSet = "arm"
734 }
Colin Cross4af21ed2019-11-04 09:37:55 -0800735 flags.Local.CFlags = append(flags.Local.CFlags, asanCflags...)
736 flags.Local.LdFlags = append(flags.Local.LdFlags, asanLdflags...)
Colin Cross16b23492016-01-06 14:41:07 -0800737
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400738 if Bool(sanProps.Writeonly) {
Jasraj Bedibb4511d2020-07-23 22:58:17 +0000739 flags.Local.CFlags = append(flags.Local.CFlags, "-mllvm", "-asan-instrument-reads=0")
740 }
741
Colin Cross16b23492016-01-06 14:41:07 -0800742 if ctx.Host() {
743 // -nodefaultlibs (provided with libc++) prevents the driver from linking
744 // libraries needed with -fsanitize=address. http://b/18650275 (WAI)
Colin Cross4af21ed2019-11-04 09:37:55 -0800745 flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,--no-as-needed")
Colin Cross16b23492016-01-06 14:41:07 -0800746 } else {
Colin Cross4af21ed2019-11-04 09:37:55 -0800747 flags.Local.CFlags = append(flags.Local.CFlags, "-mllvm", "-asan-globals=0")
Jiyong Parka2aca282019-02-02 13:13:38 +0900748 if ctx.bootstrap() {
749 flags.DynamicLinker = "/system/bin/bootstrap/linker_asan"
750 } else {
751 flags.DynamicLinker = "/system/bin/linker_asan"
752 }
Colin Cross16b23492016-01-06 14:41:07 -0800753 if flags.Toolchain.Is64Bit() {
754 flags.DynamicLinker += "64"
755 }
756 }
Colin Cross16b23492016-01-06 14:41:07 -0800757 }
758
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400759 if Bool(sanProps.Hwaddress) {
Colin Cross4af21ed2019-11-04 09:37:55 -0800760 flags.Local.CFlags = append(flags.Local.CFlags, hwasanCflags...)
Yi Kong286abc62021-11-04 16:14:14 +0800761
762 for _, flag := range hwasanCommonflags {
763 flags.Local.CFlags = append(flags.Local.CFlags, "-mllvm", flag)
764 }
765 for _, flag := range hwasanCommonflags {
766 flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,-mllvm,"+flag)
767 }
768
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400769 if Bool(sanProps.Writeonly) {
Jasraj Bedibb4511d2020-07-23 22:58:17 +0000770 flags.Local.CFlags = append(flags.Local.CFlags, "-mllvm", "-hwasan-instrument-reads=0")
771 }
Yabin Cui6be405e2017-10-19 15:52:11 -0700772 }
773
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400774 if Bool(sanProps.Fuzzer) {
Colin Cross4af21ed2019-11-04 09:37:55 -0800775 flags.Local.CFlags = append(flags.Local.CFlags, "-fsanitize=fuzzer-no-link")
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700776
Mitch Phillips5007c4a2022-03-02 01:25:22 +0000777 // TODO(b/131771163): LTO and Fuzzer support is mutually incompatible.
778 _, flags.Local.LdFlags = removeFromList("-flto", flags.Local.LdFlags)
779 _, flags.Local.CFlags = removeFromList("-flto", flags.Local.CFlags)
780 flags.Local.LdFlags = append(flags.Local.LdFlags, "-fno-lto")
781 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-lto")
782
Mitch Phillipsb8e593d2019-10-09 17:18:59 -0700783 // TODO(b/142430592): Upstream linker scripts for sanitizer runtime libraries
784 // discard the sancov_lowest_stack symbol, because it's emulated TLS (and thus
785 // doesn't match the linker script due to the "__emutls_v." prefix).
Colin Cross4af21ed2019-11-04 09:37:55 -0800786 flags.Local.LdFlags = append(flags.Local.LdFlags, "-fno-sanitize-coverage=stack-depth")
787 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-sanitize-coverage=stack-depth")
Mitch Phillipsb8e593d2019-10-09 17:18:59 -0700788
Mitch Phillipsb9b3e792019-08-28 12:41:07 -0700789 // Disable fortify for fuzzing builds. Generally, we'll be building with
790 // UBSan or ASan here and the fortify checks pollute the stack traces.
Colin Cross4af21ed2019-11-04 09:37:55 -0800791 flags.Local.CFlags = append(flags.Local.CFlags, "-U_FORTIFY_SOURCE")
Mitch Phillips734b4cb2019-12-10 08:44:52 -0800792
793 // Build fuzzer-sanitized libraries with an $ORIGIN DT_RUNPATH. Android's
794 // linker uses DT_RUNPATH, not DT_RPATH. When we deploy cc_fuzz targets and
795 // their libraries to /data/fuzz/<arch>/lib, any transient shared library gets
796 // the DT_RUNPATH from the shared library above it, and not the executable,
797 // meaning that the lookup falls back to the system. Adding the $ORIGIN to the
798 // DT_RUNPATH here means that transient shared libraries can be found
799 // colocated with their parents.
800 flags.Local.LdFlags = append(flags.Local.LdFlags, `-Wl,-rpath,\$$ORIGIN`)
Colin Cross16b23492016-01-06 14:41:07 -0800801 }
802
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400803 if Bool(sanProps.Cfi) {
Evgenii Stepanov7ebf9fa2017-01-20 14:13:06 -0800804 if ctx.Arch().ArchType == android.Arm {
805 // __cfi_check needs to be built as Thumb (see the code in linker_cfi.cpp). LLVM is not set up
806 // to do this on a function basis, so force Thumb on the entire module.
807 flags.RequiredInstructionSet = "thumb"
808 }
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000809
Colin Cross4af21ed2019-11-04 09:37:55 -0800810 flags.Local.CFlags = append(flags.Local.CFlags, cfiCflags...)
811 flags.Local.AsFlags = append(flags.Local.AsFlags, cfiAsflags...)
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400812 if Bool(s.Properties.Sanitize.Config.Cfi_assembly_support) {
Cindy Zhou8cd45de2020-11-16 08:41:00 -0800813 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-sanitize-cfi-canonical-jump-tables")
814 }
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000815 // Only append the default visibility flag if -fvisibility has not already been set
816 // to hidden.
Colin Cross4af21ed2019-11-04 09:37:55 -0800817 if !inList("-fvisibility=hidden", flags.Local.CFlags) {
818 flags.Local.CFlags = append(flags.Local.CFlags, "-fvisibility=default")
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000819 }
Colin Cross4af21ed2019-11-04 09:37:55 -0800820 flags.Local.LdFlags = append(flags.Local.LdFlags, cfiLdflags...)
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000821
822 if ctx.staticBinary() {
Colin Cross4af21ed2019-11-04 09:37:55 -0800823 _, flags.Local.CFlags = removeFromList("-fsanitize-cfi-cross-dso", flags.Local.CFlags)
824 _, flags.Local.LdFlags = removeFromList("-fsanitize-cfi-cross-dso", flags.Local.LdFlags)
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000825 }
Evgenii Stepanov1e405e12016-08-16 15:39:54 -0700826 }
827
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400828 if Bool(sanProps.Memtag_stack) {
Florian Mayerd8434a42022-08-31 20:57:03 +0000829 flags.Local.CFlags = append(flags.Local.CFlags, memtagStackCommonFlags...)
830 flags.Local.AsFlags = append(flags.Local.AsFlags, memtagStackCommonFlags...)
831 flags.Local.LdFlags = append(flags.Local.LdFlags, memtagStackCommonFlags...)
832 }
833
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400834 if (Bool(sanProps.Memtag_heap) || Bool(sanProps.Memtag_stack)) && ctx.binary() {
835 if Bool(sanProps.Diag.Memtag_heap) {
Florian Mayerd8434a42022-08-31 20:57:03 +0000836 flags.Local.LdFlags = append(flags.Local.LdFlags, "-fsanitize-memtag-mode=sync")
837 } else {
838 flags.Local.LdFlags = append(flags.Local.LdFlags, "-fsanitize-memtag-mode=async")
839 }
840 }
841
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400842 if Bool(sanProps.Integer_overflow) {
Colin Cross4af21ed2019-11-04 09:37:55 -0800843 flags.Local.CFlags = append(flags.Local.CFlags, intOverflowCflags...)
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700844 }
845
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400846 if len(s.Properties.Sanitizers) > 0 {
847 sanitizeArg := "-fsanitize=" + strings.Join(s.Properties.Sanitizers, ",")
Colin Cross4af21ed2019-11-04 09:37:55 -0800848 flags.Local.CFlags = append(flags.Local.CFlags, sanitizeArg)
849 flags.Local.AsFlags = append(flags.Local.AsFlags, sanitizeArg)
Colin Cross234b01d2022-02-07 13:49:03 -0800850 flags.Local.LdFlags = append(flags.Local.LdFlags, sanitizeArg)
851
Colin Crossed12a042022-02-07 13:55:55 -0800852 if ctx.toolchain().Bionic() || ctx.toolchain().Musl() {
853 // Bionic and musl sanitizer runtimes have already been added as dependencies so that
854 // the right variant of the runtime will be used (with the "-android" or "-musl"
855 // suffixes), so don't let clang the runtime library.
Colin Cross234b01d2022-02-07 13:49:03 -0800856 flags.Local.LdFlags = append(flags.Local.LdFlags, "-fno-sanitize-link-runtime")
857 } else {
Evgenii Stepanov76cee232017-01-27 15:44:44 -0800858 // Host sanitizers only link symbols in the final executable, so
859 // there will always be undefined symbols in intermediate libraries.
Colin Cross4af21ed2019-11-04 09:37:55 -0800860 _, flags.Global.LdFlags = removeFromList("-Wl,--no-undefined", flags.Global.LdFlags)
Colin Cross6c18d002022-06-02 15:11:50 -0700861 }
Ivan Lozano9ac32c72020-02-19 15:24:02 -0500862
Colin Cross6c18d002022-06-02 15:11:50 -0700863 if !ctx.toolchain().Bionic() {
864 // non-Bionic toolchain prebuilts are missing UBSan's vptr and function san.
865 // Musl toolchain prebuilts have vptr and function sanitizers, but enabling them
866 // implicitly enables RTTI which causes RTTI mismatch issues with dependencies.
867
Colin Cross234b01d2022-02-07 13:49:03 -0800868 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-sanitize=vptr,function")
Ivan Lozano9ac32c72020-02-19 15:24:02 -0500869 }
870
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400871 if Bool(sanProps.Fuzzer) {
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700872 // When fuzzing, we wish to crash with diagnostics on any bug.
Colin Cross4af21ed2019-11-04 09:37:55 -0800873 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-sanitize-trap=all", "-fno-sanitize-recover=all")
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700874 } else if ctx.Host() {
Trevor Radcliffe4f95ee92023-01-19 16:02:47 +0000875 flags.Local.CFlags = append(flags.Local.CFlags, hostOnlySanitizeFlags...)
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700876 } else {
Trevor Radcliffe4f95ee92023-01-19 16:02:47 +0000877 flags.Local.CFlags = append(flags.Local.CFlags, deviceOnlySanitizeFlags...)
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700878 }
Evgenii Stepanov59012812022-06-24 11:09:18 -0700879
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400880 if enableMinimalRuntime(s) {
Evgenii Stepanov59012812022-06-24 11:09:18 -0700881 flags.Local.CFlags = append(flags.Local.CFlags, strings.Join(minimalRuntimeFlags, " "))
882 }
883
Chih-Hung Hsieh3567e622018-11-15 14:01:36 -0800884 // http://b/119329758, Android core does not boot up with this sanitizer yet.
Colin Cross4af21ed2019-11-04 09:37:55 -0800885 if toDisableImplicitIntegerChange(flags.Local.CFlags) {
886 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-sanitize=implicit-integer-sign-change")
Chih-Hung Hsieh3567e622018-11-15 14:01:36 -0800887 }
Yabin Cuidb7dda82020-11-30 15:47:45 -0800888 // http://b/171275751, Android doesn't build with this sanitizer yet.
889 if toDisableUnsignedShiftBaseChange(flags.Local.CFlags) {
890 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-sanitize=unsigned-shift-base")
891 }
Colin Cross16b23492016-01-06 14:41:07 -0800892 }
893
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400894 if len(s.Properties.DiagSanitizers) > 0 {
895 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-sanitize-trap="+strings.Join(s.Properties.DiagSanitizers, ","))
Evgenii Stepanov1e405e12016-08-16 15:39:54 -0700896 }
897 // FIXME: enable RTTI if diag + (cfi or vptr)
898
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400899 if s.Properties.Sanitize.Recover != nil {
Colin Cross4af21ed2019-11-04 09:37:55 -0800900 flags.Local.CFlags = append(flags.Local.CFlags, "-fsanitize-recover="+
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400901 strings.Join(s.Properties.Sanitize.Recover, ","))
Andreas Gampe97071162017-05-08 13:15:23 -0700902 }
903
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400904 if s.Properties.Sanitize.Diag.No_recover != nil {
Colin Cross4af21ed2019-11-04 09:37:55 -0800905 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-sanitize-recover="+
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400906 strings.Join(s.Properties.Sanitize.Diag.No_recover, ","))
Ivan Lozano7929bba2018-12-12 09:36:31 -0800907 }
908
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400909 blocklist := android.OptionalPathForModuleSrc(ctx, s.Properties.Sanitize.Blocklist)
Pirama Arumuga Nainar6c4ccca2020-07-27 11:49:51 -0700910 if blocklist.Valid() {
Pirama Arumuga Nainar582fc2d2021-08-27 15:12:56 -0700911 flags.Local.CFlags = append(flags.Local.CFlags, "-fsanitize-ignorelist="+blocklist.String())
Pirama Arumuga Nainar6c4ccca2020-07-27 11:49:51 -0700912 flags.CFlagsDeps = append(flags.CFlagsDeps, blocklist.Path())
913 }
914
Colin Cross16b23492016-01-06 14:41:07 -0800915 return flags
916}
917
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400918func (s *sanitize) AndroidMkEntries(ctx AndroidMkContext, entries *android.AndroidMkEntries) {
Jiyong Park1d1119f2019-07-29 21:27:18 +0900919 // Add a suffix for cfi/hwasan/scs-enabled static/header libraries to allow surfacing
920 // both the sanitized and non-sanitized variants to make without a name conflict.
Colin Crossd80cbca2020-02-24 12:01:37 -0800921 if entries.Class == "STATIC_LIBRARIES" || entries.Class == "HEADER_LIBRARIES" {
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400922 if Bool(s.Properties.SanitizeMutated.Cfi) {
Colin Crossd80cbca2020-02-24 12:01:37 -0800923 entries.SubName += ".cfi"
Jiyong Park1d1119f2019-07-29 21:27:18 +0900924 }
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400925 if Bool(s.Properties.SanitizeMutated.Hwaddress) {
Colin Crossd80cbca2020-02-24 12:01:37 -0800926 entries.SubName += ".hwasan"
Jiyong Park1d1119f2019-07-29 21:27:18 +0900927 }
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400928 if Bool(s.Properties.SanitizeMutated.Scs) {
Colin Crossd80cbca2020-02-24 12:01:37 -0800929 entries.SubName += ".scs"
Jiyong Park1d1119f2019-07-29 21:27:18 +0900930 }
Peter Collingbourne8c7e6e22018-11-19 16:03:58 -0800931 }
Colin Cross8ff9ef42017-05-08 13:44:11 -0700932}
933
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400934func (s *sanitize) inSanitizerDir() bool {
935 return s.Properties.InSanitizerDir
Colin Cross30d5f512016-05-03 18:02:42 -0700936}
937
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500938// getSanitizerBoolPtr returns the SanitizerTypes associated bool pointer from SanitizeProperties.
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400939func (s *sanitize) getSanitizerBoolPtr(t SanitizerType) *bool {
Vishwath Mohan95229302017-08-11 00:53:16 +0000940 switch t {
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500941 case Asan:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400942 return s.Properties.SanitizeMutated.Address
Tri Vo6eafc362021-04-01 11:29:09 -0700943 case Hwasan:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400944 return s.Properties.SanitizeMutated.Hwaddress
Vishwath Mohan95229302017-08-11 00:53:16 +0000945 case tsan:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400946 return s.Properties.SanitizeMutated.Thread
Vishwath Mohan95229302017-08-11 00:53:16 +0000947 case intOverflow:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400948 return s.Properties.SanitizeMutated.Integer_overflow
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000949 case cfi:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400950 return s.Properties.SanitizeMutated.Cfi
Peter Collingbourne8c7e6e22018-11-19 16:03:58 -0800951 case scs:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400952 return s.Properties.SanitizeMutated.Scs
Ivan Lozano62cd0382021-11-01 10:27:54 -0400953 case Memtag_heap:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400954 return s.Properties.SanitizeMutated.Memtag_heap
Florian Mayerd8434a42022-08-31 20:57:03 +0000955 case Memtag_stack:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400956 return s.Properties.SanitizeMutated.Memtag_stack
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500957 case Fuzzer:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400958 return s.Properties.SanitizeMutated.Fuzzer
Vishwath Mohan95229302017-08-11 00:53:16 +0000959 default:
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500960 panic(fmt.Errorf("unknown SanitizerType %d", t))
Vishwath Mohan95229302017-08-11 00:53:16 +0000961 }
962}
963
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500964// isUnsanitizedVariant returns true if no sanitizers are enabled.
Dan Albert7d1eecf2018-01-19 12:30:45 -0800965func (sanitize *sanitize) isUnsanitizedVariant() bool {
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500966 return !sanitize.isSanitizerEnabled(Asan) &&
Tri Vo6eafc362021-04-01 11:29:09 -0700967 !sanitize.isSanitizerEnabled(Hwasan) &&
Dan Albert7d1eecf2018-01-19 12:30:45 -0800968 !sanitize.isSanitizerEnabled(tsan) &&
Peter Collingbourne8c7e6e22018-11-19 16:03:58 -0800969 !sanitize.isSanitizerEnabled(cfi) &&
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700970 !sanitize.isSanitizerEnabled(scs) &&
Ivan Lozano62cd0382021-11-01 10:27:54 -0400971 !sanitize.isSanitizerEnabled(Memtag_heap) &&
Florian Mayerd8434a42022-08-31 20:57:03 +0000972 !sanitize.isSanitizerEnabled(Memtag_stack) &&
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500973 !sanitize.isSanitizerEnabled(Fuzzer)
Dan Albert7d1eecf2018-01-19 12:30:45 -0800974}
975
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500976// isVariantOnProductionDevice returns true if variant is for production devices (no non-production sanitizers enabled).
Jayant Chowdharyb7e08ca2018-05-10 15:29:24 -0700977func (sanitize *sanitize) isVariantOnProductionDevice() bool {
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500978 return !sanitize.isSanitizerEnabled(Asan) &&
Tri Vo6eafc362021-04-01 11:29:09 -0700979 !sanitize.isSanitizerEnabled(Hwasan) &&
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700980 !sanitize.isSanitizerEnabled(tsan) &&
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500981 !sanitize.isSanitizerEnabled(Fuzzer)
Jayant Chowdharyb7e08ca2018-05-10 15:29:24 -0700982}
983
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500984func (sanitize *sanitize) SetSanitizer(t SanitizerType, b bool) {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400985 bPtr := proptools.BoolPtr(b)
986 if !b {
987 bPtr = nil
988 }
Colin Cross16b23492016-01-06 14:41:07 -0800989 switch t {
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500990 case Asan:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400991 sanitize.Properties.SanitizeMutated.Address = bPtr
Florian Mayer1bda2462022-09-29 15:48:08 -0700992 // For ASAN variant, we need to disable Memtag_stack
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400993 sanitize.Properties.SanitizeMutated.Memtag_stack = nil
Tri Vo6eafc362021-04-01 11:29:09 -0700994 case Hwasan:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400995 sanitize.Properties.SanitizeMutated.Hwaddress = bPtr
Florian Mayer1bda2462022-09-29 15:48:08 -0700996 // For HWAsan variant, we need to disable Memtag_stack
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400997 sanitize.Properties.SanitizeMutated.Memtag_stack = nil
Colin Cross16b23492016-01-06 14:41:07 -0800998 case tsan:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -0400999 sanitize.Properties.SanitizeMutated.Thread = bPtr
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -07001000 case intOverflow:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001001 sanitize.Properties.SanitizeMutated.Integer_overflow = bPtr
Vishwath Mohanb743e9c2017-11-01 09:20:21 +00001002 case cfi:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001003 sanitize.Properties.SanitizeMutated.Cfi = bPtr
Peter Collingbourne8c7e6e22018-11-19 16:03:58 -08001004 case scs:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001005 sanitize.Properties.SanitizeMutated.Scs = bPtr
Ivan Lozano62cd0382021-11-01 10:27:54 -04001006 case Memtag_heap:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001007 sanitize.Properties.SanitizeMutated.Memtag_heap = bPtr
Florian Mayerd8434a42022-08-31 20:57:03 +00001008 case Memtag_stack:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001009 sanitize.Properties.SanitizeMutated.Memtag_stack = bPtr
Florian Mayer1bda2462022-09-29 15:48:08 -07001010 // We do not need to disable ASAN or HWASan here, as there is no Memtag_stack variant.
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001011 case Fuzzer:
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001012 sanitize.Properties.SanitizeMutated.Fuzzer = bPtr
Colin Cross16b23492016-01-06 14:41:07 -08001013 default:
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001014 panic(fmt.Errorf("unknown SanitizerType %d", t))
Colin Cross16b23492016-01-06 14:41:07 -08001015 }
1016 if b {
1017 sanitize.Properties.SanitizerEnabled = true
1018 }
1019}
1020
Vishwath Mohanb743e9c2017-11-01 09:20:21 +00001021// Check if the sanitizer is explicitly disabled (as opposed to nil by
1022// virtue of not being set).
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001023func (sanitize *sanitize) isSanitizerExplicitlyDisabled(t SanitizerType) bool {
Vishwath Mohanb743e9c2017-11-01 09:20:21 +00001024 if sanitize == nil {
1025 return false
1026 }
1027
1028 sanitizerVal := sanitize.getSanitizerBoolPtr(t)
1029 return sanitizerVal != nil && *sanitizerVal == false
1030}
1031
1032// There isn't an analog of the method above (ie:isSanitizerExplicitlyEnabled)
1033// because enabling a sanitizer either directly (via the blueprint) or
1034// indirectly (via a mutator) sets the bool ptr to true, and you can't
1035// distinguish between the cases. It isn't needed though - both cases can be
1036// treated identically.
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001037func (sanitize *sanitize) isSanitizerEnabled(t SanitizerType) bool {
Vishwath Mohanb743e9c2017-11-01 09:20:21 +00001038 if sanitize == nil {
1039 return false
1040 }
1041
1042 sanitizerVal := sanitize.getSanitizerBoolPtr(t)
1043 return sanitizerVal != nil && *sanitizerVal == true
1044}
1045
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001046// IsSanitizableDependencyTag returns true if the dependency tag is sanitizable.
1047func IsSanitizableDependencyTag(tag blueprint.DependencyTag) bool {
Colin Cross6e511a92020-07-27 21:26:48 -07001048 switch t := tag.(type) {
1049 case dependencyTag:
1050 return t == reuseObjTag || t == objDepTag
1051 case libraryDependencyTag:
1052 return true
1053 default:
1054 return false
1055 }
Colin Cross6b753602018-06-21 13:03:07 -07001056}
1057
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001058func (m *Module) SanitizableDepTagChecker() SantizableDependencyTagChecker {
1059 return IsSanitizableDependencyTag
1060}
1061
Inseob Kimc42f2f22020-07-29 20:32:10 +09001062// Determines if the current module is a static library going to be captured
1063// as vendor snapshot. Such modules must create both cfi and non-cfi variants,
1064// except for ones which explicitly disable cfi.
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001065func needsCfiForVendorSnapshot(mctx android.BaseModuleContext) bool {
Justin Yun8814fc52022-12-15 21:45:35 +09001066 if inList("hwaddress", mctx.Config().SanitizeDevice()) {
1067 // cfi will not be built if SANITIZE_TARGET=hwaddress is set
1068 return false
1069 }
1070
Kiyoung Kim48f37782021-07-07 12:42:39 +09001071 if snapshot.IsVendorProprietaryModule(mctx) {
Inseob Kimc42f2f22020-07-29 20:32:10 +09001072 return false
1073 }
1074
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001075 c := mctx.Module().(PlatformSanitizeable)
Inseob Kimc42f2f22020-07-29 20:32:10 +09001076
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001077 if !c.InVendor() {
Inseob Kimc42f2f22020-07-29 20:32:10 +09001078 return false
1079 }
1080
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001081 if !c.StaticallyLinked() {
Inseob Kimc42f2f22020-07-29 20:32:10 +09001082 return false
1083 }
1084
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001085 if c.IsPrebuilt() {
Inseob Kimc42f2f22020-07-29 20:32:10 +09001086 return false
1087 }
1088
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001089 if !c.SanitizerSupported(cfi) {
1090 return false
1091 }
1092
1093 return c.SanitizePropDefined() &&
1094 !c.SanitizeNever() &&
1095 !c.IsSanitizerExplicitlyDisabled(cfi)
Inseob Kimc42f2f22020-07-29 20:32:10 +09001096}
1097
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001098type sanitizerSplitMutator struct {
1099 sanitizer SanitizerType
1100}
1101
1102// If an APEX is sanitized or not depends on whether it contains at least one
1103// sanitized module. Transition mutators cannot propagate information up the
1104// dependency graph this way, so we need an auxiliary mutator to do so.
1105func (s *sanitizerSplitMutator) markSanitizableApexesMutator(ctx android.TopDownMutatorContext) {
1106 if sanitizeable, ok := ctx.Module().(Sanitizeable); ok {
1107 enabled := sanitizeable.IsSanitizerEnabled(ctx.Config(), s.sanitizer.name())
1108 ctx.VisitDirectDeps(func(dep android.Module) {
1109 if c, ok := dep.(*Module); ok && c.sanitize.isSanitizerEnabled(s.sanitizer) {
Inseob Kimc42f2f22020-07-29 20:32:10 +09001110 enabled = true
Inseob Kimc42f2f22020-07-29 20:32:10 +09001111 }
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001112 })
1113
1114 if enabled {
1115 sanitizeable.EnableSanitizer(s.sanitizer.name())
1116 }
1117 }
1118}
1119
1120func (s *sanitizerSplitMutator) Split(ctx android.BaseModuleContext) []string {
1121 if c, ok := ctx.Module().(PlatformSanitizeable); ok && c.SanitizePropDefined() {
1122 if s.sanitizer == cfi && needsCfiForVendorSnapshot(ctx) {
1123 return []string{"", s.sanitizer.variationName()}
1124 }
1125
1126 // If the given sanitizer is not requested in the .bp file for a module, it
1127 // won't automatically build the sanitized variation.
1128 if !c.IsSanitizerEnabled(s.sanitizer) {
1129 return []string{""}
1130 }
1131
1132 if c.Binary() {
1133 // If a sanitizer is enabled for a binary, we do not build the version
1134 // without the sanitizer
1135 return []string{s.sanitizer.variationName()}
1136 } else if c.StaticallyLinked() || c.Header() {
1137 // For static libraries, we build both versions. Some Make modules
1138 // apparently depend on this behavior.
1139 return []string{"", s.sanitizer.variationName()}
1140 } else {
1141 // We only build the requested variation of dynamic libraries
1142 return []string{s.sanitizer.variationName()}
1143 }
1144 }
1145
1146 if _, ok := ctx.Module().(JniSanitizeable); ok {
1147 // TODO: this should call into JniSanitizable.IsSanitizerEnabledForJni but
1148 // that is short-circuited for now
1149 return []string{""}
1150 }
1151
1152 // If an APEX has a sanitized dependency, we build the APEX in the sanitized
1153 // variation. This is useful because such APEXes require extra dependencies.
1154 if sanitizeable, ok := ctx.Module().(Sanitizeable); ok {
1155 enabled := sanitizeable.IsSanitizerEnabled(ctx.Config(), s.sanitizer.name())
1156 if enabled {
1157 return []string{s.sanitizer.variationName()}
1158 } else {
1159 return []string{""}
1160 }
1161 }
1162
1163 if c, ok := ctx.Module().(*Module); ok {
1164 //TODO: When Rust modules have vendor support, enable this path for PlatformSanitizeable
1165
1166 // Check if it's a snapshot module supporting sanitizer
Justin Yun08270c62022-12-19 17:01:26 +09001167 if ss, ok := c.linker.(snapshotSanitizer); ok {
1168 if ss.isSanitizerAvailable(s.sanitizer) {
1169 return []string{"", s.sanitizer.variationName()}
1170 } else {
1171 return []string{""}
1172 }
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001173 }
1174 }
1175
1176 return []string{""}
1177}
1178
1179func (s *sanitizerSplitMutator) OutgoingTransition(ctx android.OutgoingTransitionContext, sourceVariation string) string {
1180 if c, ok := ctx.Module().(PlatformSanitizeable); ok {
1181 if !c.SanitizableDepTagChecker()(ctx.DepTag()) {
1182 // If the dependency is through a non-sanitizable tag, use the
1183 // non-sanitized variation
1184 return ""
1185 }
1186
1187 return sourceVariation
1188 } else if _, ok := ctx.Module().(JniSanitizeable); ok {
1189 // TODO: this should call into JniSanitizable.IsSanitizerEnabledForJni but
1190 // that is short-circuited for now
1191 return ""
1192 } else {
1193 // Otherwise, do not rock the boat.
1194 return sourceVariation
1195 }
1196}
1197
1198func (s *sanitizerSplitMutator) IncomingTransition(ctx android.IncomingTransitionContext, incomingVariation string) string {
1199 if d, ok := ctx.Module().(PlatformSanitizeable); ok {
1200 if dm, ok := ctx.Module().(*Module); ok {
Justin Yun39c30312022-11-23 16:20:12 +09001201 if ss, ok := dm.linker.(snapshotSanitizer); ok && ss.isSanitizerAvailable(s.sanitizer) {
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001202 return incomingVariation
Inseob Kimc42f2f22020-07-29 20:32:10 +09001203 }
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001204 }
1205
1206 if !d.SanitizePropDefined() ||
1207 d.SanitizeNever() ||
1208 d.IsSanitizerExplicitlyDisabled(s.sanitizer) ||
1209 !d.SanitizerSupported(s.sanitizer) {
1210 // If a module opts out of a sanitizer, use its non-sanitized variation
1211 return ""
1212 }
1213
1214 // Binaries are always built in the variation they requested.
1215 if d.Binary() {
1216 if d.IsSanitizerEnabled(s.sanitizer) {
1217 return s.sanitizer.variationName()
1218 } else {
1219 return ""
Muhammad Haseeb Ahmad7e744052022-03-25 22:50:53 +00001220 }
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001221 }
1222
1223 // If a shared library requests to be sanitized, it will be built for that
1224 // sanitizer. Otherwise, some sanitizers propagate through shared library
1225 // dependency edges, some do not.
1226 if !d.StaticallyLinked() && !d.Header() {
1227 if d.IsSanitizerEnabled(s.sanitizer) {
1228 return s.sanitizer.variationName()
1229 }
1230
Liz Kammerfd8a49f2022-10-31 10:31:11 -04001231 // Some sanitizers do not propagate to shared dependencies
1232 if !s.sanitizer.shouldPropagateToSharedLibraryDeps() {
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001233 return ""
1234 }
1235 }
1236
1237 // Static and header libraries inherit whether they are sanitized from the
1238 // module they are linked into
1239 return incomingVariation
1240 } else if d, ok := ctx.Module().(Sanitizeable); ok {
1241 // If an APEX contains a sanitized module, it will be built in the variation
1242 // corresponding to that sanitizer.
1243 enabled := d.IsSanitizerEnabled(ctx.Config(), s.sanitizer.name())
1244 if enabled {
1245 return s.sanitizer.variationName()
1246 }
1247
1248 return incomingVariation
1249 }
1250
1251 return ""
1252}
1253
1254func (s *sanitizerSplitMutator) Mutate(mctx android.BottomUpMutatorContext, variationName string) {
1255 sanitizerVariation := variationName == s.sanitizer.variationName()
1256
1257 if c, ok := mctx.Module().(PlatformSanitizeable); ok && c.SanitizePropDefined() {
1258 sanitizerEnabled := c.IsSanitizerEnabled(s.sanitizer)
1259
1260 oneMakeVariation := false
1261 if c.StaticallyLinked() || c.Header() {
1262 if s.sanitizer != cfi && s.sanitizer != scs && s.sanitizer != Hwasan {
1263 // These sanitizers export only one variation to Make. For the rest,
1264 // Make targets can depend on both the sanitized and non-sanitized
1265 // versions.
1266 oneMakeVariation = true
1267 }
1268 } else if !c.Binary() {
1269 // Shared library. These are the sanitizers that do propagate through shared
1270 // library dependencies and therefore can cause multiple variations of a
1271 // shared library to be built.
1272 if s.sanitizer != cfi && s.sanitizer != Hwasan && s.sanitizer != scs && s.sanitizer != Asan {
1273 oneMakeVariation = true
1274 }
1275 }
1276
1277 if oneMakeVariation {
1278 if sanitizerEnabled != sanitizerVariation {
1279 c.SetPreventInstall()
1280 c.SetHideFromMake()
1281 }
1282 }
1283
1284 if sanitizerVariation {
1285 c.SetSanitizer(s.sanitizer, true)
1286
1287 // CFI is incompatible with ASAN so disable it in ASAN variations
1288 if s.sanitizer.incompatibleWithCfi() {
1289 cfiSupported := mctx.Module().(PlatformSanitizeable).SanitizerSupported(cfi)
1290 if mctx.Device() && cfiSupported {
1291 c.SetSanitizer(cfi, false)
Jiyong Parkf97782b2019-02-13 20:28:58 +09001292 }
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001293 }
1294
1295 // locate the asan libraries under /data/asan
1296 if !c.Binary() && !c.StaticallyLinked() && !c.Header() && mctx.Device() && s.sanitizer == Asan && sanitizerEnabled {
1297 c.SetInSanitizerDir()
1298 }
1299
1300 if c.StaticallyLinked() && c.ExportedToMake() {
1301 if s.sanitizer == Hwasan {
1302 hwasanStaticLibs(mctx.Config()).add(c, c.Module().Name())
1303 } else if s.sanitizer == cfi {
1304 cfiStaticLibs(mctx.Config()).add(c, c.Module().Name())
1305 }
1306 }
1307 } else if c.IsSanitizerEnabled(s.sanitizer) {
1308 // Disable the sanitizer for the non-sanitized variation
1309 c.SetSanitizer(s.sanitizer, false)
1310 }
1311 } else if sanitizeable, ok := mctx.Module().(Sanitizeable); ok {
1312 // If an APEX has sanitized dependencies, it gets a few more dependencies
1313 if sanitizerVariation {
1314 sanitizeable.AddSanitizerDependencies(mctx, s.sanitizer.name())
1315 }
1316 } else if c, ok := mctx.Module().(*Module); ok {
Justin Yun39c30312022-11-23 16:20:12 +09001317 if ss, ok := c.linker.(snapshotSanitizer); ok && ss.isSanitizerAvailable(s.sanitizer) {
1318 if !ss.isUnsanitizedVariant() {
1319 // Snapshot sanitizer may have only one variantion.
1320 // Skip exporting the module if it already has a sanitizer variation.
1321 c.SetPreventInstall()
1322 c.SetHideFromMake()
1323 return
1324 }
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001325 c.linker.(snapshotSanitizer).setSanitizerVariation(s.sanitizer, sanitizerVariation)
1326
1327 // Export the static lib name to make
1328 if c.static() && c.ExportedToMake() {
Justin Yun39c30312022-11-23 16:20:12 +09001329 // use BaseModuleName which is the name for Make.
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001330 if s.sanitizer == cfi {
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001331 cfiStaticLibs(mctx.Config()).add(c, c.BaseModuleName())
Justin Yun39c30312022-11-23 16:20:12 +09001332 } else if s.sanitizer == Hwasan {
1333 hwasanStaticLibs(mctx.Config()).add(c, c.BaseModuleName())
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001334 }
1335 }
Colin Cross16b23492016-01-06 14:41:07 -08001336 }
1337 }
1338}
1339
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001340func (c *Module) SanitizeNever() bool {
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001341 return Bool(c.sanitize.Properties.SanitizeMutated.Never)
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001342}
1343
1344func (c *Module) IsSanitizerExplicitlyDisabled(t SanitizerType) bool {
1345 return c.sanitize.isSanitizerExplicitlyDisabled(t)
1346}
1347
Ivan Lozano30c5db22018-02-21 15:49:20 -08001348// Propagate the ubsan minimal runtime dependency when there are integer overflow sanitized static dependencies.
Colin Cross6b753602018-06-21 13:03:07 -07001349func sanitizerRuntimeDepsMutator(mctx android.TopDownMutatorContext) {
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001350 // Change this to PlatformSanitizable when/if non-cc modules support ubsan sanitizers.
Colin Cross6b753602018-06-21 13:03:07 -07001351 if c, ok := mctx.Module().(*Module); ok && c.sanitize != nil {
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001352 isSanitizableDependencyTag := c.SanitizableDepTagChecker()
Colin Cross6b753602018-06-21 13:03:07 -07001353 mctx.WalkDeps(func(child, parent android.Module) bool {
1354 if !isSanitizableDependencyTag(mctx.OtherModuleDependencyTag(child)) {
1355 return false
1356 }
Ivan Lozano30c5db22018-02-21 15:49:20 -08001357
Inseob Kimeec88e12020-01-22 11:11:29 +09001358 d, ok := child.(*Module)
1359 if !ok || !d.static() {
1360 return false
1361 }
1362 if d.sanitize != nil {
Colin Cross6b753602018-06-21 13:03:07 -07001363 if enableMinimalRuntime(d.sanitize) {
1364 // If a static dependency is built with the minimal runtime,
1365 // make sure we include the ubsan minimal runtime.
1366 c.sanitize.Properties.MinimalRuntimeDep = true
Inseob Kim8471cda2019-11-15 09:59:12 +09001367 } else if enableUbsanRuntime(d.sanitize) {
Colin Cross6b753602018-06-21 13:03:07 -07001368 // If a static dependency runs with full ubsan diagnostics,
1369 // make sure we include the ubsan runtime.
1370 c.sanitize.Properties.UbsanRuntimeDep = true
Ivan Lozano30c5db22018-02-21 15:49:20 -08001371 }
Colin Cross0b908332019-06-19 23:00:20 -07001372
1373 if c.sanitize.Properties.MinimalRuntimeDep &&
1374 c.sanitize.Properties.UbsanRuntimeDep {
1375 // both flags that this mutator might set are true, so don't bother recursing
1376 return false
1377 }
1378
Ivan Lozano9ac32c72020-02-19 15:24:02 -05001379 if c.Os() == android.Linux {
1380 c.sanitize.Properties.BuiltinsDep = true
1381 }
1382
Colin Cross0b908332019-06-19 23:00:20 -07001383 return true
Colin Cross6b753602018-06-21 13:03:07 -07001384 }
Inseob Kimeec88e12020-01-22 11:11:29 +09001385
Jose Galmesf7294582020-11-13 12:07:36 -08001386 if p, ok := d.linker.(*snapshotLibraryDecorator); ok {
Inseob Kimeec88e12020-01-22 11:11:29 +09001387 if Bool(p.properties.Sanitize_minimal_dep) {
1388 c.sanitize.Properties.MinimalRuntimeDep = true
1389 }
1390 if Bool(p.properties.Sanitize_ubsan_dep) {
1391 c.sanitize.Properties.UbsanRuntimeDep = true
1392 }
1393 }
1394
1395 return false
Colin Cross6b753602018-06-21 13:03:07 -07001396 })
Ivan Lozano30c5db22018-02-21 15:49:20 -08001397 }
1398}
1399
Jiyong Park379de2f2018-12-19 02:47:14 +09001400// Add the dependency to the runtime library for each of the sanitizer variants
1401func sanitizerRuntimeMutator(mctx android.BottomUpMutatorContext) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001402 if c, ok := mctx.Module().(*Module); ok && c.sanitize != nil {
Pirama Arumuga Nainar6aa21022019-01-25 00:20:35 +00001403 if !c.Enabled() {
1404 return
1405 }
Jiyong Park379de2f2018-12-19 02:47:14 +09001406 var sanitizers []string
1407 var diagSanitizers []string
1408
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001409 sanProps := &c.sanitize.Properties.SanitizeMutated
1410
1411 if Bool(sanProps.All_undefined) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001412 sanitizers = append(sanitizers, "undefined")
1413 } else {
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001414 if Bool(sanProps.Undefined) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001415 sanitizers = append(sanitizers,
1416 "bool",
1417 "integer-divide-by-zero",
1418 "return",
1419 "returns-nonnull-attribute",
1420 "shift-exponent",
1421 "unreachable",
1422 "vla-bound",
1423 // TODO(danalbert): The following checks currently have compiler performance issues.
1424 //"alignment",
1425 //"bounds",
1426 //"enum",
1427 //"float-cast-overflow",
1428 //"float-divide-by-zero",
1429 //"nonnull-attribute",
1430 //"null",
1431 //"shift-base",
1432 //"signed-integer-overflow",
1433 // TODO(danalbert): Fix UB in libc++'s __tree so we can turn this on.
1434 // https://llvm.org/PR19302
1435 // http://reviews.llvm.org/D6974
1436 // "object-size",
1437 )
1438 }
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001439 sanitizers = append(sanitizers, sanProps.Misc_undefined...)
Jiyong Park379de2f2018-12-19 02:47:14 +09001440 }
1441
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001442 if Bool(sanProps.Diag.Undefined) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001443 diagSanitizers = append(diagSanitizers, "undefined")
1444 }
1445
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001446 diagSanitizers = append(diagSanitizers, sanProps.Diag.Misc_undefined...)
Jiyong Park379de2f2018-12-19 02:47:14 +09001447
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001448 if Bool(sanProps.Address) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001449 sanitizers = append(sanitizers, "address")
1450 diagSanitizers = append(diagSanitizers, "address")
1451 }
1452
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001453 if Bool(sanProps.Hwaddress) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001454 sanitizers = append(sanitizers, "hwaddress")
1455 }
1456
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001457 if Bool(sanProps.Thread) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001458 sanitizers = append(sanitizers, "thread")
1459 }
1460
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001461 if Bool(sanProps.Safestack) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001462 sanitizers = append(sanitizers, "safe-stack")
1463 }
1464
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001465 if Bool(sanProps.Cfi) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001466 sanitizers = append(sanitizers, "cfi")
1467
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001468 if Bool(sanProps.Diag.Cfi) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001469 diagSanitizers = append(diagSanitizers, "cfi")
1470 }
1471 }
1472
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001473 if Bool(sanProps.Integer_overflow) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001474 sanitizers = append(sanitizers, "unsigned-integer-overflow")
1475 sanitizers = append(sanitizers, "signed-integer-overflow")
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001476 if Bool(sanProps.Diag.Integer_overflow) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001477 diagSanitizers = append(diagSanitizers, "unsigned-integer-overflow")
1478 diagSanitizers = append(diagSanitizers, "signed-integer-overflow")
1479 }
1480 }
1481
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001482 if Bool(sanProps.Scudo) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001483 sanitizers = append(sanitizers, "scudo")
1484 }
1485
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001486 if Bool(sanProps.Scs) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001487 sanitizers = append(sanitizers, "shadow-call-stack")
1488 }
1489
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001490 if Bool(sanProps.Memtag_heap) && c.Binary() {
Florian Mayerd8434a42022-08-31 20:57:03 +00001491 sanitizers = append(sanitizers, "memtag-heap")
1492 }
1493
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001494 if Bool(sanProps.Memtag_stack) {
Florian Mayerd8434a42022-08-31 20:57:03 +00001495 sanitizers = append(sanitizers, "memtag-stack")
Evgenii Stepanov193ac2e2020-04-28 15:09:12 -07001496 }
1497
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001498 if Bool(sanProps.Fuzzer) {
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -07001499 sanitizers = append(sanitizers, "fuzzer-no-link")
1500 }
1501
Jiyong Park379de2f2018-12-19 02:47:14 +09001502 // Save the list of sanitizers. These will be used again when generating
1503 // the build rules (for Cflags, etc.)
1504 c.sanitize.Properties.Sanitizers = sanitizers
1505 c.sanitize.Properties.DiagSanitizers = diagSanitizers
1506
Ivan Lozanof3b190f2020-03-06 12:01:21 -05001507 // TODO(b/150822854) Hosts have a different default behavior and assume the runtime library is used.
1508 if c.Host() {
1509 diagSanitizers = sanitizers
1510 }
1511
Jiyong Park379de2f2018-12-19 02:47:14 +09001512 // Determine the runtime library required
1513 runtimeLibrary := ""
Colin Crosse725b4e2022-10-19 15:46:53 -07001514 alwaysStaticRuntime := false
Ryan Prichardb49fe1b2019-10-11 15:03:34 -07001515 var extraStaticDeps []string
Jiyong Park379de2f2018-12-19 02:47:14 +09001516 toolchain := c.toolchain(mctx)
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001517 if Bool(sanProps.Address) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001518 runtimeLibrary = config.AddressSanitizerRuntimeLibrary(toolchain)
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001519 } else if Bool(sanProps.Hwaddress) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001520 if c.staticBinary() {
1521 runtimeLibrary = config.HWAddressSanitizerStaticLibrary(toolchain)
Ryan Prichardb49fe1b2019-10-11 15:03:34 -07001522 extraStaticDeps = []string{"libdl"}
Jiyong Park379de2f2018-12-19 02:47:14 +09001523 } else {
1524 runtimeLibrary = config.HWAddressSanitizerRuntimeLibrary(toolchain)
1525 }
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001526 } else if Bool(sanProps.Thread) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001527 runtimeLibrary = config.ThreadSanitizerRuntimeLibrary(toolchain)
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001528 } else if Bool(sanProps.Scudo) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001529 if len(diagSanitizers) == 0 && !c.sanitize.Properties.UbsanRuntimeDep {
1530 runtimeLibrary = config.ScudoMinimalRuntimeLibrary(toolchain)
1531 } else {
1532 runtimeLibrary = config.ScudoRuntimeLibrary(toolchain)
1533 }
Mitch Phillipsb8e593d2019-10-09 17:18:59 -07001534 } else if len(diagSanitizers) > 0 || c.sanitize.Properties.UbsanRuntimeDep ||
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001535 Bool(sanProps.Fuzzer) ||
1536 Bool(sanProps.Undefined) ||
1537 Bool(sanProps.All_undefined) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001538 runtimeLibrary = config.UndefinedBehaviorSanitizerRuntimeLibrary(toolchain)
Colin Crosse725b4e2022-10-19 15:46:53 -07001539 if c.staticBinary() || toolchain.Musl() {
1540 // Use a static runtime for static binaries.
1541 // Also use a static runtime for musl to match
1542 // what clang does for glibc. Otherwise dlopening
1543 // libraries that depend on libclang_rt.ubsan_standalone.so
1544 // fails with:
1545 // Error relocating ...: initial-exec TLS resolves to dynamic definition
Colin Cross32f1de32021-03-29 13:41:37 -07001546 runtimeLibrary += ".static"
Colin Crosse725b4e2022-10-19 15:46:53 -07001547 alwaysStaticRuntime = true
Colin Cross32f1de32021-03-29 13:41:37 -07001548 }
Jiyong Park379de2f2018-12-19 02:47:14 +09001549 }
1550
Colin Cross06c80eb2022-02-10 10:34:19 -08001551 addStaticDeps := func(deps ...string) {
1552 // If we're using snapshots, redirect to snapshot whenever possible
1553 snapshot := mctx.Provider(SnapshotInfoProvider).(SnapshotInfo)
1554 for idx, dep := range deps {
1555 if lib, ok := snapshot.StaticLibs[dep]; ok {
1556 deps[idx] = lib
1557 }
1558 }
1559
1560 // static executable gets static runtime libs
Colin Cross3e5e7782022-06-17 22:17:05 +00001561 depTag := libraryDependencyTag{Kind: staticLibraryDependency, unexportedSymbols: true}
Colin Cross06c80eb2022-02-10 10:34:19 -08001562 variations := append(mctx.Target().Variations(),
1563 blueprint.Variation{Mutator: "link", Variation: "static"})
1564 if c.Device() {
1565 variations = append(variations, c.ImageVariation())
1566 }
1567 if c.UseSdk() {
1568 variations = append(variations,
1569 blueprint.Variation{Mutator: "sdk", Variation: "sdk"})
1570 }
1571 mctx.AddFarVariationDependencies(variations, depTag, deps...)
1572
1573 }
1574 if enableMinimalRuntime(c.sanitize) || c.sanitize.Properties.MinimalRuntimeDep {
1575 addStaticDeps(config.UndefinedBehaviorSanitizerMinimalRuntimeLibrary(toolchain))
1576 }
1577 if c.sanitize.Properties.BuiltinsDep {
1578 addStaticDeps(config.BuiltinsRuntimeLibrary(toolchain))
1579 }
1580
Colin Crossed12a042022-02-07 13:55:55 -08001581 if runtimeLibrary != "" && (toolchain.Bionic() || toolchain.Musl() || c.sanitize.Properties.UbsanRuntimeDep) {
Ivan Lozano9ac32c72020-02-19 15:24:02 -05001582 // UBSan is supported on non-bionic linux host builds as well
Jiyong Park379de2f2018-12-19 02:47:14 +09001583
1584 // Adding dependency to the runtime library. We are using *FarVariation*
1585 // because the runtime libraries themselves are not mutated by sanitizer
1586 // mutators and thus don't have sanitizer variants whereas this module
1587 // has been already mutated.
1588 //
1589 // Note that by adding dependency with {static|shared}DepTag, the lib is
1590 // added to libFlags and LOCAL_SHARED_LIBRARIES by cc.Module
Colin Crosse725b4e2022-10-19 15:46:53 -07001591 if c.staticBinary() || alwaysStaticRuntime {
Colin Cross06c80eb2022-02-10 10:34:19 -08001592 addStaticDeps(runtimeLibrary)
1593 addStaticDeps(extraStaticDeps...)
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001594 } else if !c.static() && !c.Header() {
Colin Crosse0edaf92021-01-11 17:31:17 -08001595 // If we're using snapshots, redirect to snapshot whenever possible
1596 snapshot := mctx.Provider(SnapshotInfoProvider).(SnapshotInfo)
1597 if lib, ok := snapshot.SharedLibs[runtimeLibrary]; ok {
1598 runtimeLibrary = lib
Inseob Kimeec88e12020-01-22 11:11:29 +09001599 }
Colin Crosse0edaf92021-01-11 17:31:17 -08001600
Cindy Zhou18417cb2020-12-10 07:12:38 -08001601 // Skip apex dependency check for sharedLibraryDependency
1602 // when sanitizer diags are enabled. Skipping the check will allow
1603 // building with diag libraries without having to list the
1604 // dependency in Apex's allowed_deps file.
1605 diagEnabled := len(diagSanitizers) > 0
Jiyong Park3b1746a2019-01-29 11:15:04 +09001606 // dynamic executable and shared libs get shared runtime libs
Cindy Zhou18417cb2020-12-10 07:12:38 -08001607 depTag := libraryDependencyTag{
1608 Kind: sharedLibraryDependency,
1609 Order: earlyLibraryDependency,
1610
1611 skipApexAllowedDependenciesCheck: diagEnabled,
1612 }
Colin Cross42507332020-08-21 16:15:23 -07001613 variations := append(mctx.Target().Variations(),
1614 blueprint.Variation{Mutator: "link", Variation: "shared"})
1615 if c.Device() {
1616 variations = append(variations, c.ImageVariation())
1617 }
Colin Cross06c80eb2022-02-10 10:34:19 -08001618 if c.UseSdk() {
1619 variations = append(variations,
1620 blueprint.Variation{Mutator: "sdk", Variation: "sdk"})
1621 }
Ivan Lozanod67a6b02021-05-20 13:01:32 -04001622 AddSharedLibDependenciesWithVersions(mctx, c, variations, depTag, runtimeLibrary, "", true)
Jiyong Park379de2f2018-12-19 02:47:14 +09001623 }
1624 // static lib does not have dependency to the runtime library. The
1625 // dependency will be added to the executables or shared libs using
1626 // the static lib.
1627 }
1628 }
1629}
1630
1631type Sanitizeable interface {
1632 android.Module
Lukacs T. Berki01a648a2022-06-17 08:59:37 +02001633 IsSanitizerEnabled(config android.Config, sanitizerName string) bool
Jiyong Parkf97782b2019-02-13 20:28:58 +09001634 EnableSanitizer(sanitizerName string)
Jooyung Han8ce8db92020-05-15 19:05:05 +09001635 AddSanitizerDependencies(ctx android.BottomUpMutatorContext, sanitizerName string)
Jiyong Park379de2f2018-12-19 02:47:14 +09001636}
1637
Muhammad Haseeb Ahmad7e744052022-03-25 22:50:53 +00001638type JniSanitizeable interface {
1639 android.Module
1640 IsSanitizerEnabledForJni(ctx android.BaseModuleContext, sanitizerName string) bool
1641}
1642
Ivan Lozanod7586b62021-04-01 09:49:36 -04001643func (c *Module) MinimalRuntimeDep() bool {
1644 return c.sanitize.Properties.MinimalRuntimeDep
1645}
1646
1647func (c *Module) UbsanRuntimeDep() bool {
1648 return c.sanitize.Properties.UbsanRuntimeDep
1649}
1650
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001651func (c *Module) SanitizePropDefined() bool {
1652 return c.sanitize != nil
1653}
1654
1655func (c *Module) IsSanitizerEnabled(t SanitizerType) bool {
1656 return c.sanitize.isSanitizerEnabled(t)
1657}
1658
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001659func (c *Module) StaticallyLinked() bool {
1660 return c.static()
1661}
1662
1663func (c *Module) SetInSanitizerDir() {
1664 if c.sanitize != nil {
1665 c.sanitize.Properties.InSanitizerDir = true
1666 }
1667}
1668
1669func (c *Module) SetSanitizer(t SanitizerType, b bool) {
1670 if c.sanitize != nil {
1671 c.sanitize.SetSanitizer(t, b)
1672 }
1673}
1674
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001675var _ PlatformSanitizeable = (*Module)(nil)
1676
Inseob Kim74d25562020-08-04 00:41:38 +09001677type sanitizerStaticLibsMap struct {
1678 // libsMap contains one list of modules per each image and each arch.
1679 // e.g. libs[vendor]["arm"] contains arm modules installed to vendor
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001680 libsMap map[ImageVariantType]map[string][]string
Inseob Kim74d25562020-08-04 00:41:38 +09001681 libsMapLock sync.Mutex
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001682 sanitizerType SanitizerType
Inseob Kim74d25562020-08-04 00:41:38 +09001683}
1684
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001685func newSanitizerStaticLibsMap(t SanitizerType) *sanitizerStaticLibsMap {
Inseob Kim74d25562020-08-04 00:41:38 +09001686 return &sanitizerStaticLibsMap{
1687 sanitizerType: t,
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001688 libsMap: make(map[ImageVariantType]map[string][]string),
Inseob Kim74d25562020-08-04 00:41:38 +09001689 }
1690}
1691
1692// Add the current module to sanitizer static libs maps
1693// Each module should pass its exported name as names of Make and Soong can differ.
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001694func (s *sanitizerStaticLibsMap) add(c LinkableInterface, name string) {
1695 image := GetImageVariantType(c)
1696 arch := c.Module().Target().Arch.ArchType.String()
Inseob Kim74d25562020-08-04 00:41:38 +09001697
1698 s.libsMapLock.Lock()
1699 defer s.libsMapLock.Unlock()
1700
1701 if _, ok := s.libsMap[image]; !ok {
1702 s.libsMap[image] = make(map[string][]string)
1703 }
1704
1705 s.libsMap[image][arch] = append(s.libsMap[image][arch], name)
1706}
1707
1708// Exports makefile variables in the following format:
1709// SOONG_{sanitizer}_{image}_{arch}_STATIC_LIBRARIES
1710// e.g. SOONG_cfi_core_x86_STATIC_LIBRARIES
1711// These are to be used by use_soong_sanitized_static_libraries.
1712// See build/make/core/binary.mk for more details.
1713func (s *sanitizerStaticLibsMap) exportToMake(ctx android.MakeVarsContext) {
Cole Faust18994c72023-02-28 16:02:16 -08001714 for _, image := range android.SortedKeys(s.libsMap) {
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001715 archMap := s.libsMap[ImageVariantType(image)]
Cole Faust18994c72023-02-28 16:02:16 -08001716 for _, arch := range android.SortedKeys(archMap) {
Inseob Kim74d25562020-08-04 00:41:38 +09001717 libs := archMap[arch]
1718 sort.Strings(libs)
1719
1720 key := fmt.Sprintf(
1721 "SOONG_%s_%s_%s_STATIC_LIBRARIES",
1722 s.sanitizerType.variationName(),
1723 image, // already upper
1724 arch)
1725
1726 ctx.Strict(key, strings.Join(libs, " "))
1727 }
1728 }
1729}
1730
Colin Cross571cccf2019-02-04 11:22:08 -08001731var cfiStaticLibsKey = android.NewOnceKey("cfiStaticLibs")
1732
Inseob Kim74d25562020-08-04 00:41:38 +09001733func cfiStaticLibs(config android.Config) *sanitizerStaticLibsMap {
Colin Cross571cccf2019-02-04 11:22:08 -08001734 return config.Once(cfiStaticLibsKey, func() interface{} {
Inseob Kim74d25562020-08-04 00:41:38 +09001735 return newSanitizerStaticLibsMap(cfi)
1736 }).(*sanitizerStaticLibsMap)
Vishwath Mohane7128792017-11-17 11:08:10 -08001737}
1738
Colin Cross571cccf2019-02-04 11:22:08 -08001739var hwasanStaticLibsKey = android.NewOnceKey("hwasanStaticLibs")
1740
Inseob Kim74d25562020-08-04 00:41:38 +09001741func hwasanStaticLibs(config android.Config) *sanitizerStaticLibsMap {
Colin Cross571cccf2019-02-04 11:22:08 -08001742 return config.Once(hwasanStaticLibsKey, func() interface{} {
Tri Vo6eafc362021-04-01 11:29:09 -07001743 return newSanitizerStaticLibsMap(Hwasan)
Inseob Kim74d25562020-08-04 00:41:38 +09001744 }).(*sanitizerStaticLibsMap)
Jiyong Park1d1119f2019-07-29 21:27:18 +09001745}
1746
Ivan Lozano30c5db22018-02-21 15:49:20 -08001747func enableMinimalRuntime(sanitize *sanitize) bool {
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001748 if sanitize.isSanitizerEnabled(Asan) {
1749 return false
1750 } else if sanitize.isSanitizerEnabled(Hwasan) {
1751 return false
1752 } else if sanitize.isSanitizerEnabled(Fuzzer) {
1753 return false
Ivan Lozano30c5db22018-02-21 15:49:20 -08001754 }
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001755
1756 if enableUbsanRuntime(sanitize) {
1757 return false
1758 }
1759
1760 sanitizeProps := &sanitize.Properties.SanitizeMutated
1761 if Bool(sanitizeProps.Diag.Cfi) {
1762 return false
1763 }
1764
1765 return Bool(sanitizeProps.Integer_overflow) ||
1766 len(sanitizeProps.Misc_undefined) > 0 ||
1767 Bool(sanitizeProps.Undefined) ||
1768 Bool(sanitizeProps.All_undefined)
Ivan Lozano30c5db22018-02-21 15:49:20 -08001769}
1770
Ivan Lozanod7586b62021-04-01 09:49:36 -04001771func (m *Module) UbsanRuntimeNeeded() bool {
1772 return enableUbsanRuntime(m.sanitize)
1773}
1774
1775func (m *Module) MinimalRuntimeNeeded() bool {
1776 return enableMinimalRuntime(m.sanitize)
1777}
1778
Inseob Kim8471cda2019-11-15 09:59:12 +09001779func enableUbsanRuntime(sanitize *sanitize) bool {
Liz Kammer2c1d6aa2022-10-03 15:07:37 -04001780 sanitizeProps := &sanitize.Properties.SanitizeMutated
1781 return Bool(sanitizeProps.Diag.Integer_overflow) ||
1782 Bool(sanitizeProps.Diag.Undefined) ||
1783 len(sanitizeProps.Diag.Misc_undefined) > 0
Inseob Kim8471cda2019-11-15 09:59:12 +09001784}
1785
Vishwath Mohane7128792017-11-17 11:08:10 -08001786func cfiMakeVarsProvider(ctx android.MakeVarsContext) {
Inseob Kim74d25562020-08-04 00:41:38 +09001787 cfiStaticLibs(ctx.Config()).exportToMake(ctx)
Vishwath Mohane7128792017-11-17 11:08:10 -08001788}
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -07001789
1790func hwasanMakeVarsProvider(ctx android.MakeVarsContext) {
Inseob Kim74d25562020-08-04 00:41:38 +09001791 hwasanStaticLibs(ctx.Config()).exportToMake(ctx)
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -07001792}
Trevor Radcliffe4f95ee92023-01-19 16:02:47 +00001793
1794func BazelCcSanitizerToolchainVars(config android.Config) string {
1795 return android.BazelToolchainVars(config, exportedVars)
1796}