aboutsummaryrefslogtreecommitdiffstats
path: root/cc/sanitize.go
blob: 670443bff5959951c934bb42cb16636b9cce4432 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cc

import (
	"fmt"
	"strings"

	"github.com/google/blueprint"

	"android/soong/common"
)

type sanitizerType int

func init() {
	pctx.StaticVariable("clangAsanLibDir", "${clangPath}/lib64/clang/3.8/lib/linux")
}

const (
	asan sanitizerType = iota + 1
	tsan
)

func (t sanitizerType) String() string {
	switch t {
	case asan:
		return "asan"
	case tsan:
		return "tsan"
	default:
		panic(fmt.Errorf("unknown sanitizerType %d", t))
	}
}

type SanitizeProperties struct {
	// enable AddressSanitizer, ThreadSanitizer, or UndefinedBehaviorSanitizer
	Sanitize struct {
		Never bool `android:"arch_variant"`

		// main sanitizers
		Address bool `android:"arch_variant"`
		Thread  bool `android:"arch_variant"`

		// local sanitizers
		Undefined      bool     `android:"arch_variant"`
		All_undefined  bool     `android:"arch_variant"`
		Misc_undefined []string `android:"arch_variant"`
		Coverage       bool     `android:"arch_variant"`

		// value to pass to -fsantitize-recover=
		Recover []string

		// value to pass to -fsanitize-blacklist
		Blacklist *string
	} `android:"arch_variant"`

	SanitizerEnabled bool `blueprint:"mutated"`
	SanitizeDep      bool `blueprint:"mutated"`
	InData           bool `blueprint:"mutated"`
}

type sanitize struct {
	Properties SanitizeProperties
}

func (sanitize *sanitize) props() []interface{} {
	return []interface{}{&sanitize.Properties}
}

func (sanitize *sanitize) begin(ctx BaseModuleContext) {
	// Don't apply sanitizers to NDK code.
	if ctx.sdk() {
		sanitize.Properties.Sanitize.Never = true
	}

	// Never always wins.
	if sanitize.Properties.Sanitize.Never {
		return
	}

	if ctx.ContainsProperty("sanitize") {
		sanitize.Properties.SanitizerEnabled = true
	}

	var globalSanitizers []string
	if ctx.clang() {
		if ctx.Host() {
			globalSanitizers = ctx.AConfig().SanitizeHost()
		} else {
			globalSanitizers = ctx.AConfig().SanitizeDevice()
		}
	}

	// The sanitizer specified by the environment wins over the module.
	if len(globalSanitizers) > 0 {
		// wipe the enabled sanitizers
		sanitize.Properties = SanitizeProperties{}
		var found bool
		if found, globalSanitizers = removeFromList("undefined", globalSanitizers); found {
			sanitize.Properties.Sanitize.All_undefined = true
		} else if found, globalSanitizers = removeFromList("default-ub", globalSanitizers); found {
			sanitize.Properties.Sanitize.Undefined = true
		}

		if found, globalSanitizers = removeFromList("address", globalSanitizers); found {
			sanitize.Properties.Sanitize.Address = true
		}

		if found, globalSanitizers = removeFromList("thread", globalSanitizers); found {
			sanitize.Properties.Sanitize.Thread = true
		}

		if found, globalSanitizers = removeFromList("coverage", globalSanitizers); found {
			sanitize.Properties.Sanitize.Coverage = true
		}

		if len(globalSanitizers) > 0 {
			ctx.ModuleErrorf("unknown global sanitizer option %s", globalSanitizers[0])
		}
		sanitize.Properties.SanitizerEnabled = true
	}

	if !ctx.toolchain().Is64Bit() && sanitize.Properties.Sanitize.Thread {
		// TSAN is not supported on 32-bit architectures
		sanitize.Properties.Sanitize.Thread = false
		// TODO(ccross): error for compile_multilib = "32"?
	}

	if sanitize.Properties.Sanitize.Coverage {
		if !sanitize.Properties.Sanitize.Address {
			ctx.ModuleErrorf(`Use of "coverage" also requires "address"`)
		}
	}
}

func (sanitize *sanitize) deps(ctx BaseModuleContext, deps Deps) Deps {
	if !sanitize.Properties.SanitizerEnabled { // || c.static() {
		return deps
	}

	if ctx.Device() {
		deps.SharedLibs = append(deps.SharedLibs, "libdl")
		if sanitize.Properties.Sanitize.Address {
			deps.StaticLibs = append(deps.StaticLibs, "libasan")
		}
	}

	return deps
}

func (sanitize *sanitize) flags(ctx ModuleContext, flags Flags) Flags {
	if !sanitize.Properties.SanitizerEnabled {
		return flags
	}

	if !ctx.clang() {
		ctx.ModuleErrorf("Use of sanitizers requires clang")
	}

	var sanitizers []string

	if sanitize.Properties.Sanitize.All_undefined {
		sanitizers = append(sanitizers, "undefined")
		if ctx.Device() {
			ctx.ModuleErrorf("ubsan is not yet supported on the device")
		}
	} else {
		if sanitize.Properties.Sanitize.Undefined {
			sanitizers = append(sanitizers,
				"bool",
				"integer-divide-by-zero",
				"return",
				"returns-nonnull-attribute",
				"shift-exponent",
				"unreachable",
				"vla-bound",
				// TODO(danalbert): The following checks currently have compiler performance issues.
				//"alignment",
				//"bounds",
				//"enum",
				//"float-cast-overflow",
				//"float-divide-by-zero",
				//"nonnull-attribute",
				//"null",
				//"shift-base",
				//"signed-integer-overflow",
				// TODO(danalbert): Fix UB in libc++'s __tree so we can turn this on.
				// https://llvm.org/PR19302
				// http://reviews.llvm.org/D6974
				// "object-size",
			)
		}
		sanitizers = append(sanitizers, sanitize.Properties.Sanitize.Misc_undefined...)
	}

	if sanitize.Properties.Sanitize.Address {
		if ctx.Arch().ArchType == common.Arm {
			// Frame pointer based unwinder in ASan requires ARM frame setup.
			// TODO: put in flags?
			flags.RequiredInstructionSet = "arm"
		}
		flags.CFlags = append(flags.CFlags, "-fno-omit-frame-pointer")
		flags.LdFlags = append(flags.LdFlags, "-Wl,-u,__asan_preinit")

		// ASan runtime library must be the first in the link order.
		runtimeLibrary := ctx.toolchain().AddressSanitizerRuntimeLibrary()
		if runtimeLibrary != "" {
			flags.libFlags = append([]string{"${clangAsanLibDir}/" + runtimeLibrary}, flags.libFlags...)
		}
		if ctx.Host() {
			// -nodefaultlibs (provided with libc++) prevents the driver from linking
			// libraries needed with -fsanitize=address. http://b/18650275 (WAI)
			flags.LdFlags = append(flags.LdFlags, "-lm", "-lpthread")
			flags.LdFlags = append(flags.LdFlags, "-Wl,--no-as-needed")
		} else {
			flags.CFlags = append(flags.CFlags, "-mllvm", "-asan-globals=0")
			flags.DynamicLinker = "/system/bin/linker_asan"
			if flags.Toolchain.Is64Bit() {
				flags.DynamicLinker += "64"
			}
		}
		sanitizers = append(sanitizers, "address")
	}

	if sanitize.Properties.Sanitize.Coverage {
		flags.CFlags = append(flags.CFlags, "-fsanitize-coverage=edge,indirect-calls,8bit-counters,trace-cmp")
	}

	if sanitize.Properties.Sanitize.Recover != nil {
		flags.CFlags = append(flags.CFlags, "-fsanitize-recover="+
			strings.Join(sanitize.Properties.Sanitize.Recover, ","))
	}

	if len(sanitizers) > 0 {
		sanitizeArg := "-fsanitize=" + strings.Join(sanitizers, ",")
		flags.CFlags = append(flags.CFlags, sanitizeArg)
		if ctx.Host() {
			flags.CFlags = append(flags.CFlags, "-fno-sanitize-recover=all")
			flags.LdFlags = append(flags.LdFlags, sanitizeArg)
			flags.LdFlags = append(flags.LdFlags, "-lrt", "-ldl")
		} else {
			if !sanitize.Properties.Sanitize.Address {
				flags.CFlags = append(flags.CFlags, "-fsanitize-trap=all", "-ftrap-function=abort")
			}
		}
	}

	blacklist := common.OptionalPathForModuleSrc(ctx, sanitize.Properties.Sanitize.Blacklist)
	if blacklist.Valid() {
		flags.CFlags = append(flags.CFlags, "-fsanitize-blacklist="+blacklist.String())
		flags.CFlagsDeps = append(flags.CFlagsDeps, blacklist.Path())
	}

	return flags
}

func (sanitize *sanitize) inData() bool {
	return sanitize.Properties.InData
}

func (sanitize *sanitize) Sanitizer(t sanitizerType) bool {
	if sanitize == nil {
		return false
	}

	switch t {
	case asan:
		return sanitize.Properties.Sanitize.Address
	case tsan:
		return sanitize.Properties.Sanitize.Thread
	default:
		panic(fmt.Errorf("unknown sanitizerType %d", t))
	}
}

func (sanitize *sanitize) SetSanitizer(t sanitizerType, b bool) {
	switch t {
	case asan:
		sanitize.Properties.Sanitize.Address = b
	case tsan:
		sanitize.Properties.Sanitize.Thread = b
	default:
		panic(fmt.Errorf("unknown sanitizerType %d", t))
	}
	if b {
		sanitize.Properties.SanitizerEnabled = true
	}
}

// Propagate asan requirements down from binaries
func sanitizerDepsMutator(t sanitizerType) func(common.AndroidTopDownMutatorContext) {
	return func(mctx common.AndroidTopDownMutatorContext) {
		if c, ok := mctx.Module().(*Module); ok && c.sanitize.Sanitizer(t) {
			mctx.VisitDepsDepthFirst(func(module blueprint.Module) {
				if d, ok := mctx.Module().(*Module); ok && c.sanitize != nil &&
					!c.sanitize.Properties.Sanitize.Never {
					d.sanitize.Properties.SanitizeDep = true
				}
			})
		}
	}
}

// Create asan variants for modules that need them
func sanitizerMutator(t sanitizerType) func(common.AndroidBottomUpMutatorContext) {
	return func(mctx common.AndroidBottomUpMutatorContext) {
		if c, ok := mctx.Module().(*Module); ok && c.sanitize != nil {
			if d, ok := c.linker.(baseLinkerInterface); ok && d.isDependencyRoot() && c.sanitize.Sanitizer(t) {
				modules := mctx.CreateVariations(t.String())
				modules[0].(*Module).sanitize.SetSanitizer(t, true)
				if mctx.AConfig().EmbeddedInMake() {
					modules[0].(*Module).sanitize.Properties.InData = true
				}
			} else if c.sanitize.Properties.SanitizeDep {
				if mctx.AConfig().EmbeddedInMake() {
					modules := mctx.CreateVariations(t.String())
					modules[0].(*Module).sanitize.SetSanitizer(t, true)
					modules[0].(*Module).sanitize.Properties.InData = true
				} else {
					modules := mctx.CreateVariations("", t.String())
					modules[0].(*Module).sanitize.SetSanitizer(t, false)
					modules[1].(*Module).sanitize.SetSanitizer(t, true)
					modules[1].(*Module).appendVariantName("_" + t.String())
					modules[0].(*Module).sanitize.Properties.SanitizeDep = false
					modules[1].(*Module).sanitize.Properties.SanitizeDep = false
				}
			}
			c.sanitize.Properties.SanitizeDep = false
		}
	}
}