blob: f39781b315554e5a90b0bd8964c47d9696780bd8 [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",
Mitch Phillips59760562022-03-22 18:33:44 +000079 "export_memory_stats=0", "max_malloc_fill_size=4096", "malloc_fill_byte=0"}
Florian Mayerd8434a42022-08-31 20:57:03 +000080 memtagStackCommonFlags = []string{"-march=armv8-a+memtag"}
Dan Willemsencbceaab2016-10-13 16:44:07 -070081)
82
Ivan Lozano3968d8f2020-12-14 11:27:52 -050083type SanitizerType int
Colin Cross16b23492016-01-06 14:41:07 -080084
Colin Cross16b23492016-01-06 14:41:07 -080085const (
Ivan Lozano3968d8f2020-12-14 11:27:52 -050086 Asan SanitizerType = iota + 1
Tri Vo6eafc362021-04-01 11:29:09 -070087 Hwasan
Colin Cross16b23492016-01-06 14:41:07 -080088 tsan
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -070089 intOverflow
Peter Collingbourne8c7e6e22018-11-19 16:03:58 -080090 scs
Ivan Lozano3968d8f2020-12-14 11:27:52 -050091 Fuzzer
Ivan Lozano62cd0382021-11-01 10:27:54 -040092 Memtag_heap
Florian Mayerd8434a42022-08-31 20:57:03 +000093 Memtag_stack
Liz Kammer75db9312021-07-07 16:41:50 -040094 cfi // cfi is last to prevent it running before incompatible mutators
Colin Cross16b23492016-01-06 14:41:07 -080095)
96
Liz Kammer75db9312021-07-07 16:41:50 -040097var Sanitizers = []SanitizerType{
98 Asan,
99 Hwasan,
100 tsan,
101 intOverflow,
102 scs,
103 Fuzzer,
Ivan Lozano62cd0382021-11-01 10:27:54 -0400104 Memtag_heap,
Florian Mayerd8434a42022-08-31 20:57:03 +0000105 Memtag_stack,
Liz Kammer75db9312021-07-07 16:41:50 -0400106 cfi, // cfi is last to prevent it running before incompatible mutators
107}
108
Jiyong Park82226632019-02-01 10:50:50 +0900109// Name of the sanitizer variation for this sanitizer type
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500110func (t SanitizerType) variationName() string {
Colin Cross16b23492016-01-06 14:41:07 -0800111 switch t {
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500112 case Asan:
Colin Cross16b23492016-01-06 14:41:07 -0800113 return "asan"
Tri Vo6eafc362021-04-01 11:29:09 -0700114 case Hwasan:
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700115 return "hwasan"
Colin Cross16b23492016-01-06 14:41:07 -0800116 case tsan:
117 return "tsan"
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700118 case intOverflow:
119 return "intOverflow"
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000120 case cfi:
121 return "cfi"
Peter Collingbourne8c7e6e22018-11-19 16:03:58 -0800122 case scs:
123 return "scs"
Ivan Lozano62cd0382021-11-01 10:27:54 -0400124 case Memtag_heap:
Evgenii Stepanov193ac2e2020-04-28 15:09:12 -0700125 return "memtag_heap"
Florian Mayerd8434a42022-08-31 20:57:03 +0000126 case Memtag_stack:
127 return "memtag_stack"
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500128 case Fuzzer:
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700129 return "fuzzer"
Colin Cross16b23492016-01-06 14:41:07 -0800130 default:
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500131 panic(fmt.Errorf("unknown SanitizerType %d", t))
Colin Cross16b23492016-01-06 14:41:07 -0800132 }
133}
134
Jiyong Park82226632019-02-01 10:50:50 +0900135// This is the sanitizer names in SANITIZE_[TARGET|HOST]
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500136func (t SanitizerType) name() string {
Jiyong Park82226632019-02-01 10:50:50 +0900137 switch t {
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500138 case Asan:
Jiyong Park82226632019-02-01 10:50:50 +0900139 return "address"
Tri Vo6eafc362021-04-01 11:29:09 -0700140 case Hwasan:
Jiyong Park82226632019-02-01 10:50:50 +0900141 return "hwaddress"
Ivan Lozano62cd0382021-11-01 10:27:54 -0400142 case Memtag_heap:
Evgenii Stepanov193ac2e2020-04-28 15:09:12 -0700143 return "memtag_heap"
Florian Mayerd8434a42022-08-31 20:57:03 +0000144 case Memtag_stack:
145 return "memtag_stack"
Jiyong Park82226632019-02-01 10:50:50 +0900146 case tsan:
147 return "thread"
148 case intOverflow:
149 return "integer_overflow"
150 case cfi:
151 return "cfi"
152 case scs:
153 return "shadow-call-stack"
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500154 case Fuzzer:
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700155 return "fuzzer"
Jiyong Park82226632019-02-01 10:50:50 +0900156 default:
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500157 panic(fmt.Errorf("unknown SanitizerType %d", t))
Jiyong Park82226632019-02-01 10:50:50 +0900158 }
159}
160
Liz Kammer75db9312021-07-07 16:41:50 -0400161func (t SanitizerType) registerMutators(ctx android.RegisterMutatorsContext) {
162 switch t {
Lukacs T. Berki6c716762022-06-13 20:50:39 +0200163 case cfi, Hwasan, Asan, tsan, Fuzzer, scs:
164 sanitizer := &sanitizerSplitMutator{t}
165 ctx.TopDown(t.variationName()+"_markapexes", sanitizer.markSanitizableApexesMutator)
166 ctx.Transition(t.variationName(), sanitizer)
Florian Mayerd8434a42022-08-31 20:57:03 +0000167 case Memtag_heap, Memtag_stack, intOverflow:
Liz Kammer75db9312021-07-07 16:41:50 -0400168 // do nothing
169 default:
170 panic(fmt.Errorf("unknown SanitizerType %d", t))
171 }
172}
173
Liz Kammerfd8a49f2022-10-31 10:31:11 -0400174// shouldPropagateToSharedLibraryDeps returns whether a sanitizer type should propagate to share
175// dependencies. In most cases, sanitizers only propagate to static dependencies; however, some
176// sanitizers also must be enabled for shared libraries for linking.
177func (t SanitizerType) shouldPropagateToSharedLibraryDeps() bool {
178 switch t {
179 case Fuzzer:
180 // Typically, shared libs are not split. However, for fuzzer, we split even for shared libs
181 // because a library sanitized for fuzzer can't be linked from a library that isn't sanitized
182 // for fuzzer.
183 return true
184 default:
185 return false
186 }
187}
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500188func (*Module) SanitizerSupported(t SanitizerType) bool {
189 switch t {
190 case Asan:
191 return true
Tri Vo6eafc362021-04-01 11:29:09 -0700192 case Hwasan:
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500193 return true
194 case tsan:
195 return true
196 case intOverflow:
197 return true
198 case cfi:
199 return true
200 case scs:
201 return true
202 case Fuzzer:
203 return true
Ivan Lozano62cd0382021-11-01 10:27:54 -0400204 case Memtag_heap:
205 return true
Florian Mayerd8434a42022-08-31 20:57:03 +0000206 case Memtag_stack:
207 return true
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500208 default:
209 return false
210 }
211}
212
213// incompatibleWithCfi returns true if a sanitizer is incompatible with CFI.
214func (t SanitizerType) incompatibleWithCfi() bool {
Tri Vo6eafc362021-04-01 11:29:09 -0700215 return t == Asan || t == Fuzzer || t == Hwasan
Jiyong Park1d1119f2019-07-29 21:27:18 +0900216}
217
Martin Stjernholmb0249572020-09-15 02:32:35 +0100218type SanitizeUserProps struct {
Liz Kammer75b9b402021-06-25 15:19:27 -0400219 // Prevent use of any sanitizers on this module
Martin Stjernholmb0249572020-09-15 02:32:35 +0100220 Never *bool `android:"arch_variant"`
Colin Cross16b23492016-01-06 14:41:07 -0800221
Liz Kammer75b9b402021-06-25 15:19:27 -0400222 // ASan (Address sanitizer), incompatible with static binaries.
223 // Always runs in a diagnostic mode.
224 // Use of address sanitizer disables cfi sanitizer.
225 // Hwaddress sanitizer takes precedence over this sanitizer.
226 Address *bool `android:"arch_variant"`
227 // TSan (Thread sanitizer), incompatible with static binaries and 32 bit architectures.
228 // Always runs in a diagnostic mode.
229 // Use of thread sanitizer disables cfi and scudo sanitizers.
230 // Hwaddress sanitizer takes precedence over this sanitizer.
231 Thread *bool `android:"arch_variant"`
232 // HWASan (Hardware Address sanitizer).
233 // Use of hwasan sanitizer disables cfi, address, thread, and scudo sanitizers.
Martin Stjernholmb0249572020-09-15 02:32:35 +0100234 Hwaddress *bool `android:"arch_variant"`
Colin Cross16b23492016-01-06 14:41:07 -0800235
Liz Kammer75b9b402021-06-25 15:19:27 -0400236 // Undefined behavior sanitizer
237 All_undefined *bool `android:"arch_variant"`
238 // Subset of undefined behavior sanitizer
239 Undefined *bool `android:"arch_variant"`
240 // List of specific undefined behavior sanitizers to enable
241 Misc_undefined []string `android:"arch_variant"`
242 // Fuzzer, incompatible with static binaries.
243 Fuzzer *bool `android:"arch_variant"`
244 // safe-stack sanitizer, incompatible with 32-bit architectures.
245 Safestack *bool `android:"arch_variant"`
246 // cfi sanitizer, incompatible with asan, hwasan, fuzzer, or Darwin
247 Cfi *bool `android:"arch_variant"`
248 // signed/unsigned integer overflow sanitizer, incompatible with Darwin.
249 Integer_overflow *bool `android:"arch_variant"`
250 // scudo sanitizer, incompatible with asan, hwasan, tsan
251 // This should not be used in Android 11+ : https://source.android.com/devices/tech/debug/scudo
252 // deprecated
253 Scudo *bool `android:"arch_variant"`
254 // shadow-call-stack sanitizer, only available on arm64
255 Scs *bool `android:"arch_variant"`
256 // Memory-tagging, only available on arm64
257 // if diag.memtag unset or false, enables async memory tagging
Florian Mayer00ab5cf2022-08-31 18:30:18 +0000258 Memtag_heap *bool `android:"arch_variant"`
Florian Mayerd8434a42022-08-31 20:57:03 +0000259 // Memory-tagging stack instrumentation, only available on arm64
260 // Adds instrumentation to detect stack buffer overflows and use-after-scope using MTE.
261 Memtag_stack *bool `android:"arch_variant"`
Martin Stjernholmb0249572020-09-15 02:32:35 +0100262
263 // A modifier for ASAN and HWASAN for write only instrumentation
264 Writeonly *bool `android:"arch_variant"`
265
266 // Sanitizers to run in the diagnostic mode (as opposed to the release mode).
267 // Replaces abort() on error with a human-readable error message.
268 // Address and Thread sanitizers always run in diagnostic mode.
269 Diag struct {
Liz Kammer75b9b402021-06-25 15:19:27 -0400270 // Undefined behavior sanitizer, diagnostic mode
271 Undefined *bool `android:"arch_variant"`
272 // cfi sanitizer, diagnostic mode, incompatible with asan, hwasan, fuzzer, or Darwin
273 Cfi *bool `android:"arch_variant"`
274 // signed/unsigned integer overflow sanitizer, diagnostic mode, incompatible with Darwin.
275 Integer_overflow *bool `android:"arch_variant"`
276 // Memory-tagging, only available on arm64
277 // requires sanitizer.memtag: true
278 // if set, enables sync memory tagging
279 Memtag_heap *bool `android:"arch_variant"`
280 // List of specific undefined behavior sanitizers to enable in diagnostic mode
281 Misc_undefined []string `android:"arch_variant"`
282 // List of sanitizers to pass to -fno-sanitize-recover
283 // results in only the first detected error for these sanitizers being reported and program then
284 // exits with a non-zero exit code.
285 No_recover []string `android:"arch_variant"`
Cindy Zhoud3fe4922020-12-01 11:14:30 -0800286 } `android:"arch_variant"`
Colin Cross16b23492016-01-06 14:41:07 -0800287
Cindy Zhou8cd45de2020-11-16 08:41:00 -0800288 // Sanitizers to run with flag configuration specified
289 Config struct {
290 // Enables CFI support flags for assembly-heavy libraries
291 Cfi_assembly_support *bool `android:"arch_variant"`
Cindy Zhoud3fe4922020-12-01 11:14:30 -0800292 } `android:"arch_variant"`
Cindy Zhou8cd45de2020-11-16 08:41:00 -0800293
Liz Kammer75b9b402021-06-25 15:19:27 -0400294 // List of sanitizers to pass to -fsanitize-recover
295 // allows execution to continue for these sanitizers to detect multiple errors rather than only
296 // the first one
Martin Stjernholmb0249572020-09-15 02:32:35 +0100297 Recover []string
Jasraj Bedibb4511d2020-07-23 22:58:17 +0000298
Pirama Arumuga Nainar582fc2d2021-08-27 15:12:56 -0700299 // value to pass to -fsanitize-ignorelist
Martin Stjernholmb0249572020-09-15 02:32:35 +0100300 Blocklist *string
301}
Evgenii Stepanov1e405e12016-08-16 15:39:54 -0700302
Martin Stjernholmb0249572020-09-15 02:32:35 +0100303type SanitizeProperties struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +0100304 Sanitize SanitizeUserProps `android:"arch_variant"`
305 SanitizerEnabled bool `blueprint:"mutated"`
Martin Stjernholmb0249572020-09-15 02:32:35 +0100306 MinimalRuntimeDep bool `blueprint:"mutated"`
307 BuiltinsDep bool `blueprint:"mutated"`
308 UbsanRuntimeDep bool `blueprint:"mutated"`
309 InSanitizerDir bool `blueprint:"mutated"`
310 Sanitizers []string `blueprint:"mutated"`
311 DiagSanitizers []string `blueprint:"mutated"`
Colin Cross16b23492016-01-06 14:41:07 -0800312}
313
314type sanitize struct {
315 Properties SanitizeProperties
316}
317
Cindy Zhou18417cb2020-12-10 07:12:38 -0800318// Mark this tag with a check to see if apex dependency check should be skipped
319func (t libraryDependencyTag) SkipApexAllowedDependenciesCheck() bool {
320 return t.skipApexAllowedDependenciesCheck
321}
322
323var _ android.SkipApexAllowedDependenciesCheck = (*libraryDependencyTag)(nil)
324
Vishwath Mohane7128792017-11-17 11:08:10 -0800325func init() {
326 android.RegisterMakeVarsProvider(pctx, cfiMakeVarsProvider)
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700327 android.RegisterMakeVarsProvider(pctx, hwasanMakeVarsProvider)
Vishwath Mohane7128792017-11-17 11:08:10 -0800328}
329
Colin Cross16b23492016-01-06 14:41:07 -0800330func (sanitize *sanitize) props() []interface{} {
331 return []interface{}{&sanitize.Properties}
332}
333
334func (sanitize *sanitize) begin(ctx BaseModuleContext) {
Evgenii Stepanovfcfe56d2016-07-07 10:54:07 -0700335 s := &sanitize.Properties.Sanitize
336
Colin Cross16b23492016-01-06 14:41:07 -0800337 // Don't apply sanitizers to NDK code.
Jeff Gastonaf3cc2d2017-09-27 17:01:44 -0700338 if ctx.useSdk() {
Nan Zhang0007d812017-11-07 10:57:05 -0800339 s.Never = BoolPtr(true)
Colin Cross16b23492016-01-06 14:41:07 -0800340 }
341
342 // Never always wins.
Nan Zhang0007d812017-11-07 10:57:05 -0800343 if Bool(s.Never) {
Colin Cross16b23492016-01-06 14:41:07 -0800344 return
345 }
346
Florian Mayerd8434a42022-08-31 20:57:03 +0000347 // cc_test targets default to SYNC MemTag unless explicitly set to ASYNC (via diag: {memtag_heap: false}).
Liz Kammer7b920b42021-06-22 16:57:27 -0400348 if ctx.testBinary() {
349 if s.Memtag_heap == nil {
350 s.Memtag_heap = proptools.BoolPtr(true)
351 }
352 if s.Diag.Memtag_heap == nil {
353 s.Diag.Memtag_heap = proptools.BoolPtr(true)
354 }
Evgenii Stepanov04896ca2021-01-12 18:28:33 -0800355 }
356
Colin Cross16b23492016-01-06 14:41:07 -0800357 var globalSanitizers []string
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700358 var globalSanitizersDiag []string
359
Dan Willemsen8536d6b2018-10-07 20:54:34 -0700360 if ctx.Host() {
361 if !ctx.Windows() {
362 globalSanitizers = ctx.Config().SanitizeHost()
363 }
364 } else {
365 arches := ctx.Config().SanitizeDeviceArch()
366 if len(arches) == 0 || inList(ctx.Arch().ArchType.Name, arches) {
367 globalSanitizers = ctx.Config().SanitizeDevice()
368 globalSanitizersDiag = ctx.Config().SanitizeDeviceDiag()
Colin Cross16b23492016-01-06 14:41:07 -0800369 }
370 }
371
Colin Cross16b23492016-01-06 14:41:07 -0800372 if len(globalSanitizers) > 0 {
Evgenii Stepanov05bafd32016-07-07 17:38:41 +0000373 var found bool
Evgenii Stepanovfcfe56d2016-07-07 10:54:07 -0700374 if found, globalSanitizers = removeFromList("undefined", globalSanitizers); found && s.All_undefined == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400375 s.All_undefined = proptools.BoolPtr(true)
Evgenii Stepanov05bafd32016-07-07 17:38:41 +0000376 }
Colin Cross16b23492016-01-06 14:41:07 -0800377
Evgenii Stepanovfcfe56d2016-07-07 10:54:07 -0700378 if found, globalSanitizers = removeFromList("default-ub", globalSanitizers); found && s.Undefined == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400379 s.Undefined = proptools.BoolPtr(true)
Evgenii Stepanov05bafd32016-07-07 17:38:41 +0000380 }
381
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700382 if found, globalSanitizers = removeFromList("address", globalSanitizers); found && s.Address == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400383 s.Address = proptools.BoolPtr(true)
Evgenii Stepanov05bafd32016-07-07 17:38:41 +0000384 }
385
Evgenii Stepanovfcfe56d2016-07-07 10:54:07 -0700386 if found, globalSanitizers = removeFromList("thread", globalSanitizers); found && s.Thread == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400387 s.Thread = proptools.BoolPtr(true)
Evgenii Stepanov05bafd32016-07-07 17:38:41 +0000388 }
389
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700390 if found, globalSanitizers = removeFromList("fuzzer", globalSanitizers); found && s.Fuzzer == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400391 s.Fuzzer = proptools.BoolPtr(true)
Evgenii Stepanovfcfe56d2016-07-07 10:54:07 -0700392 }
393
394 if found, globalSanitizers = removeFromList("safe-stack", globalSanitizers); found && s.Safestack == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400395 s.Safestack = proptools.BoolPtr(true)
Evgenii Stepanov05bafd32016-07-07 17:38:41 +0000396 }
397
Evgenii Stepanov1e405e12016-08-16 15:39:54 -0700398 if found, globalSanitizers = removeFromList("cfi", globalSanitizers); found && s.Cfi == nil {
Colin Cross6510f912017-11-29 00:27:14 -0800399 if !ctx.Config().CFIDisabledForPath(ctx.ModuleDir()) {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400400 s.Cfi = proptools.BoolPtr(true)
Vishwath Mohan1fa3ac52017-10-31 02:26:14 -0700401 }
Evgenii Stepanov1e405e12016-08-16 15:39:54 -0700402 }
403
Ivan Lozanoa9255a82018-03-13 10:41:07 -0700404 // Global integer_overflow builds do not support static libraries.
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700405 if found, globalSanitizers = removeFromList("integer_overflow", globalSanitizers); found && s.Integer_overflow == nil {
Ivan Lozanoa9255a82018-03-13 10:41:07 -0700406 if !ctx.Config().IntegerOverflowDisabledForPath(ctx.ModuleDir()) && !ctx.static() {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400407 s.Integer_overflow = proptools.BoolPtr(true)
Ivan Lozano5f595532017-07-13 14:46:05 -0700408 }
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700409 }
410
Kostya Kortchinskyd18ae5c2018-06-12 14:46:54 -0700411 if found, globalSanitizers = removeFromList("scudo", globalSanitizers); found && s.Scudo == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400412 s.Scudo = proptools.BoolPtr(true)
Kostya Kortchinskyd18ae5c2018-06-12 14:46:54 -0700413 }
414
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700415 if found, globalSanitizers = removeFromList("hwaddress", globalSanitizers); found && s.Hwaddress == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400416 s.Hwaddress = proptools.BoolPtr(true)
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700417 }
418
Jasraj Bedibb4511d2020-07-23 22:58:17 +0000419 if found, globalSanitizers = removeFromList("writeonly", globalSanitizers); found && s.Writeonly == nil {
420 // Hwaddress and Address are set before, so we can check them here
421 // If they aren't explicitly set in the blueprint/SANITIZE_(HOST|TARGET), they would be nil instead of false
422 if s.Address == nil && s.Hwaddress == nil {
423 ctx.ModuleErrorf("writeonly modifier cannot be used without 'address' or 'hwaddress'")
424 }
Liz Kammerb2fc4702021-06-25 14:53:40 -0400425 s.Writeonly = proptools.BoolPtr(true)
Jasraj Bedibb4511d2020-07-23 22:58:17 +0000426 }
Evgenii Stepanov193ac2e2020-04-28 15:09:12 -0700427 if found, globalSanitizers = removeFromList("memtag_heap", globalSanitizers); found && s.Memtag_heap == nil {
Evgenii Stepanov4beaa0c2021-01-05 16:41:26 -0800428 if !ctx.Config().MemtagHeapDisabledForPath(ctx.ModuleDir()) {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400429 s.Memtag_heap = proptools.BoolPtr(true)
Evgenii Stepanov4beaa0c2021-01-05 16:41:26 -0800430 }
Evgenii Stepanov193ac2e2020-04-28 15:09:12 -0700431 }
Jasraj Bedibb4511d2020-07-23 22:58:17 +0000432
Florian Mayerd8434a42022-08-31 20:57:03 +0000433 if found, globalSanitizers = removeFromList("memtag_stack", globalSanitizers); found && s.Memtag_stack == nil {
434 s.Memtag_stack = proptools.BoolPtr(true)
435 }
436
Evgenii Stepanov05bafd32016-07-07 17:38:41 +0000437 if len(globalSanitizers) > 0 {
438 ctx.ModuleErrorf("unknown global sanitizer option %s", globalSanitizers[0])
439 }
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700440
Ivan Lozanoa9255a82018-03-13 10:41:07 -0700441 // Global integer_overflow builds do not support static library diagnostics.
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700442 if found, globalSanitizersDiag = removeFromList("integer_overflow", globalSanitizersDiag); found &&
Ivan Lozanoa9255a82018-03-13 10:41:07 -0700443 s.Diag.Integer_overflow == nil && Bool(s.Integer_overflow) && !ctx.static() {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400444 s.Diag.Integer_overflow = proptools.BoolPtr(true)
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700445 }
446
Vishwath Mohan1fa3ac52017-10-31 02:26:14 -0700447 if found, globalSanitizersDiag = removeFromList("cfi", globalSanitizersDiag); found &&
448 s.Diag.Cfi == nil && Bool(s.Cfi) {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400449 s.Diag.Cfi = proptools.BoolPtr(true)
Vishwath Mohan1fa3ac52017-10-31 02:26:14 -0700450 }
451
Evgenii Stepanov04896ca2021-01-12 18:28:33 -0800452 if found, globalSanitizersDiag = removeFromList("memtag_heap", globalSanitizersDiag); found &&
453 s.Diag.Memtag_heap == nil && Bool(s.Memtag_heap) {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400454 s.Diag.Memtag_heap = proptools.BoolPtr(true)
Evgenii Stepanov04896ca2021-01-12 18:28:33 -0800455 }
456
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700457 if len(globalSanitizersDiag) > 0 {
458 ctx.ModuleErrorf("unknown global sanitizer diagnostics option %s", globalSanitizersDiag[0])
459 }
Evgenii Stepanovfcfe56d2016-07-07 10:54:07 -0700460 }
Colin Cross3c344ef2016-07-18 15:44:56 -0700461
Evgenii Stepanov4beaa0c2021-01-05 16:41:26 -0800462 // Enable Memtag for all components in the include paths (for Aarch64 only)
Colin Cross88a029f2022-06-23 14:51:20 -0700463 if ctx.Arch().ArchType == android.Arm64 && ctx.toolchain().Bionic() {
Evgenii Stepanov4beaa0c2021-01-05 16:41:26 -0800464 if ctx.Config().MemtagHeapSyncEnabledForPath(ctx.ModuleDir()) {
Evgenii Stepanov04896ca2021-01-12 18:28:33 -0800465 if s.Memtag_heap == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400466 s.Memtag_heap = proptools.BoolPtr(true)
Evgenii Stepanov04896ca2021-01-12 18:28:33 -0800467 }
468 if s.Diag.Memtag_heap == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400469 s.Diag.Memtag_heap = proptools.BoolPtr(true)
Evgenii Stepanov04896ca2021-01-12 18:28:33 -0800470 }
Evgenii Stepanov4beaa0c2021-01-05 16:41:26 -0800471 } else if ctx.Config().MemtagHeapAsyncEnabledForPath(ctx.ModuleDir()) {
Evgenii Stepanov04896ca2021-01-12 18:28:33 -0800472 if s.Memtag_heap == nil {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400473 s.Memtag_heap = proptools.BoolPtr(true)
Evgenii Stepanov04896ca2021-01-12 18:28:33 -0800474 }
Evgenii Stepanov4beaa0c2021-01-05 16:41:26 -0800475 }
Evgenii Stepanov193ac2e2020-04-28 15:09:12 -0700476 }
477
Elvis Chien9c993542021-06-25 01:15:17 +0800478 // Enable CFI for non-host components in the include paths
479 if s.Cfi == nil && ctx.Config().CFIEnabledForPath(ctx.ModuleDir()) && !ctx.Host() {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400480 s.Cfi = proptools.BoolPtr(true)
Vishwath Mohan3af8ee02018-03-30 02:55:23 +0000481 if inList("cfi", ctx.Config().SanitizeDeviceDiag()) {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400482 s.Diag.Cfi = proptools.BoolPtr(true)
Vishwath Mohan1fa3ac52017-10-31 02:26:14 -0700483 }
484 }
485
Elliott Hughesda3a0712020-03-06 16:55:28 -0800486 // Is CFI actually enabled?
487 if !ctx.Config().EnableCFI() {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400488 s.Cfi = nil
489 s.Diag.Cfi = nil
Vishwath Mohan1b017a72017-01-19 13:54:55 -0800490 }
491
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700492 // HWASan requires AArch64 hardware feature (top-byte-ignore).
Colin Cross88a029f2022-06-23 14:51:20 -0700493 if ctx.Arch().ArchType != android.Arm64 || !ctx.toolchain().Bionic() {
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700494 s.Hwaddress = nil
495 }
496
Peter Collingbourne8c7e6e22018-11-19 16:03:58 -0800497 // SCS is only implemented on AArch64.
Colin Cross88a029f2022-06-23 14:51:20 -0700498 if ctx.Arch().ArchType != android.Arm64 || !ctx.toolchain().Bionic() {
Peter Collingbourne8c7e6e22018-11-19 16:03:58 -0800499 s.Scs = nil
500 }
501
Ivan Lozano62cd0382021-11-01 10:27:54 -0400502 // Memtag_heap is only implemented on AArch64.
Florian Mayerd8434a42022-08-31 20:57:03 +0000503 // Memtag ABI is Android specific for now, so disable for host.
504 if ctx.Arch().ArchType != android.Arm64 || !ctx.toolchain().Bionic() || ctx.Host() {
Evgenii Stepanov193ac2e2020-04-28 15:09:12 -0700505 s.Memtag_heap = nil
Florian Mayerd8434a42022-08-31 20:57:03 +0000506 s.Memtag_stack = nil
Evgenii Stepanov193ac2e2020-04-28 15:09:12 -0700507 }
508
Vishwath Mohan8f4fdd82017-04-20 07:42:52 -0700509 // Also disable CFI if ASAN is enabled.
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700510 if Bool(s.Address) || Bool(s.Hwaddress) {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400511 s.Cfi = nil
512 s.Diag.Cfi = nil
Florian Mayerd8434a42022-08-31 20:57:03 +0000513 // HWASAN and ASAN win against MTE.
514 s.Memtag_heap = nil
515 s.Memtag_stack = nil
Vishwath Mohan8f4fdd82017-04-20 07:42:52 -0700516 }
517
Colin Crossed12a042022-02-07 13:55:55 -0800518 // Disable sanitizers that depend on the UBSan runtime for windows/darwin builds.
519 if !ctx.Os().Linux() {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400520 s.Cfi = nil
521 s.Diag.Cfi = nil
Ivan Lozanoa9255a82018-03-13 10:41:07 -0700522 s.Misc_undefined = nil
523 s.Undefined = nil
524 s.All_undefined = nil
525 s.Integer_overflow = nil
Vishwath Mohane7128792017-11-17 11:08:10 -0800526 }
527
Colin Cross2c435a02022-10-20 13:55:53 -0700528 // TODO(b/254713216): CFI doesn't work for riscv64 yet because LTO doesn't work.
Colin Crossecf4e662022-10-20 13:59:17 -0700529 if ctx.Arch().ArchType == android.Riscv64 {
530 s.Cfi = nil
531 s.Diag.Cfi = nil
532 }
533
Colin Crossed12a042022-02-07 13:55:55 -0800534 // Disable CFI for musl
535 if ctx.toolchain().Musl() {
536 s.Cfi = nil
537 s.Diag.Cfi = nil
538 }
539
Vishwath Mohan9ccbba02018-05-28 13:54:48 -0700540 // Also disable CFI for VNDK variants of components
541 if ctx.isVndk() && ctx.useVndk() {
Inseob Kimc42f2f22020-07-29 20:32:10 +0900542 if ctx.static() {
543 // Cfi variant for static vndk should be captured as vendor snapshot,
544 // so don't strictly disable Cfi.
545 s.Cfi = nil
546 s.Diag.Cfi = nil
547 } else {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400548 s.Cfi = nil
549 s.Diag.Cfi = nil
Inseob Kimc42f2f22020-07-29 20:32:10 +0900550 }
Inseob Kimeec88e12020-01-22 11:11:29 +0900551 }
552
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700553 // HWASan ramdisk (which is built from recovery) goes over some bootloader limit.
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700554 // Keep libc instrumented so that ramdisk / vendor_ramdisk / recovery can run hwasan-instrumented code if necessary.
555 if (ctx.inRamdisk() || ctx.inVendorRamdisk() || ctx.inRecovery()) && !strings.HasPrefix(ctx.ModuleDir(), "bionic/libc") {
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700556 s.Hwaddress = nil
557 }
558
Colin Cross3c344ef2016-07-18 15:44:56 -0700559 if ctx.staticBinary() {
560 s.Address = nil
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700561 s.Fuzzer = nil
Colin Cross3c344ef2016-07-18 15:44:56 -0700562 s.Thread = nil
Colin Cross16b23492016-01-06 14:41:07 -0800563 }
564
Evgenii Stepanovfcfe56d2016-07-07 10:54:07 -0700565 if Bool(s.All_undefined) {
566 s.Undefined = nil
567 }
568
Evgenii Stepanov0a8a0d02016-05-12 13:54:53 -0700569 if !ctx.toolchain().Is64Bit() {
570 // TSAN and SafeStack are not supported on 32-bit architectures
Evgenii Stepanovfcfe56d2016-07-07 10:54:07 -0700571 s.Thread = nil
572 s.Safestack = nil
Colin Cross16b23492016-01-06 14:41:07 -0800573 // TODO(ccross): error for compile_multilib = "32"?
574 }
575
Evgenii Stepanov76cee232017-01-27 15:44:44 -0800576 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 -0700577 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 +0000578 Bool(s.Scudo) || Bool(s.Hwaddress) || Bool(s.Scs) || Bool(s.Memtag_heap) || Bool(s.Memtag_stack)) {
Colin Cross3c344ef2016-07-18 15:44:56 -0700579 sanitize.Properties.SanitizerEnabled = true
580 }
581
Kostya Kortchinskyd5275c82019-02-01 08:42:56 -0800582 // Disable Scudo if ASan or TSan is enabled, or if it's disabled globally.
583 if Bool(s.Address) || Bool(s.Thread) || Bool(s.Hwaddress) || ctx.Config().DisableScudo() {
Kostya Kortchinskyd18ae5c2018-06-12 14:46:54 -0700584 s.Scudo = nil
585 }
586
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700587 if Bool(s.Hwaddress) {
588 s.Address = nil
589 s.Thread = nil
590 }
Mitch Phillips5007c4a2022-03-02 01:25:22 +0000591
592 // TODO(b/131771163): CFI transiently depends on LTO, and thus Fuzzer is
593 // mutually incompatible.
594 if Bool(s.Fuzzer) {
595 s.Cfi = nil
596 }
Colin Cross16b23492016-01-06 14:41:07 -0800597}
598
Chih-Hung Hsieh3567e622018-11-15 14:01:36 -0800599func toDisableImplicitIntegerChange(flags []string) bool {
600 // Returns true if any flag is fsanitize*integer, and there is
601 // no explicit flag about sanitize=implicit-integer-sign-change.
602 for _, f := range flags {
603 if strings.Contains(f, "sanitize=implicit-integer-sign-change") {
604 return false
605 }
606 }
607 for _, f := range flags {
608 if strings.HasPrefix(f, "-fsanitize") && strings.Contains(f, "integer") {
609 return true
610 }
611 }
612 return false
613}
614
Yabin Cuidb7dda82020-11-30 15:47:45 -0800615func toDisableUnsignedShiftBaseChange(flags []string) bool {
616 // Returns true if any flag is fsanitize*integer, and there is
617 // no explicit flag about sanitize=unsigned-shift-base.
618 for _, f := range flags {
619 if strings.Contains(f, "sanitize=unsigned-shift-base") {
620 return false
621 }
622 }
623 for _, f := range flags {
624 if strings.HasPrefix(f, "-fsanitize") && strings.Contains(f, "integer") {
625 return true
626 }
627 }
628 return false
629}
630
Colin Cross16b23492016-01-06 14:41:07 -0800631func (sanitize *sanitize) flags(ctx ModuleContext, flags Flags) Flags {
Ivan Lozanoa9255a82018-03-13 10:41:07 -0700632 if !sanitize.Properties.SanitizerEnabled && !sanitize.Properties.UbsanRuntimeDep {
Colin Cross16b23492016-01-06 14:41:07 -0800633 return flags
634 }
635
Florian Mayer7410d282022-10-19 14:06:26 -0700636 // Currently unwinding through tagged frames for exceptions is broken, so disable memtag stack
637 // in that case, so we don't end up tagging those.
638 // TODO(b/174878242): Remove once https://r.android.com/2251926 is included in toolchain.
639 if android.InList("-fexceptions", flags.Local.CFlags) || android.InList("-fexceptions", flags.Global.CFlags) {
640 sanitize.Properties.Sanitize.Memtag_stack = nil
641 _, sanitize.Properties.Sanitizers = android.RemoveFromList("memtag-stack", sanitize.Properties.Sanitizers)
642 }
643
Evgenii Stepanovfcfe56d2016-07-07 10:54:07 -0700644 if Bool(sanitize.Properties.Sanitize.Address) {
Colin Cross635c3b02016-05-18 15:37:25 -0700645 if ctx.Arch().ArchType == android.Arm {
Colin Cross16b23492016-01-06 14:41:07 -0800646 // Frame pointer based unwinder in ASan requires ARM frame setup.
647 // TODO: put in flags?
648 flags.RequiredInstructionSet = "arm"
649 }
Colin Cross4af21ed2019-11-04 09:37:55 -0800650 flags.Local.CFlags = append(flags.Local.CFlags, asanCflags...)
651 flags.Local.LdFlags = append(flags.Local.LdFlags, asanLdflags...)
Colin Cross16b23492016-01-06 14:41:07 -0800652
Jasraj Bedibb4511d2020-07-23 22:58:17 +0000653 if Bool(sanitize.Properties.Sanitize.Writeonly) {
654 flags.Local.CFlags = append(flags.Local.CFlags, "-mllvm", "-asan-instrument-reads=0")
655 }
656
Colin Cross16b23492016-01-06 14:41:07 -0800657 if ctx.Host() {
658 // -nodefaultlibs (provided with libc++) prevents the driver from linking
659 // libraries needed with -fsanitize=address. http://b/18650275 (WAI)
Colin Cross4af21ed2019-11-04 09:37:55 -0800660 flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,--no-as-needed")
Colin Cross16b23492016-01-06 14:41:07 -0800661 } else {
Colin Cross4af21ed2019-11-04 09:37:55 -0800662 flags.Local.CFlags = append(flags.Local.CFlags, "-mllvm", "-asan-globals=0")
Jiyong Parka2aca282019-02-02 13:13:38 +0900663 if ctx.bootstrap() {
664 flags.DynamicLinker = "/system/bin/bootstrap/linker_asan"
665 } else {
666 flags.DynamicLinker = "/system/bin/linker_asan"
667 }
Colin Cross16b23492016-01-06 14:41:07 -0800668 if flags.Toolchain.Is64Bit() {
669 flags.DynamicLinker += "64"
670 }
671 }
Colin Cross16b23492016-01-06 14:41:07 -0800672 }
673
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700674 if Bool(sanitize.Properties.Sanitize.Hwaddress) {
Colin Cross4af21ed2019-11-04 09:37:55 -0800675 flags.Local.CFlags = append(flags.Local.CFlags, hwasanCflags...)
Yi Kong286abc62021-11-04 16:14:14 +0800676
677 for _, flag := range hwasanCommonflags {
678 flags.Local.CFlags = append(flags.Local.CFlags, "-mllvm", flag)
679 }
680 for _, flag := range hwasanCommonflags {
681 flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,-mllvm,"+flag)
682 }
683
Jasraj Bedibb4511d2020-07-23 22:58:17 +0000684 if Bool(sanitize.Properties.Sanitize.Writeonly) {
685 flags.Local.CFlags = append(flags.Local.CFlags, "-mllvm", "-hwasan-instrument-reads=0")
686 }
Yabin Cui6be405e2017-10-19 15:52:11 -0700687 }
688
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700689 if Bool(sanitize.Properties.Sanitize.Fuzzer) {
Colin Cross4af21ed2019-11-04 09:37:55 -0800690 flags.Local.CFlags = append(flags.Local.CFlags, "-fsanitize=fuzzer-no-link")
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700691
Mitch Phillips5007c4a2022-03-02 01:25:22 +0000692 // TODO(b/131771163): LTO and Fuzzer support is mutually incompatible.
693 _, flags.Local.LdFlags = removeFromList("-flto", flags.Local.LdFlags)
694 _, flags.Local.CFlags = removeFromList("-flto", flags.Local.CFlags)
695 flags.Local.LdFlags = append(flags.Local.LdFlags, "-fno-lto")
696 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-lto")
697
Mitch Phillipsb8e593d2019-10-09 17:18:59 -0700698 // TODO(b/142430592): Upstream linker scripts for sanitizer runtime libraries
699 // discard the sancov_lowest_stack symbol, because it's emulated TLS (and thus
700 // doesn't match the linker script due to the "__emutls_v." prefix).
Colin Cross4af21ed2019-11-04 09:37:55 -0800701 flags.Local.LdFlags = append(flags.Local.LdFlags, "-fno-sanitize-coverage=stack-depth")
702 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-sanitize-coverage=stack-depth")
Mitch Phillipsb8e593d2019-10-09 17:18:59 -0700703
Mitch Phillipsb9b3e792019-08-28 12:41:07 -0700704 // Disable fortify for fuzzing builds. Generally, we'll be building with
705 // UBSan or ASan here and the fortify checks pollute the stack traces.
Colin Cross4af21ed2019-11-04 09:37:55 -0800706 flags.Local.CFlags = append(flags.Local.CFlags, "-U_FORTIFY_SOURCE")
Mitch Phillips734b4cb2019-12-10 08:44:52 -0800707
708 // Build fuzzer-sanitized libraries with an $ORIGIN DT_RUNPATH. Android's
709 // linker uses DT_RUNPATH, not DT_RPATH. When we deploy cc_fuzz targets and
710 // their libraries to /data/fuzz/<arch>/lib, any transient shared library gets
711 // the DT_RUNPATH from the shared library above it, and not the executable,
712 // meaning that the lookup falls back to the system. Adding the $ORIGIN to the
713 // DT_RUNPATH here means that transient shared libraries can be found
714 // colocated with their parents.
715 flags.Local.LdFlags = append(flags.Local.LdFlags, `-Wl,-rpath,\$$ORIGIN`)
Colin Cross16b23492016-01-06 14:41:07 -0800716 }
717
Evgenii Stepanov1e405e12016-08-16 15:39:54 -0700718 if Bool(sanitize.Properties.Sanitize.Cfi) {
Evgenii Stepanov7ebf9fa2017-01-20 14:13:06 -0800719 if ctx.Arch().ArchType == android.Arm {
720 // __cfi_check needs to be built as Thumb (see the code in linker_cfi.cpp). LLVM is not set up
721 // to do this on a function basis, so force Thumb on the entire module.
722 flags.RequiredInstructionSet = "thumb"
723 }
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000724
Colin Cross4af21ed2019-11-04 09:37:55 -0800725 flags.Local.CFlags = append(flags.Local.CFlags, cfiCflags...)
726 flags.Local.AsFlags = append(flags.Local.AsFlags, cfiAsflags...)
Cindy Zhou8cd45de2020-11-16 08:41:00 -0800727 if Bool(sanitize.Properties.Sanitize.Config.Cfi_assembly_support) {
728 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-sanitize-cfi-canonical-jump-tables")
729 }
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000730 // Only append the default visibility flag if -fvisibility has not already been set
731 // to hidden.
Colin Cross4af21ed2019-11-04 09:37:55 -0800732 if !inList("-fvisibility=hidden", flags.Local.CFlags) {
733 flags.Local.CFlags = append(flags.Local.CFlags, "-fvisibility=default")
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000734 }
Colin Cross4af21ed2019-11-04 09:37:55 -0800735 flags.Local.LdFlags = append(flags.Local.LdFlags, cfiLdflags...)
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000736
737 if ctx.staticBinary() {
Colin Cross4af21ed2019-11-04 09:37:55 -0800738 _, flags.Local.CFlags = removeFromList("-fsanitize-cfi-cross-dso", flags.Local.CFlags)
739 _, flags.Local.LdFlags = removeFromList("-fsanitize-cfi-cross-dso", flags.Local.LdFlags)
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000740 }
Evgenii Stepanov1e405e12016-08-16 15:39:54 -0700741 }
742
Florian Mayerd8434a42022-08-31 20:57:03 +0000743 if Bool(sanitize.Properties.Sanitize.Memtag_stack) {
744 flags.Local.CFlags = append(flags.Local.CFlags, memtagStackCommonFlags...)
Florian Mayer1e4f8992022-09-08 16:47:32 -0700745 // TODO(fmayer): remove -Wno-error once https://reviews.llvm.org/D127917 is in Android toolchain.
746 flags.Local.CFlags = append(flags.Local.CFlags, "-Wno-error=frame-larger-than")
Florian Mayerd8434a42022-08-31 20:57:03 +0000747 flags.Local.AsFlags = append(flags.Local.AsFlags, memtagStackCommonFlags...)
748 flags.Local.LdFlags = append(flags.Local.LdFlags, memtagStackCommonFlags...)
Florian Mayerf79b2102022-09-09 14:23:31 -0700749 // This works around LLD complaining about the stack frame size.
750 // TODO(fmayer): remove once https://reviews.llvm.org/D127917 is in Android toolchain.
751 flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,--no-fatal-warnings")
Florian Mayerd8434a42022-08-31 20:57:03 +0000752 }
753
754 if (Bool(sanitize.Properties.Sanitize.Memtag_heap) || Bool(sanitize.Properties.Sanitize.Memtag_stack)) && ctx.binary() {
755 if Bool(sanitize.Properties.Sanitize.Diag.Memtag_heap) {
756 flags.Local.LdFlags = append(flags.Local.LdFlags, "-fsanitize-memtag-mode=sync")
757 } else {
758 flags.Local.LdFlags = append(flags.Local.LdFlags, "-fsanitize-memtag-mode=async")
759 }
760 }
761
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700762 if Bool(sanitize.Properties.Sanitize.Integer_overflow) {
Colin Cross4af21ed2019-11-04 09:37:55 -0800763 flags.Local.CFlags = append(flags.Local.CFlags, intOverflowCflags...)
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700764 }
765
Jiyong Park379de2f2018-12-19 02:47:14 +0900766 if len(sanitize.Properties.Sanitizers) > 0 {
767 sanitizeArg := "-fsanitize=" + strings.Join(sanitize.Properties.Sanitizers, ",")
Colin Cross4af21ed2019-11-04 09:37:55 -0800768 flags.Local.CFlags = append(flags.Local.CFlags, sanitizeArg)
769 flags.Local.AsFlags = append(flags.Local.AsFlags, sanitizeArg)
Colin Cross234b01d2022-02-07 13:49:03 -0800770 flags.Local.LdFlags = append(flags.Local.LdFlags, sanitizeArg)
771
Colin Crossed12a042022-02-07 13:55:55 -0800772 if ctx.toolchain().Bionic() || ctx.toolchain().Musl() {
773 // Bionic and musl sanitizer runtimes have already been added as dependencies so that
774 // the right variant of the runtime will be used (with the "-android" or "-musl"
775 // suffixes), so don't let clang the runtime library.
Colin Cross234b01d2022-02-07 13:49:03 -0800776 flags.Local.LdFlags = append(flags.Local.LdFlags, "-fno-sanitize-link-runtime")
777 } else {
Evgenii Stepanov76cee232017-01-27 15:44:44 -0800778 // Host sanitizers only link symbols in the final executable, so
779 // there will always be undefined symbols in intermediate libraries.
Colin Cross4af21ed2019-11-04 09:37:55 -0800780 _, flags.Global.LdFlags = removeFromList("-Wl,--no-undefined", flags.Global.LdFlags)
Colin Cross6c18d002022-06-02 15:11:50 -0700781 }
Ivan Lozano9ac32c72020-02-19 15:24:02 -0500782
Colin Cross6c18d002022-06-02 15:11:50 -0700783 if !ctx.toolchain().Bionic() {
784 // non-Bionic toolchain prebuilts are missing UBSan's vptr and function san.
785 // Musl toolchain prebuilts have vptr and function sanitizers, but enabling them
786 // implicitly enables RTTI which causes RTTI mismatch issues with dependencies.
787
Colin Cross234b01d2022-02-07 13:49:03 -0800788 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-sanitize=vptr,function")
Ivan Lozano9ac32c72020-02-19 15:24:02 -0500789 }
790
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700791 if Bool(sanitize.Properties.Sanitize.Fuzzer) {
792 // When fuzzing, we wish to crash with diagnostics on any bug.
Colin Cross4af21ed2019-11-04 09:37:55 -0800793 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-sanitize-trap=all", "-fno-sanitize-recover=all")
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700794 } else if ctx.Host() {
Colin Cross4af21ed2019-11-04 09:37:55 -0800795 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-sanitize-recover=all")
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700796 } else {
Colin Cross4af21ed2019-11-04 09:37:55 -0800797 flags.Local.CFlags = append(flags.Local.CFlags, "-fsanitize-trap=all", "-ftrap-function=abort")
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700798 }
Evgenii Stepanov59012812022-06-24 11:09:18 -0700799
800 if enableMinimalRuntime(sanitize) {
801 flags.Local.CFlags = append(flags.Local.CFlags, strings.Join(minimalRuntimeFlags, " "))
802 }
803
Chih-Hung Hsieh3567e622018-11-15 14:01:36 -0800804 // http://b/119329758, Android core does not boot up with this sanitizer yet.
Colin Cross4af21ed2019-11-04 09:37:55 -0800805 if toDisableImplicitIntegerChange(flags.Local.CFlags) {
806 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-sanitize=implicit-integer-sign-change")
Chih-Hung Hsieh3567e622018-11-15 14:01:36 -0800807 }
Yabin Cuidb7dda82020-11-30 15:47:45 -0800808 // http://b/171275751, Android doesn't build with this sanitizer yet.
809 if toDisableUnsignedShiftBaseChange(flags.Local.CFlags) {
810 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-sanitize=unsigned-shift-base")
811 }
Colin Cross16b23492016-01-06 14:41:07 -0800812 }
813
Jiyong Park379de2f2018-12-19 02:47:14 +0900814 if len(sanitize.Properties.DiagSanitizers) > 0 {
Colin Cross4af21ed2019-11-04 09:37:55 -0800815 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-sanitize-trap="+strings.Join(sanitize.Properties.DiagSanitizers, ","))
Evgenii Stepanov1e405e12016-08-16 15:39:54 -0700816 }
817 // FIXME: enable RTTI if diag + (cfi or vptr)
818
Andreas Gampe97071162017-05-08 13:15:23 -0700819 if sanitize.Properties.Sanitize.Recover != nil {
Colin Cross4af21ed2019-11-04 09:37:55 -0800820 flags.Local.CFlags = append(flags.Local.CFlags, "-fsanitize-recover="+
Andreas Gampe97071162017-05-08 13:15:23 -0700821 strings.Join(sanitize.Properties.Sanitize.Recover, ","))
822 }
823
Ivan Lozano7929bba2018-12-12 09:36:31 -0800824 if sanitize.Properties.Sanitize.Diag.No_recover != nil {
Colin Cross4af21ed2019-11-04 09:37:55 -0800825 flags.Local.CFlags = append(flags.Local.CFlags, "-fno-sanitize-recover="+
Ivan Lozano7929bba2018-12-12 09:36:31 -0800826 strings.Join(sanitize.Properties.Sanitize.Diag.No_recover, ","))
827 }
828
Pirama Arumuga Nainar6c4ccca2020-07-27 11:49:51 -0700829 blocklist := android.OptionalPathForModuleSrc(ctx, sanitize.Properties.Sanitize.Blocklist)
830 if blocklist.Valid() {
Pirama Arumuga Nainar582fc2d2021-08-27 15:12:56 -0700831 flags.Local.CFlags = append(flags.Local.CFlags, "-fsanitize-ignorelist="+blocklist.String())
Pirama Arumuga Nainar6c4ccca2020-07-27 11:49:51 -0700832 flags.CFlagsDeps = append(flags.CFlagsDeps, blocklist.Path())
833 }
834
Colin Cross16b23492016-01-06 14:41:07 -0800835 return flags
836}
837
Colin Crossd80cbca2020-02-24 12:01:37 -0800838func (sanitize *sanitize) AndroidMkEntries(ctx AndroidMkContext, entries *android.AndroidMkEntries) {
Jiyong Park1d1119f2019-07-29 21:27:18 +0900839 // Add a suffix for cfi/hwasan/scs-enabled static/header libraries to allow surfacing
840 // both the sanitized and non-sanitized variants to make without a name conflict.
Colin Crossd80cbca2020-02-24 12:01:37 -0800841 if entries.Class == "STATIC_LIBRARIES" || entries.Class == "HEADER_LIBRARIES" {
Jiyong Park1d1119f2019-07-29 21:27:18 +0900842 if Bool(sanitize.Properties.Sanitize.Cfi) {
Colin Crossd80cbca2020-02-24 12:01:37 -0800843 entries.SubName += ".cfi"
Jiyong Park1d1119f2019-07-29 21:27:18 +0900844 }
845 if Bool(sanitize.Properties.Sanitize.Hwaddress) {
Colin Crossd80cbca2020-02-24 12:01:37 -0800846 entries.SubName += ".hwasan"
Jiyong Park1d1119f2019-07-29 21:27:18 +0900847 }
848 if Bool(sanitize.Properties.Sanitize.Scs) {
Colin Crossd80cbca2020-02-24 12:01:37 -0800849 entries.SubName += ".scs"
Jiyong Park1d1119f2019-07-29 21:27:18 +0900850 }
Peter Collingbourne8c7e6e22018-11-19 16:03:58 -0800851 }
Colin Cross8ff9ef42017-05-08 13:44:11 -0700852}
853
Vishwath Mohan1dd88392017-03-29 22:00:18 -0700854func (sanitize *sanitize) inSanitizerDir() bool {
855 return sanitize.Properties.InSanitizerDir
Colin Cross30d5f512016-05-03 18:02:42 -0700856}
857
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500858// getSanitizerBoolPtr returns the SanitizerTypes associated bool pointer from SanitizeProperties.
859func (sanitize *sanitize) getSanitizerBoolPtr(t SanitizerType) *bool {
Vishwath Mohan95229302017-08-11 00:53:16 +0000860 switch t {
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500861 case Asan:
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000862 return sanitize.Properties.Sanitize.Address
Tri Vo6eafc362021-04-01 11:29:09 -0700863 case Hwasan:
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -0700864 return sanitize.Properties.Sanitize.Hwaddress
Vishwath Mohan95229302017-08-11 00:53:16 +0000865 case tsan:
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000866 return sanitize.Properties.Sanitize.Thread
Vishwath Mohan95229302017-08-11 00:53:16 +0000867 case intOverflow:
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000868 return sanitize.Properties.Sanitize.Integer_overflow
869 case cfi:
870 return sanitize.Properties.Sanitize.Cfi
Peter Collingbourne8c7e6e22018-11-19 16:03:58 -0800871 case scs:
872 return sanitize.Properties.Sanitize.Scs
Ivan Lozano62cd0382021-11-01 10:27:54 -0400873 case Memtag_heap:
Evgenii Stepanov193ac2e2020-04-28 15:09:12 -0700874 return sanitize.Properties.Sanitize.Memtag_heap
Florian Mayerd8434a42022-08-31 20:57:03 +0000875 case Memtag_stack:
876 return sanitize.Properties.Sanitize.Memtag_stack
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500877 case Fuzzer:
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700878 return sanitize.Properties.Sanitize.Fuzzer
Vishwath Mohan95229302017-08-11 00:53:16 +0000879 default:
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500880 panic(fmt.Errorf("unknown SanitizerType %d", t))
Vishwath Mohan95229302017-08-11 00:53:16 +0000881 }
882}
883
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500884// isUnsanitizedVariant returns true if no sanitizers are enabled.
Dan Albert7d1eecf2018-01-19 12:30:45 -0800885func (sanitize *sanitize) isUnsanitizedVariant() bool {
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500886 return !sanitize.isSanitizerEnabled(Asan) &&
Tri Vo6eafc362021-04-01 11:29:09 -0700887 !sanitize.isSanitizerEnabled(Hwasan) &&
Dan Albert7d1eecf2018-01-19 12:30:45 -0800888 !sanitize.isSanitizerEnabled(tsan) &&
Peter Collingbourne8c7e6e22018-11-19 16:03:58 -0800889 !sanitize.isSanitizerEnabled(cfi) &&
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700890 !sanitize.isSanitizerEnabled(scs) &&
Ivan Lozano62cd0382021-11-01 10:27:54 -0400891 !sanitize.isSanitizerEnabled(Memtag_heap) &&
Florian Mayerd8434a42022-08-31 20:57:03 +0000892 !sanitize.isSanitizerEnabled(Memtag_stack) &&
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500893 !sanitize.isSanitizerEnabled(Fuzzer)
Dan Albert7d1eecf2018-01-19 12:30:45 -0800894}
895
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500896// isVariantOnProductionDevice returns true if variant is for production devices (no non-production sanitizers enabled).
Jayant Chowdharyb7e08ca2018-05-10 15:29:24 -0700897func (sanitize *sanitize) isVariantOnProductionDevice() bool {
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500898 return !sanitize.isSanitizerEnabled(Asan) &&
Tri Vo6eafc362021-04-01 11:29:09 -0700899 !sanitize.isSanitizerEnabled(Hwasan) &&
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -0700900 !sanitize.isSanitizerEnabled(tsan) &&
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500901 !sanitize.isSanitizerEnabled(Fuzzer)
Jayant Chowdharyb7e08ca2018-05-10 15:29:24 -0700902}
903
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500904func (sanitize *sanitize) SetSanitizer(t SanitizerType, b bool) {
Liz Kammerb2fc4702021-06-25 14:53:40 -0400905 bPtr := proptools.BoolPtr(b)
906 if !b {
907 bPtr = nil
908 }
Colin Cross16b23492016-01-06 14:41:07 -0800909 switch t {
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500910 case Asan:
Liz Kammerb2fc4702021-06-25 14:53:40 -0400911 sanitize.Properties.Sanitize.Address = bPtr
Florian Mayer1bda2462022-09-29 15:48:08 -0700912 // For ASAN variant, we need to disable Memtag_stack
913 sanitize.Properties.Sanitize.Memtag_stack = nil
Tri Vo6eafc362021-04-01 11:29:09 -0700914 case Hwasan:
Liz Kammerb2fc4702021-06-25 14:53:40 -0400915 sanitize.Properties.Sanitize.Hwaddress = bPtr
Florian Mayer1bda2462022-09-29 15:48:08 -0700916 // For HWAsan variant, we need to disable Memtag_stack
917 sanitize.Properties.Sanitize.Memtag_stack = nil
Colin Cross16b23492016-01-06 14:41:07 -0800918 case tsan:
Liz Kammerb2fc4702021-06-25 14:53:40 -0400919 sanitize.Properties.Sanitize.Thread = bPtr
Ivan Lozano0c3a1ef2017-06-28 09:10:48 -0700920 case intOverflow:
Liz Kammerb2fc4702021-06-25 14:53:40 -0400921 sanitize.Properties.Sanitize.Integer_overflow = bPtr
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000922 case cfi:
Liz Kammerb2fc4702021-06-25 14:53:40 -0400923 sanitize.Properties.Sanitize.Cfi = bPtr
Peter Collingbourne8c7e6e22018-11-19 16:03:58 -0800924 case scs:
Liz Kammerb2fc4702021-06-25 14:53:40 -0400925 sanitize.Properties.Sanitize.Scs = bPtr
Ivan Lozano62cd0382021-11-01 10:27:54 -0400926 case Memtag_heap:
Liz Kammerb2fc4702021-06-25 14:53:40 -0400927 sanitize.Properties.Sanitize.Memtag_heap = bPtr
Florian Mayerd8434a42022-08-31 20:57:03 +0000928 case Memtag_stack:
929 sanitize.Properties.Sanitize.Memtag_stack = bPtr
Florian Mayer1bda2462022-09-29 15:48:08 -0700930 // We do not need to disable ASAN or HWASan here, as there is no Memtag_stack variant.
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500931 case Fuzzer:
Liz Kammerb2fc4702021-06-25 14:53:40 -0400932 sanitize.Properties.Sanitize.Fuzzer = bPtr
Colin Cross16b23492016-01-06 14:41:07 -0800933 default:
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500934 panic(fmt.Errorf("unknown SanitizerType %d", t))
Colin Cross16b23492016-01-06 14:41:07 -0800935 }
936 if b {
937 sanitize.Properties.SanitizerEnabled = true
938 }
939}
940
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000941// Check if the sanitizer is explicitly disabled (as opposed to nil by
942// virtue of not being set).
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500943func (sanitize *sanitize) isSanitizerExplicitlyDisabled(t SanitizerType) bool {
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000944 if sanitize == nil {
945 return false
946 }
947
948 sanitizerVal := sanitize.getSanitizerBoolPtr(t)
949 return sanitizerVal != nil && *sanitizerVal == false
950}
951
952// There isn't an analog of the method above (ie:isSanitizerExplicitlyEnabled)
953// because enabling a sanitizer either directly (via the blueprint) or
954// indirectly (via a mutator) sets the bool ptr to true, and you can't
955// distinguish between the cases. It isn't needed though - both cases can be
956// treated identically.
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500957func (sanitize *sanitize) isSanitizerEnabled(t SanitizerType) bool {
Vishwath Mohanb743e9c2017-11-01 09:20:21 +0000958 if sanitize == nil {
959 return false
960 }
961
962 sanitizerVal := sanitize.getSanitizerBoolPtr(t)
963 return sanitizerVal != nil && *sanitizerVal == true
964}
965
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500966// IsSanitizableDependencyTag returns true if the dependency tag is sanitizable.
967func IsSanitizableDependencyTag(tag blueprint.DependencyTag) bool {
Colin Cross6e511a92020-07-27 21:26:48 -0700968 switch t := tag.(type) {
969 case dependencyTag:
970 return t == reuseObjTag || t == objDepTag
971 case libraryDependencyTag:
972 return true
973 default:
974 return false
975 }
Colin Cross6b753602018-06-21 13:03:07 -0700976}
977
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500978func (m *Module) SanitizableDepTagChecker() SantizableDependencyTagChecker {
979 return IsSanitizableDependencyTag
980}
981
Inseob Kimc42f2f22020-07-29 20:32:10 +0900982// Determines if the current module is a static library going to be captured
983// as vendor snapshot. Such modules must create both cfi and non-cfi variants,
984// except for ones which explicitly disable cfi.
Lukacs T. Berki6c716762022-06-13 20:50:39 +0200985func needsCfiForVendorSnapshot(mctx android.BaseModuleContext) bool {
Kiyoung Kim48f37782021-07-07 12:42:39 +0900986 if snapshot.IsVendorProprietaryModule(mctx) {
Inseob Kimc42f2f22020-07-29 20:32:10 +0900987 return false
988 }
989
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500990 c := mctx.Module().(PlatformSanitizeable)
Inseob Kimc42f2f22020-07-29 20:32:10 +0900991
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500992 if !c.InVendor() {
Inseob Kimc42f2f22020-07-29 20:32:10 +0900993 return false
994 }
995
Ivan Lozano3968d8f2020-12-14 11:27:52 -0500996 if !c.StaticallyLinked() {
Inseob Kimc42f2f22020-07-29 20:32:10 +0900997 return false
998 }
999
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001000 if c.IsPrebuilt() {
Inseob Kimc42f2f22020-07-29 20:32:10 +09001001 return false
1002 }
1003
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001004 if !c.SanitizerSupported(cfi) {
1005 return false
1006 }
1007
1008 return c.SanitizePropDefined() &&
1009 !c.SanitizeNever() &&
1010 !c.IsSanitizerExplicitlyDisabled(cfi)
Inseob Kimc42f2f22020-07-29 20:32:10 +09001011}
1012
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001013type sanitizerSplitMutator struct {
1014 sanitizer SanitizerType
1015}
1016
1017// If an APEX is sanitized or not depends on whether it contains at least one
1018// sanitized module. Transition mutators cannot propagate information up the
1019// dependency graph this way, so we need an auxiliary mutator to do so.
1020func (s *sanitizerSplitMutator) markSanitizableApexesMutator(ctx android.TopDownMutatorContext) {
1021 if sanitizeable, ok := ctx.Module().(Sanitizeable); ok {
1022 enabled := sanitizeable.IsSanitizerEnabled(ctx.Config(), s.sanitizer.name())
1023 ctx.VisitDirectDeps(func(dep android.Module) {
1024 if c, ok := dep.(*Module); ok && c.sanitize.isSanitizerEnabled(s.sanitizer) {
Inseob Kimc42f2f22020-07-29 20:32:10 +09001025 enabled = true
Inseob Kimc42f2f22020-07-29 20:32:10 +09001026 }
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001027 })
1028
1029 if enabled {
1030 sanitizeable.EnableSanitizer(s.sanitizer.name())
1031 }
1032 }
1033}
1034
1035func (s *sanitizerSplitMutator) Split(ctx android.BaseModuleContext) []string {
1036 if c, ok := ctx.Module().(PlatformSanitizeable); ok && c.SanitizePropDefined() {
1037 if s.sanitizer == cfi && needsCfiForVendorSnapshot(ctx) {
1038 return []string{"", s.sanitizer.variationName()}
1039 }
1040
1041 // If the given sanitizer is not requested in the .bp file for a module, it
1042 // won't automatically build the sanitized variation.
1043 if !c.IsSanitizerEnabled(s.sanitizer) {
1044 return []string{""}
1045 }
1046
1047 if c.Binary() {
1048 // If a sanitizer is enabled for a binary, we do not build the version
1049 // without the sanitizer
1050 return []string{s.sanitizer.variationName()}
1051 } else if c.StaticallyLinked() || c.Header() {
1052 // For static libraries, we build both versions. Some Make modules
1053 // apparently depend on this behavior.
1054 return []string{"", s.sanitizer.variationName()}
1055 } else {
1056 // We only build the requested variation of dynamic libraries
1057 return []string{s.sanitizer.variationName()}
1058 }
1059 }
1060
1061 if _, ok := ctx.Module().(JniSanitizeable); ok {
1062 // TODO: this should call into JniSanitizable.IsSanitizerEnabledForJni but
1063 // that is short-circuited for now
1064 return []string{""}
1065 }
1066
1067 // If an APEX has a sanitized dependency, we build the APEX in the sanitized
1068 // variation. This is useful because such APEXes require extra dependencies.
1069 if sanitizeable, ok := ctx.Module().(Sanitizeable); ok {
1070 enabled := sanitizeable.IsSanitizerEnabled(ctx.Config(), s.sanitizer.name())
1071 if enabled {
1072 return []string{s.sanitizer.variationName()}
1073 } else {
1074 return []string{""}
1075 }
1076 }
1077
1078 if c, ok := ctx.Module().(*Module); ok {
1079 //TODO: When Rust modules have vendor support, enable this path for PlatformSanitizeable
1080
1081 // Check if it's a snapshot module supporting sanitizer
1082 if ss, ok := c.linker.(snapshotSanitizer); ok && ss.isSanitizerEnabled(s.sanitizer) {
1083 return []string{"", s.sanitizer.variationName()}
1084 } else {
1085 return []string{""}
1086 }
1087 }
1088
1089 return []string{""}
1090}
1091
1092func (s *sanitizerSplitMutator) OutgoingTransition(ctx android.OutgoingTransitionContext, sourceVariation string) string {
1093 if c, ok := ctx.Module().(PlatformSanitizeable); ok {
1094 if !c.SanitizableDepTagChecker()(ctx.DepTag()) {
1095 // If the dependency is through a non-sanitizable tag, use the
1096 // non-sanitized variation
1097 return ""
1098 }
1099
1100 return sourceVariation
1101 } else if _, ok := ctx.Module().(JniSanitizeable); ok {
1102 // TODO: this should call into JniSanitizable.IsSanitizerEnabledForJni but
1103 // that is short-circuited for now
1104 return ""
1105 } else {
1106 // Otherwise, do not rock the boat.
1107 return sourceVariation
1108 }
1109}
1110
1111func (s *sanitizerSplitMutator) IncomingTransition(ctx android.IncomingTransitionContext, incomingVariation string) string {
1112 if d, ok := ctx.Module().(PlatformSanitizeable); ok {
1113 if dm, ok := ctx.Module().(*Module); ok {
1114 if ss, ok := dm.linker.(snapshotSanitizer); ok && ss.isSanitizerEnabled(s.sanitizer) {
1115 return incomingVariation
Inseob Kimc42f2f22020-07-29 20:32:10 +09001116 }
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001117 }
1118
1119 if !d.SanitizePropDefined() ||
1120 d.SanitizeNever() ||
1121 d.IsSanitizerExplicitlyDisabled(s.sanitizer) ||
1122 !d.SanitizerSupported(s.sanitizer) {
1123 // If a module opts out of a sanitizer, use its non-sanitized variation
1124 return ""
1125 }
1126
1127 // Binaries are always built in the variation they requested.
1128 if d.Binary() {
1129 if d.IsSanitizerEnabled(s.sanitizer) {
1130 return s.sanitizer.variationName()
1131 } else {
1132 return ""
Muhammad Haseeb Ahmad7e744052022-03-25 22:50:53 +00001133 }
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001134 }
1135
1136 // If a shared library requests to be sanitized, it will be built for that
1137 // sanitizer. Otherwise, some sanitizers propagate through shared library
1138 // dependency edges, some do not.
1139 if !d.StaticallyLinked() && !d.Header() {
1140 if d.IsSanitizerEnabled(s.sanitizer) {
1141 return s.sanitizer.variationName()
1142 }
1143
Liz Kammerfd8a49f2022-10-31 10:31:11 -04001144 // Some sanitizers do not propagate to shared dependencies
1145 if !s.sanitizer.shouldPropagateToSharedLibraryDeps() {
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001146 return ""
1147 }
1148 }
1149
1150 // Static and header libraries inherit whether they are sanitized from the
1151 // module they are linked into
1152 return incomingVariation
1153 } else if d, ok := ctx.Module().(Sanitizeable); ok {
1154 // If an APEX contains a sanitized module, it will be built in the variation
1155 // corresponding to that sanitizer.
1156 enabled := d.IsSanitizerEnabled(ctx.Config(), s.sanitizer.name())
1157 if enabled {
1158 return s.sanitizer.variationName()
1159 }
1160
1161 return incomingVariation
1162 }
1163
1164 return ""
1165}
1166
1167func (s *sanitizerSplitMutator) Mutate(mctx android.BottomUpMutatorContext, variationName string) {
1168 sanitizerVariation := variationName == s.sanitizer.variationName()
1169
1170 if c, ok := mctx.Module().(PlatformSanitizeable); ok && c.SanitizePropDefined() {
1171 sanitizerEnabled := c.IsSanitizerEnabled(s.sanitizer)
1172
1173 oneMakeVariation := false
1174 if c.StaticallyLinked() || c.Header() {
1175 if s.sanitizer != cfi && s.sanitizer != scs && s.sanitizer != Hwasan {
1176 // These sanitizers export only one variation to Make. For the rest,
1177 // Make targets can depend on both the sanitized and non-sanitized
1178 // versions.
1179 oneMakeVariation = true
1180 }
1181 } else if !c.Binary() {
1182 // Shared library. These are the sanitizers that do propagate through shared
1183 // library dependencies and therefore can cause multiple variations of a
1184 // shared library to be built.
1185 if s.sanitizer != cfi && s.sanitizer != Hwasan && s.sanitizer != scs && s.sanitizer != Asan {
1186 oneMakeVariation = true
1187 }
1188 }
1189
1190 if oneMakeVariation {
1191 if sanitizerEnabled != sanitizerVariation {
1192 c.SetPreventInstall()
1193 c.SetHideFromMake()
1194 }
1195 }
1196
1197 if sanitizerVariation {
1198 c.SetSanitizer(s.sanitizer, true)
1199
1200 // CFI is incompatible with ASAN so disable it in ASAN variations
1201 if s.sanitizer.incompatibleWithCfi() {
1202 cfiSupported := mctx.Module().(PlatformSanitizeable).SanitizerSupported(cfi)
1203 if mctx.Device() && cfiSupported {
1204 c.SetSanitizer(cfi, false)
Jiyong Parkf97782b2019-02-13 20:28:58 +09001205 }
Lukacs T. Berki6c716762022-06-13 20:50:39 +02001206 }
1207
1208 // locate the asan libraries under /data/asan
1209 if !c.Binary() && !c.StaticallyLinked() && !c.Header() && mctx.Device() && s.sanitizer == Asan && sanitizerEnabled {
1210 c.SetInSanitizerDir()
1211 }
1212
1213 if c.StaticallyLinked() && c.ExportedToMake() {
1214 if s.sanitizer == Hwasan {
1215 hwasanStaticLibs(mctx.Config()).add(c, c.Module().Name())
1216 } else if s.sanitizer == cfi {
1217 cfiStaticLibs(mctx.Config()).add(c, c.Module().Name())
1218 }
1219 }
1220 } else if c.IsSanitizerEnabled(s.sanitizer) {
1221 // Disable the sanitizer for the non-sanitized variation
1222 c.SetSanitizer(s.sanitizer, false)
1223 }
1224 } else if sanitizeable, ok := mctx.Module().(Sanitizeable); ok {
1225 // If an APEX has sanitized dependencies, it gets a few more dependencies
1226 if sanitizerVariation {
1227 sanitizeable.AddSanitizerDependencies(mctx, s.sanitizer.name())
1228 }
1229 } else if c, ok := mctx.Module().(*Module); ok {
1230 if ss, ok := c.linker.(snapshotSanitizer); ok && ss.isSanitizerEnabled(s.sanitizer) {
1231 c.linker.(snapshotSanitizer).setSanitizerVariation(s.sanitizer, sanitizerVariation)
1232
1233 // Export the static lib name to make
1234 if c.static() && c.ExportedToMake() {
1235 if s.sanitizer == cfi {
1236 // use BaseModuleName which is the name for Make.
1237 cfiStaticLibs(mctx.Config()).add(c, c.BaseModuleName())
1238 }
1239 }
Colin Cross16b23492016-01-06 14:41:07 -08001240 }
1241 }
1242}
1243
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001244func (c *Module) SanitizeNever() bool {
1245 return Bool(c.sanitize.Properties.Sanitize.Never)
1246}
1247
1248func (c *Module) IsSanitizerExplicitlyDisabled(t SanitizerType) bool {
1249 return c.sanitize.isSanitizerExplicitlyDisabled(t)
1250}
1251
Ivan Lozano30c5db22018-02-21 15:49:20 -08001252// Propagate the ubsan minimal runtime dependency when there are integer overflow sanitized static dependencies.
Colin Cross6b753602018-06-21 13:03:07 -07001253func sanitizerRuntimeDepsMutator(mctx android.TopDownMutatorContext) {
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001254 // Change this to PlatformSanitizable when/if non-cc modules support ubsan sanitizers.
Colin Cross6b753602018-06-21 13:03:07 -07001255 if c, ok := mctx.Module().(*Module); ok && c.sanitize != nil {
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001256 isSanitizableDependencyTag := c.SanitizableDepTagChecker()
Colin Cross6b753602018-06-21 13:03:07 -07001257 mctx.WalkDeps(func(child, parent android.Module) bool {
1258 if !isSanitizableDependencyTag(mctx.OtherModuleDependencyTag(child)) {
1259 return false
1260 }
Ivan Lozano30c5db22018-02-21 15:49:20 -08001261
Inseob Kimeec88e12020-01-22 11:11:29 +09001262 d, ok := child.(*Module)
1263 if !ok || !d.static() {
1264 return false
1265 }
1266 if d.sanitize != nil {
Colin Cross6b753602018-06-21 13:03:07 -07001267 if enableMinimalRuntime(d.sanitize) {
1268 // If a static dependency is built with the minimal runtime,
1269 // make sure we include the ubsan minimal runtime.
1270 c.sanitize.Properties.MinimalRuntimeDep = true
Inseob Kim8471cda2019-11-15 09:59:12 +09001271 } else if enableUbsanRuntime(d.sanitize) {
Colin Cross6b753602018-06-21 13:03:07 -07001272 // If a static dependency runs with full ubsan diagnostics,
1273 // make sure we include the ubsan runtime.
1274 c.sanitize.Properties.UbsanRuntimeDep = true
Ivan Lozano30c5db22018-02-21 15:49:20 -08001275 }
Colin Cross0b908332019-06-19 23:00:20 -07001276
1277 if c.sanitize.Properties.MinimalRuntimeDep &&
1278 c.sanitize.Properties.UbsanRuntimeDep {
1279 // both flags that this mutator might set are true, so don't bother recursing
1280 return false
1281 }
1282
Ivan Lozano9ac32c72020-02-19 15:24:02 -05001283 if c.Os() == android.Linux {
1284 c.sanitize.Properties.BuiltinsDep = true
1285 }
1286
Colin Cross0b908332019-06-19 23:00:20 -07001287 return true
Colin Cross6b753602018-06-21 13:03:07 -07001288 }
Inseob Kimeec88e12020-01-22 11:11:29 +09001289
Jose Galmesf7294582020-11-13 12:07:36 -08001290 if p, ok := d.linker.(*snapshotLibraryDecorator); ok {
Inseob Kimeec88e12020-01-22 11:11:29 +09001291 if Bool(p.properties.Sanitize_minimal_dep) {
1292 c.sanitize.Properties.MinimalRuntimeDep = true
1293 }
1294 if Bool(p.properties.Sanitize_ubsan_dep) {
1295 c.sanitize.Properties.UbsanRuntimeDep = true
1296 }
1297 }
1298
1299 return false
Colin Cross6b753602018-06-21 13:03:07 -07001300 })
Ivan Lozano30c5db22018-02-21 15:49:20 -08001301 }
1302}
1303
Jiyong Park379de2f2018-12-19 02:47:14 +09001304// Add the dependency to the runtime library for each of the sanitizer variants
1305func sanitizerRuntimeMutator(mctx android.BottomUpMutatorContext) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001306 if c, ok := mctx.Module().(*Module); ok && c.sanitize != nil {
Pirama Arumuga Nainar6aa21022019-01-25 00:20:35 +00001307 if !c.Enabled() {
1308 return
1309 }
Jiyong Park379de2f2018-12-19 02:47:14 +09001310 var sanitizers []string
1311 var diagSanitizers []string
1312
1313 if Bool(c.sanitize.Properties.Sanitize.All_undefined) {
1314 sanitizers = append(sanitizers, "undefined")
1315 } else {
1316 if Bool(c.sanitize.Properties.Sanitize.Undefined) {
1317 sanitizers = append(sanitizers,
1318 "bool",
1319 "integer-divide-by-zero",
1320 "return",
1321 "returns-nonnull-attribute",
1322 "shift-exponent",
1323 "unreachable",
1324 "vla-bound",
1325 // TODO(danalbert): The following checks currently have compiler performance issues.
1326 //"alignment",
1327 //"bounds",
1328 //"enum",
1329 //"float-cast-overflow",
1330 //"float-divide-by-zero",
1331 //"nonnull-attribute",
1332 //"null",
1333 //"shift-base",
1334 //"signed-integer-overflow",
1335 // TODO(danalbert): Fix UB in libc++'s __tree so we can turn this on.
1336 // https://llvm.org/PR19302
1337 // http://reviews.llvm.org/D6974
1338 // "object-size",
1339 )
1340 }
1341 sanitizers = append(sanitizers, c.sanitize.Properties.Sanitize.Misc_undefined...)
1342 }
1343
1344 if Bool(c.sanitize.Properties.Sanitize.Diag.Undefined) {
1345 diagSanitizers = append(diagSanitizers, "undefined")
1346 }
1347
1348 diagSanitizers = append(diagSanitizers, c.sanitize.Properties.Sanitize.Diag.Misc_undefined...)
1349
1350 if Bool(c.sanitize.Properties.Sanitize.Address) {
1351 sanitizers = append(sanitizers, "address")
1352 diagSanitizers = append(diagSanitizers, "address")
1353 }
1354
1355 if Bool(c.sanitize.Properties.Sanitize.Hwaddress) {
1356 sanitizers = append(sanitizers, "hwaddress")
1357 }
1358
1359 if Bool(c.sanitize.Properties.Sanitize.Thread) {
1360 sanitizers = append(sanitizers, "thread")
1361 }
1362
1363 if Bool(c.sanitize.Properties.Sanitize.Safestack) {
1364 sanitizers = append(sanitizers, "safe-stack")
1365 }
1366
1367 if Bool(c.sanitize.Properties.Sanitize.Cfi) {
1368 sanitizers = append(sanitizers, "cfi")
1369
1370 if Bool(c.sanitize.Properties.Sanitize.Diag.Cfi) {
1371 diagSanitizers = append(diagSanitizers, "cfi")
1372 }
1373 }
1374
1375 if Bool(c.sanitize.Properties.Sanitize.Integer_overflow) {
1376 sanitizers = append(sanitizers, "unsigned-integer-overflow")
1377 sanitizers = append(sanitizers, "signed-integer-overflow")
1378 if Bool(c.sanitize.Properties.Sanitize.Diag.Integer_overflow) {
1379 diagSanitizers = append(diagSanitizers, "unsigned-integer-overflow")
1380 diagSanitizers = append(diagSanitizers, "signed-integer-overflow")
1381 }
1382 }
1383
1384 if Bool(c.sanitize.Properties.Sanitize.Scudo) {
1385 sanitizers = append(sanitizers, "scudo")
1386 }
1387
1388 if Bool(c.sanitize.Properties.Sanitize.Scs) {
1389 sanitizers = append(sanitizers, "shadow-call-stack")
1390 }
1391
Ivan Lozanod7586b62021-04-01 09:49:36 -04001392 if Bool(c.sanitize.Properties.Sanitize.Memtag_heap) && c.Binary() {
Florian Mayerd8434a42022-08-31 20:57:03 +00001393 sanitizers = append(sanitizers, "memtag-heap")
1394 }
1395
1396 if Bool(c.sanitize.Properties.Sanitize.Memtag_stack) {
1397 sanitizers = append(sanitizers, "memtag-stack")
Evgenii Stepanov193ac2e2020-04-28 15:09:12 -07001398 }
1399
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -07001400 if Bool(c.sanitize.Properties.Sanitize.Fuzzer) {
1401 sanitizers = append(sanitizers, "fuzzer-no-link")
1402 }
1403
Jiyong Park379de2f2018-12-19 02:47:14 +09001404 // Save the list of sanitizers. These will be used again when generating
1405 // the build rules (for Cflags, etc.)
1406 c.sanitize.Properties.Sanitizers = sanitizers
1407 c.sanitize.Properties.DiagSanitizers = diagSanitizers
1408
Ivan Lozanof3b190f2020-03-06 12:01:21 -05001409 // TODO(b/150822854) Hosts have a different default behavior and assume the runtime library is used.
1410 if c.Host() {
1411 diagSanitizers = sanitizers
1412 }
1413
Jiyong Park379de2f2018-12-19 02:47:14 +09001414 // Determine the runtime library required
1415 runtimeLibrary := ""
Colin Crosse725b4e2022-10-19 15:46:53 -07001416 alwaysStaticRuntime := false
Ryan Prichardb49fe1b2019-10-11 15:03:34 -07001417 var extraStaticDeps []string
Jiyong Park379de2f2018-12-19 02:47:14 +09001418 toolchain := c.toolchain(mctx)
1419 if Bool(c.sanitize.Properties.Sanitize.Address) {
1420 runtimeLibrary = config.AddressSanitizerRuntimeLibrary(toolchain)
1421 } else if Bool(c.sanitize.Properties.Sanitize.Hwaddress) {
1422 if c.staticBinary() {
1423 runtimeLibrary = config.HWAddressSanitizerStaticLibrary(toolchain)
Ryan Prichardb49fe1b2019-10-11 15:03:34 -07001424 extraStaticDeps = []string{"libdl"}
Jiyong Park379de2f2018-12-19 02:47:14 +09001425 } else {
1426 runtimeLibrary = config.HWAddressSanitizerRuntimeLibrary(toolchain)
1427 }
1428 } else if Bool(c.sanitize.Properties.Sanitize.Thread) {
1429 runtimeLibrary = config.ThreadSanitizerRuntimeLibrary(toolchain)
1430 } else if Bool(c.sanitize.Properties.Sanitize.Scudo) {
1431 if len(diagSanitizers) == 0 && !c.sanitize.Properties.UbsanRuntimeDep {
1432 runtimeLibrary = config.ScudoMinimalRuntimeLibrary(toolchain)
1433 } else {
1434 runtimeLibrary = config.ScudoRuntimeLibrary(toolchain)
1435 }
Mitch Phillipsb8e593d2019-10-09 17:18:59 -07001436 } else if len(diagSanitizers) > 0 || c.sanitize.Properties.UbsanRuntimeDep ||
Ivan Lozano9ac32c72020-02-19 15:24:02 -05001437 Bool(c.sanitize.Properties.Sanitize.Fuzzer) ||
1438 Bool(c.sanitize.Properties.Sanitize.Undefined) ||
1439 Bool(c.sanitize.Properties.Sanitize.All_undefined) {
Jiyong Park379de2f2018-12-19 02:47:14 +09001440 runtimeLibrary = config.UndefinedBehaviorSanitizerRuntimeLibrary(toolchain)
Colin Crosse725b4e2022-10-19 15:46:53 -07001441 if c.staticBinary() || toolchain.Musl() {
1442 // Use a static runtime for static binaries.
1443 // Also use a static runtime for musl to match
1444 // what clang does for glibc. Otherwise dlopening
1445 // libraries that depend on libclang_rt.ubsan_standalone.so
1446 // fails with:
1447 // Error relocating ...: initial-exec TLS resolves to dynamic definition
Colin Cross32f1de32021-03-29 13:41:37 -07001448 runtimeLibrary += ".static"
Colin Crosse725b4e2022-10-19 15:46:53 -07001449 alwaysStaticRuntime = true
Colin Cross32f1de32021-03-29 13:41:37 -07001450 }
Jiyong Park379de2f2018-12-19 02:47:14 +09001451 }
1452
Colin Cross06c80eb2022-02-10 10:34:19 -08001453 addStaticDeps := func(deps ...string) {
1454 // If we're using snapshots, redirect to snapshot whenever possible
1455 snapshot := mctx.Provider(SnapshotInfoProvider).(SnapshotInfo)
1456 for idx, dep := range deps {
1457 if lib, ok := snapshot.StaticLibs[dep]; ok {
1458 deps[idx] = lib
1459 }
1460 }
1461
1462 // static executable gets static runtime libs
Colin Cross3e5e7782022-06-17 22:17:05 +00001463 depTag := libraryDependencyTag{Kind: staticLibraryDependency, unexportedSymbols: true}
Colin Cross06c80eb2022-02-10 10:34:19 -08001464 variations := append(mctx.Target().Variations(),
1465 blueprint.Variation{Mutator: "link", Variation: "static"})
1466 if c.Device() {
1467 variations = append(variations, c.ImageVariation())
1468 }
1469 if c.UseSdk() {
1470 variations = append(variations,
1471 blueprint.Variation{Mutator: "sdk", Variation: "sdk"})
1472 }
1473 mctx.AddFarVariationDependencies(variations, depTag, deps...)
1474
1475 }
1476 if enableMinimalRuntime(c.sanitize) || c.sanitize.Properties.MinimalRuntimeDep {
1477 addStaticDeps(config.UndefinedBehaviorSanitizerMinimalRuntimeLibrary(toolchain))
1478 }
1479 if c.sanitize.Properties.BuiltinsDep {
1480 addStaticDeps(config.BuiltinsRuntimeLibrary(toolchain))
1481 }
1482
Colin Crossed12a042022-02-07 13:55:55 -08001483 if runtimeLibrary != "" && (toolchain.Bionic() || toolchain.Musl() || c.sanitize.Properties.UbsanRuntimeDep) {
Ivan Lozano9ac32c72020-02-19 15:24:02 -05001484 // UBSan is supported on non-bionic linux host builds as well
Jiyong Park379de2f2018-12-19 02:47:14 +09001485
1486 // Adding dependency to the runtime library. We are using *FarVariation*
1487 // because the runtime libraries themselves are not mutated by sanitizer
1488 // mutators and thus don't have sanitizer variants whereas this module
1489 // has been already mutated.
1490 //
1491 // Note that by adding dependency with {static|shared}DepTag, the lib is
1492 // added to libFlags and LOCAL_SHARED_LIBRARIES by cc.Module
Colin Crosse725b4e2022-10-19 15:46:53 -07001493 if c.staticBinary() || alwaysStaticRuntime {
Colin Cross06c80eb2022-02-10 10:34:19 -08001494 addStaticDeps(runtimeLibrary)
1495 addStaticDeps(extraStaticDeps...)
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001496 } else if !c.static() && !c.Header() {
Colin Crosse0edaf92021-01-11 17:31:17 -08001497 // If we're using snapshots, redirect to snapshot whenever possible
1498 snapshot := mctx.Provider(SnapshotInfoProvider).(SnapshotInfo)
1499 if lib, ok := snapshot.SharedLibs[runtimeLibrary]; ok {
1500 runtimeLibrary = lib
Inseob Kimeec88e12020-01-22 11:11:29 +09001501 }
Colin Crosse0edaf92021-01-11 17:31:17 -08001502
Cindy Zhou18417cb2020-12-10 07:12:38 -08001503 // Skip apex dependency check for sharedLibraryDependency
1504 // when sanitizer diags are enabled. Skipping the check will allow
1505 // building with diag libraries without having to list the
1506 // dependency in Apex's allowed_deps file.
1507 diagEnabled := len(diagSanitizers) > 0
Jiyong Park3b1746a2019-01-29 11:15:04 +09001508 // dynamic executable and shared libs get shared runtime libs
Cindy Zhou18417cb2020-12-10 07:12:38 -08001509 depTag := libraryDependencyTag{
1510 Kind: sharedLibraryDependency,
1511 Order: earlyLibraryDependency,
1512
1513 skipApexAllowedDependenciesCheck: diagEnabled,
1514 }
Colin Cross42507332020-08-21 16:15:23 -07001515 variations := append(mctx.Target().Variations(),
1516 blueprint.Variation{Mutator: "link", Variation: "shared"})
1517 if c.Device() {
1518 variations = append(variations, c.ImageVariation())
1519 }
Colin Cross06c80eb2022-02-10 10:34:19 -08001520 if c.UseSdk() {
1521 variations = append(variations,
1522 blueprint.Variation{Mutator: "sdk", Variation: "sdk"})
1523 }
Ivan Lozanod67a6b02021-05-20 13:01:32 -04001524 AddSharedLibDependenciesWithVersions(mctx, c, variations, depTag, runtimeLibrary, "", true)
Jiyong Park379de2f2018-12-19 02:47:14 +09001525 }
1526 // static lib does not have dependency to the runtime library. The
1527 // dependency will be added to the executables or shared libs using
1528 // the static lib.
1529 }
1530 }
1531}
1532
1533type Sanitizeable interface {
1534 android.Module
Lukacs T. Berki01a648a2022-06-17 08:59:37 +02001535 IsSanitizerEnabled(config android.Config, sanitizerName string) bool
Jiyong Parkf97782b2019-02-13 20:28:58 +09001536 EnableSanitizer(sanitizerName string)
Jooyung Han8ce8db92020-05-15 19:05:05 +09001537 AddSanitizerDependencies(ctx android.BottomUpMutatorContext, sanitizerName string)
Jiyong Park379de2f2018-12-19 02:47:14 +09001538}
1539
Muhammad Haseeb Ahmad7e744052022-03-25 22:50:53 +00001540type JniSanitizeable interface {
1541 android.Module
1542 IsSanitizerEnabledForJni(ctx android.BaseModuleContext, sanitizerName string) bool
1543}
1544
Ivan Lozanod7586b62021-04-01 09:49:36 -04001545func (c *Module) MinimalRuntimeDep() bool {
1546 return c.sanitize.Properties.MinimalRuntimeDep
1547}
1548
1549func (c *Module) UbsanRuntimeDep() bool {
1550 return c.sanitize.Properties.UbsanRuntimeDep
1551}
1552
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001553func (c *Module) SanitizePropDefined() bool {
1554 return c.sanitize != nil
1555}
1556
1557func (c *Module) IsSanitizerEnabled(t SanitizerType) bool {
1558 return c.sanitize.isSanitizerEnabled(t)
1559}
1560
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001561func (c *Module) StaticallyLinked() bool {
1562 return c.static()
1563}
1564
1565func (c *Module) SetInSanitizerDir() {
1566 if c.sanitize != nil {
1567 c.sanitize.Properties.InSanitizerDir = true
1568 }
1569}
1570
1571func (c *Module) SetSanitizer(t SanitizerType, b bool) {
1572 if c.sanitize != nil {
1573 c.sanitize.SetSanitizer(t, b)
1574 }
1575}
1576
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001577var _ PlatformSanitizeable = (*Module)(nil)
1578
Inseob Kim74d25562020-08-04 00:41:38 +09001579type sanitizerStaticLibsMap struct {
1580 // libsMap contains one list of modules per each image and each arch.
1581 // e.g. libs[vendor]["arm"] contains arm modules installed to vendor
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001582 libsMap map[ImageVariantType]map[string][]string
Inseob Kim74d25562020-08-04 00:41:38 +09001583 libsMapLock sync.Mutex
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001584 sanitizerType SanitizerType
Inseob Kim74d25562020-08-04 00:41:38 +09001585}
1586
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001587func newSanitizerStaticLibsMap(t SanitizerType) *sanitizerStaticLibsMap {
Inseob Kim74d25562020-08-04 00:41:38 +09001588 return &sanitizerStaticLibsMap{
1589 sanitizerType: t,
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001590 libsMap: make(map[ImageVariantType]map[string][]string),
Inseob Kim74d25562020-08-04 00:41:38 +09001591 }
1592}
1593
1594// Add the current module to sanitizer static libs maps
1595// Each module should pass its exported name as names of Make and Soong can differ.
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001596func (s *sanitizerStaticLibsMap) add(c LinkableInterface, name string) {
1597 image := GetImageVariantType(c)
1598 arch := c.Module().Target().Arch.ArchType.String()
Inseob Kim74d25562020-08-04 00:41:38 +09001599
1600 s.libsMapLock.Lock()
1601 defer s.libsMapLock.Unlock()
1602
1603 if _, ok := s.libsMap[image]; !ok {
1604 s.libsMap[image] = make(map[string][]string)
1605 }
1606
1607 s.libsMap[image][arch] = append(s.libsMap[image][arch], name)
1608}
1609
1610// Exports makefile variables in the following format:
1611// SOONG_{sanitizer}_{image}_{arch}_STATIC_LIBRARIES
1612// e.g. SOONG_cfi_core_x86_STATIC_LIBRARIES
1613// These are to be used by use_soong_sanitized_static_libraries.
1614// See build/make/core/binary.mk for more details.
1615func (s *sanitizerStaticLibsMap) exportToMake(ctx android.MakeVarsContext) {
1616 for _, image := range android.SortedStringKeys(s.libsMap) {
Ivan Lozano3968d8f2020-12-14 11:27:52 -05001617 archMap := s.libsMap[ImageVariantType(image)]
Inseob Kim74d25562020-08-04 00:41:38 +09001618 for _, arch := range android.SortedStringKeys(archMap) {
1619 libs := archMap[arch]
1620 sort.Strings(libs)
1621
1622 key := fmt.Sprintf(
1623 "SOONG_%s_%s_%s_STATIC_LIBRARIES",
1624 s.sanitizerType.variationName(),
1625 image, // already upper
1626 arch)
1627
1628 ctx.Strict(key, strings.Join(libs, " "))
1629 }
1630 }
1631}
1632
Colin Cross571cccf2019-02-04 11:22:08 -08001633var cfiStaticLibsKey = android.NewOnceKey("cfiStaticLibs")
1634
Inseob Kim74d25562020-08-04 00:41:38 +09001635func cfiStaticLibs(config android.Config) *sanitizerStaticLibsMap {
Colin Cross571cccf2019-02-04 11:22:08 -08001636 return config.Once(cfiStaticLibsKey, func() interface{} {
Inseob Kim74d25562020-08-04 00:41:38 +09001637 return newSanitizerStaticLibsMap(cfi)
1638 }).(*sanitizerStaticLibsMap)
Vishwath Mohane7128792017-11-17 11:08:10 -08001639}
1640
Colin Cross571cccf2019-02-04 11:22:08 -08001641var hwasanStaticLibsKey = android.NewOnceKey("hwasanStaticLibs")
1642
Inseob Kim74d25562020-08-04 00:41:38 +09001643func hwasanStaticLibs(config android.Config) *sanitizerStaticLibsMap {
Colin Cross571cccf2019-02-04 11:22:08 -08001644 return config.Once(hwasanStaticLibsKey, func() interface{} {
Tri Vo6eafc362021-04-01 11:29:09 -07001645 return newSanitizerStaticLibsMap(Hwasan)
Inseob Kim74d25562020-08-04 00:41:38 +09001646 }).(*sanitizerStaticLibsMap)
Jiyong Park1d1119f2019-07-29 21:27:18 +09001647}
1648
Ivan Lozano30c5db22018-02-21 15:49:20 -08001649func enableMinimalRuntime(sanitize *sanitize) bool {
1650 if !Bool(sanitize.Properties.Sanitize.Address) &&
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -07001651 !Bool(sanitize.Properties.Sanitize.Hwaddress) &&
Mitch Phillips5a6ea6c2019-05-01 14:42:05 -07001652 !Bool(sanitize.Properties.Sanitize.Fuzzer) &&
Ivan Lozano30c5db22018-02-21 15:49:20 -08001653 (Bool(sanitize.Properties.Sanitize.Integer_overflow) ||
Ivan Lozano9ac32c72020-02-19 15:24:02 -05001654 len(sanitize.Properties.Sanitize.Misc_undefined) > 0 ||
1655 Bool(sanitize.Properties.Sanitize.Undefined) ||
1656 Bool(sanitize.Properties.Sanitize.All_undefined)) &&
Ivan Lozano30c5db22018-02-21 15:49:20 -08001657 !(Bool(sanitize.Properties.Sanitize.Diag.Integer_overflow) ||
1658 Bool(sanitize.Properties.Sanitize.Diag.Cfi) ||
Ivan Lozano9ac32c72020-02-19 15:24:02 -05001659 Bool(sanitize.Properties.Sanitize.Diag.Undefined) ||
Ivan Lozano30c5db22018-02-21 15:49:20 -08001660 len(sanitize.Properties.Sanitize.Diag.Misc_undefined) > 0) {
Ivan Lozano9ac32c72020-02-19 15:24:02 -05001661
Ivan Lozano30c5db22018-02-21 15:49:20 -08001662 return true
1663 }
1664 return false
1665}
1666
Ivan Lozanod7586b62021-04-01 09:49:36 -04001667func (m *Module) UbsanRuntimeNeeded() bool {
1668 return enableUbsanRuntime(m.sanitize)
1669}
1670
1671func (m *Module) MinimalRuntimeNeeded() bool {
1672 return enableMinimalRuntime(m.sanitize)
1673}
1674
Inseob Kim8471cda2019-11-15 09:59:12 +09001675func enableUbsanRuntime(sanitize *sanitize) bool {
1676 return Bool(sanitize.Properties.Sanitize.Diag.Integer_overflow) ||
Ivan Lozano9ac32c72020-02-19 15:24:02 -05001677 Bool(sanitize.Properties.Sanitize.Diag.Undefined) ||
Inseob Kim8471cda2019-11-15 09:59:12 +09001678 len(sanitize.Properties.Sanitize.Diag.Misc_undefined) > 0
1679}
1680
Vishwath Mohane7128792017-11-17 11:08:10 -08001681func cfiMakeVarsProvider(ctx android.MakeVarsContext) {
Inseob Kim74d25562020-08-04 00:41:38 +09001682 cfiStaticLibs(ctx.Config()).exportToMake(ctx)
Vishwath Mohane7128792017-11-17 11:08:10 -08001683}
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -07001684
1685func hwasanMakeVarsProvider(ctx android.MakeVarsContext) {
Inseob Kim74d25562020-08-04 00:41:38 +09001686 hwasanStaticLibs(ctx.Config()).exportToMake(ctx)
Evgenii Stepanovd97a6e92018-08-02 16:19:13 -07001687}