sanitize.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. // Copyright 2020 The Android Open Source Project
  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. package rust
  15. import (
  16. "fmt"
  17. "strings"
  18. "github.com/google/blueprint"
  19. "github.com/google/blueprint/proptools"
  20. "android/soong/android"
  21. "android/soong/cc"
  22. "android/soong/rust/config"
  23. )
  24. // TODO: When Rust has sanitizer-parity with CC, deduplicate this struct
  25. type SanitizeProperties struct {
  26. // enable AddressSanitizer, HWAddressSanitizer, and others.
  27. Sanitize struct {
  28. Address *bool `android:"arch_variant"`
  29. Hwaddress *bool `android:"arch_variant"`
  30. // Memory-tagging, only available on arm64
  31. // if diag.memtag unset or false, enables async memory tagging
  32. Memtag_heap *bool `android:"arch_variant"`
  33. Fuzzer *bool `android:"arch_variant"`
  34. Never *bool `android:"arch_variant"`
  35. // Sanitizers to run in the diagnostic mode (as opposed to the release mode).
  36. // Replaces abort() on error with a human-readable error message.
  37. // Address and Thread sanitizers always run in diagnostic mode.
  38. Diag struct {
  39. // Memory-tagging, only available on arm64
  40. // requires sanitizer.memtag: true
  41. // if set, enables sync memory tagging
  42. Memtag_heap *bool `android:"arch_variant"`
  43. }
  44. }
  45. SanitizerEnabled bool `blueprint:"mutated"`
  46. // Used when we need to place libraries in their own directory, such as ASAN.
  47. InSanitizerDir bool `blueprint:"mutated"`
  48. }
  49. var fuzzerFlags = []string{
  50. "-C passes='sancov-module'",
  51. "--cfg fuzzing",
  52. "-C llvm-args=-sanitizer-coverage-level=3",
  53. "-C llvm-args=-sanitizer-coverage-trace-compares",
  54. "-C llvm-args=-sanitizer-coverage-inline-8bit-counters",
  55. "-C llvm-args=-sanitizer-coverage-pc-table",
  56. // See https://github.com/rust-fuzz/cargo-fuzz/pull/193
  57. "-C link-dead-code",
  58. // Sancov breaks with lto
  59. // TODO: Remove when https://bugs.llvm.org/show_bug.cgi?id=41734 is resolved and sancov-module works with LTO
  60. "-C lto=no",
  61. }
  62. var asanFlags = []string{
  63. "-Z sanitizer=address",
  64. }
  65. // See cc/sanitize.go's hwasanGlobalOptions for global hwasan options.
  66. var hwasanFlags = []string{
  67. "-Z sanitizer=hwaddress",
  68. "-C target-feature=+tagged-globals",
  69. // Flags from cc/sanitize.go hwasanFlags
  70. "-C llvm-args=--aarch64-enable-global-isel-at-O=-1",
  71. "-C llvm-args=-fast-isel=false",
  72. "-C llvm-args=-instcombine-lower-dbg-declare=0",
  73. // Additional flags for HWASAN-ified Rust/C interop
  74. "-C llvm-args=--hwasan-with-ifunc",
  75. }
  76. func boolPtr(v bool) *bool {
  77. if v {
  78. return &v
  79. } else {
  80. return nil
  81. }
  82. }
  83. func init() {
  84. }
  85. func (sanitize *sanitize) props() []interface{} {
  86. return []interface{}{&sanitize.Properties}
  87. }
  88. func (sanitize *sanitize) begin(ctx BaseModuleContext) {
  89. s := &sanitize.Properties.Sanitize
  90. // Never always wins.
  91. if Bool(s.Never) {
  92. return
  93. }
  94. // rust_test targets default to SYNC MemTag unless explicitly set to ASYNC (via diag: {Memtag_heap}).
  95. if binary, ok := ctx.RustModule().compiler.(binaryInterface); ok && binary.testBinary() {
  96. if s.Memtag_heap == nil {
  97. s.Memtag_heap = proptools.BoolPtr(true)
  98. }
  99. if s.Diag.Memtag_heap == nil {
  100. s.Diag.Memtag_heap = proptools.BoolPtr(true)
  101. }
  102. }
  103. var globalSanitizers []string
  104. var globalSanitizersDiag []string
  105. if ctx.Host() {
  106. if !ctx.Windows() {
  107. globalSanitizers = ctx.Config().SanitizeHost()
  108. }
  109. } else {
  110. arches := ctx.Config().SanitizeDeviceArch()
  111. if len(arches) == 0 || android.InList(ctx.Arch().ArchType.Name, arches) {
  112. globalSanitizers = ctx.Config().SanitizeDevice()
  113. globalSanitizersDiag = ctx.Config().SanitizeDeviceDiag()
  114. }
  115. }
  116. if len(globalSanitizers) > 0 {
  117. var found bool
  118. // Global Sanitizers
  119. if found, globalSanitizers = android.RemoveFromList("hwaddress", globalSanitizers); found && s.Hwaddress == nil {
  120. // TODO(b/204776996): HWASan for static Rust binaries isn't supported yet.
  121. if !ctx.RustModule().StaticExecutable() {
  122. s.Hwaddress = proptools.BoolPtr(true)
  123. }
  124. }
  125. if found, globalSanitizers = android.RemoveFromList("memtag_heap", globalSanitizers); found && s.Memtag_heap == nil {
  126. if !ctx.Config().MemtagHeapDisabledForPath(ctx.ModuleDir()) {
  127. s.Memtag_heap = proptools.BoolPtr(true)
  128. }
  129. }
  130. if found, globalSanitizers = android.RemoveFromList("address", globalSanitizers); found && s.Address == nil {
  131. s.Address = proptools.BoolPtr(true)
  132. }
  133. if found, globalSanitizers = android.RemoveFromList("fuzzer", globalSanitizers); found && s.Fuzzer == nil {
  134. // TODO(b/204776996): HWASan for static Rust binaries isn't supported yet, and fuzzer enables HWAsan
  135. if !ctx.RustModule().StaticExecutable() {
  136. s.Fuzzer = proptools.BoolPtr(true)
  137. }
  138. }
  139. // Global Diag Sanitizers
  140. if found, globalSanitizersDiag = android.RemoveFromList("memtag_heap", globalSanitizersDiag); found &&
  141. s.Diag.Memtag_heap == nil && Bool(s.Memtag_heap) {
  142. s.Diag.Memtag_heap = proptools.BoolPtr(true)
  143. }
  144. }
  145. // Enable Memtag for all components in the include paths (for Aarch64 only)
  146. if ctx.Arch().ArchType == android.Arm64 && ctx.Os().Bionic() {
  147. if ctx.Config().MemtagHeapSyncEnabledForPath(ctx.ModuleDir()) {
  148. if s.Memtag_heap == nil {
  149. s.Memtag_heap = proptools.BoolPtr(true)
  150. }
  151. if s.Diag.Memtag_heap == nil {
  152. s.Diag.Memtag_heap = proptools.BoolPtr(true)
  153. }
  154. } else if ctx.Config().MemtagHeapAsyncEnabledForPath(ctx.ModuleDir()) {
  155. if s.Memtag_heap == nil {
  156. s.Memtag_heap = proptools.BoolPtr(true)
  157. }
  158. }
  159. }
  160. // HWASan requires AArch64 hardware feature (top-byte-ignore).
  161. if ctx.Arch().ArchType != android.Arm64 || !ctx.Os().Bionic() {
  162. s.Hwaddress = nil
  163. }
  164. // HWASan ramdisk (which is built from recovery) goes over some bootloader limit.
  165. // Keep libc instrumented so that ramdisk / vendor_ramdisk / recovery can run hwasan-instrumented code if necessary.
  166. if (ctx.RustModule().InRamdisk() || ctx.RustModule().InVendorRamdisk() || ctx.RustModule().InRecovery()) && !strings.HasPrefix(ctx.ModuleDir(), "bionic/libc") {
  167. s.Hwaddress = nil
  168. }
  169. if Bool(s.Hwaddress) {
  170. s.Address = nil
  171. }
  172. // Memtag_heap is only implemented on AArch64.
  173. if ctx.Arch().ArchType != android.Arm64 || !ctx.Os().Bionic() {
  174. s.Memtag_heap = nil
  175. }
  176. // TODO:(b/178369775)
  177. // For now sanitizing is only supported on devices
  178. if ctx.Os() == android.Android && (Bool(s.Hwaddress) || Bool(s.Address) || Bool(s.Memtag_heap) || Bool(s.Fuzzer)) {
  179. sanitize.Properties.SanitizerEnabled = true
  180. }
  181. }
  182. type sanitize struct {
  183. Properties SanitizeProperties
  184. }
  185. func (sanitize *sanitize) flags(ctx ModuleContext, flags Flags, deps PathDeps) (Flags, PathDeps) {
  186. if !sanitize.Properties.SanitizerEnabled {
  187. return flags, deps
  188. }
  189. if Bool(sanitize.Properties.Sanitize.Fuzzer) {
  190. flags.RustFlags = append(flags.RustFlags, fuzzerFlags...)
  191. } else if Bool(sanitize.Properties.Sanitize.Hwaddress) {
  192. flags.RustFlags = append(flags.RustFlags, hwasanFlags...)
  193. } else if Bool(sanitize.Properties.Sanitize.Address) {
  194. flags.RustFlags = append(flags.RustFlags, asanFlags...)
  195. }
  196. return flags, deps
  197. }
  198. func (sanitize *sanitize) deps(ctx BaseModuleContext, deps Deps) Deps {
  199. return deps
  200. }
  201. func rustSanitizerRuntimeMutator(mctx android.BottomUpMutatorContext) {
  202. if mod, ok := mctx.Module().(*Module); ok && mod.sanitize != nil {
  203. if !mod.Enabled() {
  204. return
  205. }
  206. if Bool(mod.sanitize.Properties.Sanitize.Memtag_heap) && mod.Binary() {
  207. noteDep := "note_memtag_heap_async"
  208. if Bool(mod.sanitize.Properties.Sanitize.Diag.Memtag_heap) {
  209. noteDep = "note_memtag_heap_sync"
  210. }
  211. // If we're using snapshots, redirect to snapshot whenever possible
  212. // TODO(b/178470649): clean manual snapshot redirections
  213. snapshot := mctx.Provider(cc.SnapshotInfoProvider).(cc.SnapshotInfo)
  214. if lib, ok := snapshot.StaticLibs[noteDep]; ok {
  215. noteDep = lib
  216. }
  217. depTag := cc.StaticDepTag(true)
  218. variations := append(mctx.Target().Variations(),
  219. blueprint.Variation{Mutator: "link", Variation: "static"})
  220. if mod.Device() {
  221. variations = append(variations, mod.ImageVariation())
  222. }
  223. mctx.AddFarVariationDependencies(variations, depTag, noteDep)
  224. }
  225. variations := mctx.Target().Variations()
  226. var depTag blueprint.DependencyTag
  227. var deps []string
  228. if mod.IsSanitizerEnabled(cc.Asan) ||
  229. (mod.IsSanitizerEnabled(cc.Fuzzer) && (mctx.Arch().ArchType != android.Arm64 || !mctx.Os().Bionic())) {
  230. variations = append(variations,
  231. blueprint.Variation{Mutator: "link", Variation: "shared"})
  232. depTag = cc.SharedDepTag()
  233. deps = []string{config.LibclangRuntimeLibrary(mod.toolchain(mctx), "asan")}
  234. } else if mod.IsSanitizerEnabled(cc.Hwasan) ||
  235. (mod.IsSanitizerEnabled(cc.Fuzzer) && mctx.Arch().ArchType == android.Arm64 && mctx.Os().Bionic()) {
  236. // TODO(b/204776996): HWASan for static Rust binaries isn't supported yet.
  237. if binary, ok := mod.compiler.(binaryInterface); ok {
  238. if binary.staticallyLinked() {
  239. mctx.ModuleErrorf("HWASan is not supported for static Rust executables yet.")
  240. }
  241. }
  242. // Always link against the shared library -- static binaries will pull in the static
  243. // library during final link if necessary
  244. variations = append(variations,
  245. blueprint.Variation{Mutator: "link", Variation: "shared"})
  246. depTag = cc.SharedDepTag()
  247. deps = []string{config.LibclangRuntimeLibrary(mod.toolchain(mctx), "hwasan")}
  248. }
  249. if len(deps) > 0 {
  250. mctx.AddFarVariationDependencies(variations, depTag, deps...)
  251. }
  252. }
  253. }
  254. func (sanitize *sanitize) SetSanitizer(t cc.SanitizerType, b bool) {
  255. sanitizerSet := false
  256. switch t {
  257. case cc.Fuzzer:
  258. sanitize.Properties.Sanitize.Fuzzer = boolPtr(b)
  259. sanitizerSet = true
  260. case cc.Asan:
  261. sanitize.Properties.Sanitize.Address = boolPtr(b)
  262. sanitizerSet = true
  263. case cc.Hwasan:
  264. sanitize.Properties.Sanitize.Hwaddress = boolPtr(b)
  265. sanitizerSet = true
  266. case cc.Memtag_heap:
  267. sanitize.Properties.Sanitize.Memtag_heap = boolPtr(b)
  268. sanitizerSet = true
  269. default:
  270. panic(fmt.Errorf("setting unsupported sanitizerType %d", t))
  271. }
  272. if b && sanitizerSet {
  273. sanitize.Properties.SanitizerEnabled = true
  274. }
  275. }
  276. func (m *Module) UbsanRuntimeNeeded() bool {
  277. return false
  278. }
  279. func (m *Module) MinimalRuntimeNeeded() bool {
  280. return false
  281. }
  282. func (m *Module) UbsanRuntimeDep() bool {
  283. return false
  284. }
  285. func (m *Module) MinimalRuntimeDep() bool {
  286. return false
  287. }
  288. // Check if the sanitizer is explicitly disabled (as opposed to nil by
  289. // virtue of not being set).
  290. func (sanitize *sanitize) isSanitizerExplicitlyDisabled(t cc.SanitizerType) bool {
  291. if sanitize == nil {
  292. return false
  293. }
  294. if Bool(sanitize.Properties.Sanitize.Never) {
  295. return true
  296. }
  297. sanitizerVal := sanitize.getSanitizerBoolPtr(t)
  298. return sanitizerVal != nil && *sanitizerVal == false
  299. }
  300. // There isn't an analog of the method above (ie:isSanitizerExplicitlyEnabled)
  301. // because enabling a sanitizer either directly (via the blueprint) or
  302. // indirectly (via a mutator) sets the bool ptr to true, and you can't
  303. // distinguish between the cases. It isn't needed though - both cases can be
  304. // treated identically.
  305. func (sanitize *sanitize) isSanitizerEnabled(t cc.SanitizerType) bool {
  306. if sanitize == nil || !sanitize.Properties.SanitizerEnabled {
  307. return false
  308. }
  309. sanitizerVal := sanitize.getSanitizerBoolPtr(t)
  310. return sanitizerVal != nil && *sanitizerVal == true
  311. }
  312. func (sanitize *sanitize) getSanitizerBoolPtr(t cc.SanitizerType) *bool {
  313. switch t {
  314. case cc.Fuzzer:
  315. return sanitize.Properties.Sanitize.Fuzzer
  316. case cc.Asan:
  317. return sanitize.Properties.Sanitize.Address
  318. case cc.Hwasan:
  319. return sanitize.Properties.Sanitize.Hwaddress
  320. case cc.Memtag_heap:
  321. return sanitize.Properties.Sanitize.Memtag_heap
  322. default:
  323. return nil
  324. }
  325. }
  326. func (sanitize *sanitize) AndroidMk(ctx AndroidMkContext, entries *android.AndroidMkEntries) {
  327. // Add a suffix for hwasan rlib libraries to allow surfacing both the sanitized and
  328. // non-sanitized variants to make without a name conflict.
  329. if entries.Class == "RLIB_LIBRARIES" || entries.Class == "STATIC_LIBRARIES" {
  330. if sanitize.isSanitizerEnabled(cc.Hwasan) {
  331. entries.SubName += ".hwasan"
  332. }
  333. }
  334. }
  335. func (mod *Module) SanitizerSupported(t cc.SanitizerType) bool {
  336. if mod.Host() {
  337. return false
  338. }
  339. switch t {
  340. case cc.Fuzzer:
  341. return true
  342. case cc.Asan:
  343. return true
  344. case cc.Hwasan:
  345. // TODO(b/180495975): HWASan for static Rust binaries isn't supported yet.
  346. if mod.StaticExecutable() {
  347. return false
  348. }
  349. return true
  350. case cc.Memtag_heap:
  351. return true
  352. default:
  353. return false
  354. }
  355. }
  356. func (mod *Module) IsSanitizerEnabled(t cc.SanitizerType) bool {
  357. return mod.sanitize.isSanitizerEnabled(t)
  358. }
  359. func (mod *Module) IsSanitizerExplicitlyDisabled(t cc.SanitizerType) bool {
  360. if mod.Host() {
  361. return true
  362. }
  363. return mod.sanitize.isSanitizerExplicitlyDisabled(t)
  364. }
  365. func (mod *Module) SetSanitizer(t cc.SanitizerType, b bool) {
  366. if !Bool(mod.sanitize.Properties.Sanitize.Never) {
  367. mod.sanitize.SetSanitizer(t, b)
  368. }
  369. }
  370. func (mod *Module) StaticallyLinked() bool {
  371. if lib, ok := mod.compiler.(libraryInterface); ok {
  372. return lib.rlib() || lib.static()
  373. } else if binary, ok := mod.compiler.(binaryInterface); ok {
  374. return binary.staticallyLinked()
  375. }
  376. return false
  377. }
  378. func (mod *Module) SetInSanitizerDir() {
  379. mod.sanitize.Properties.InSanitizerDir = true
  380. }
  381. func (mod *Module) SanitizeNever() bool {
  382. return Bool(mod.sanitize.Properties.Sanitize.Never)
  383. }
  384. var _ cc.PlatformSanitizeable = (*Module)(nil)
  385. func IsSanitizableDependencyTag(tag blueprint.DependencyTag) bool {
  386. switch t := tag.(type) {
  387. case dependencyTag:
  388. return t.library
  389. default:
  390. return cc.IsSanitizableDependencyTag(tag)
  391. }
  392. }
  393. func (m *Module) SanitizableDepTagChecker() cc.SantizableDependencyTagChecker {
  394. return IsSanitizableDependencyTag
  395. }