1// Copyright 2017 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 "strconv" 19 20 "github.com/google/blueprint" 21 22 "android/soong/android" 23) 24 25var ( 26 clangCoverageHostLdFlags = []string{ 27 "-Wl,--no-as-needed", 28 "-Wl,--wrap,open", 29 } 30 clangContinuousCoverageFlags = []string{ 31 "-mllvm", 32 "-runtime-counter-relocation", 33 } 34 clangCoverageCFlags = []string{ 35 "-Wno-frame-larger-than=", 36 } 37 clangCoverageCommonFlags = []string{ 38 "-fcoverage-mapping", 39 "-Wno-pass-failed", 40 "-D__ANDROID_CLANG_COVERAGE__", 41 } 42 clangCoverageHWASanFlags = []string{ 43 "-mllvm", 44 "-hwasan-globals=0", 45 } 46) 47 48const profileInstrFlag = "-fprofile-instr-generate=/data/misc/trace/clang-%p-%m.profraw" 49 50type CoverageProperties struct { 51 Native_coverage *bool 52 53 NeedCoverageVariant bool `blueprint:"mutated"` 54 NeedCoverageBuild bool `blueprint:"mutated"` 55 56 CoverageEnabled bool `blueprint:"mutated"` 57 IsCoverageVariant bool `blueprint:"mutated"` 58} 59 60type coverage struct { 61 Properties CoverageProperties 62 63 // Whether binaries containing this module need --coverage added to their ldflags 64 linkCoverage bool 65} 66 67func (cov *coverage) props() []interface{} { 68 return []interface{}{&cov.Properties} 69} 70 71func getGcovProfileLibraryName(ctx ModuleContextIntf) string { 72 // This function should only ever be called for a cc.Module, so the 73 // following statement should always succeed. 74 // LINT.IfChange 75 if ctx.useSdk() { 76 return "libprofile-extras_ndk" 77 } else { 78 return "libprofile-extras" 79 } 80} 81 82func getClangProfileLibraryName(ctx ModuleContextIntf) string { 83 if ctx.useSdk() { 84 return "libprofile-clang-extras_ndk" 85 } else if ctx.isCfiAssemblySupportEnabled() { 86 return "libprofile-clang-extras_cfi_support" 87 } else { 88 return "libprofile-clang-extras" 89 } 90 // LINT.ThenChange(library.go) 91} 92 93func (cov *coverage) deps(ctx DepsContext, deps Deps) Deps { 94 if cov.Properties.NeedCoverageVariant && ctx.Device() { 95 ctx.AddVariationDependencies([]blueprint.Variation{ 96 {Mutator: "link", Variation: "static"}, 97 }, CoverageDepTag, getGcovProfileLibraryName(ctx)) 98 ctx.AddVariationDependencies([]blueprint.Variation{ 99 {Mutator: "link", Variation: "static"}, 100 }, CoverageDepTag, getClangProfileLibraryName(ctx)) 101 } 102 return deps 103} 104 105func EnableContinuousCoverage(ctx android.BaseModuleContext) bool { 106 return ctx.DeviceConfig().ClangCoverageContinuousMode() 107} 108 109func (cov *coverage) flags(ctx ModuleContext, flags Flags, deps PathDeps) (Flags, PathDeps) { 110 clangCoverage := ctx.DeviceConfig().ClangCoverageEnabled() 111 gcovCoverage := ctx.DeviceConfig().GcovCoverageEnabled() 112 113 if !gcovCoverage && !clangCoverage { 114 return flags, deps 115 } 116 117 if cov.Properties.CoverageEnabled { 118 cov.linkCoverage = true 119 120 if gcovCoverage { 121 flags.GcovCoverage = true 122 flags.Local.CommonFlags = append(flags.Local.CommonFlags, "--coverage", "-O0") 123 124 // Override -Wframe-larger-than and non-default optimization 125 // flags that the module may use. 126 flags.Local.CFlags = append(flags.Local.CFlags, "-Wno-frame-larger-than=", "-O0") 127 } else if clangCoverage { 128 flags.Local.CommonFlags = append(flags.Local.CommonFlags, profileInstrFlag) 129 flags.Local.CommonFlags = append(flags.Local.CommonFlags, clangCoverageCommonFlags...) 130 // Override -Wframe-larger-than. We can expect frame size increase after 131 // coverage instrumentation. 132 flags.Local.CFlags = append(flags.Local.CFlags, clangCoverageCFlags...) 133 if EnableContinuousCoverage(ctx) { 134 flags.Local.CommonFlags = append(flags.Local.CommonFlags, clangContinuousCoverageFlags...) 135 } 136 137 // http://b/248022906, http://b/247941801 enabling coverage and hwasan-globals 138 // instrumentation together causes duplicate-symbol errors for __llvm_profile_filename. 139 if c, ok := ctx.Module().(*Module); ok && c.sanitize.isSanitizerEnabled(Hwasan) { 140 flags.Local.CommonFlags = append(flags.Local.CommonFlags, clangCoverageHWASanFlags...) 141 } 142 } 143 } 144 145 // Even if we don't have coverage enabled, if any of our object files were compiled 146 // with coverage, then we need to add --coverage to our ldflags. 147 if !cov.linkCoverage { 148 if ctx.static() && !ctx.staticBinary() { 149 // For static libraries, the only thing that changes our object files 150 // are included whole static libraries, so check to see if any of 151 // those have coverage enabled. 152 ctx.VisitDirectDeps(func(m android.Module) { 153 if depTag, ok := ctx.OtherModuleDependencyTag(m).(libraryDependencyTag); ok { 154 if depTag.static() && depTag.wholeStatic { 155 if cc, ok := m.(*Module); ok && cc.coverage != nil { 156 if cc.coverage.linkCoverage { 157 cov.linkCoverage = true 158 } 159 } 160 } 161 } 162 }) 163 } else { 164 // For executables and shared libraries, we need to check all of 165 // our static dependencies. 166 ctx.VisitDirectDeps(func(m android.Module) { 167 cc, ok := m.(*Module) 168 if !ok || cc.coverage == nil { 169 return 170 } 171 172 if static, ok := cc.linker.(libraryInterface); !ok || !static.static() { 173 return 174 } 175 176 if cc.coverage.linkCoverage { 177 cov.linkCoverage = true 178 } 179 }) 180 } 181 } 182 183 if cov.linkCoverage { 184 if gcovCoverage { 185 flags.Local.LdFlags = append(flags.Local.LdFlags, "--coverage") 186 187 if ctx.Device() { 188 coverage := ctx.GetDirectDepWithTag(getGcovProfileLibraryName(ctx), CoverageDepTag).(*Module) 189 deps.WholeStaticLibs = append(deps.WholeStaticLibs, coverage.OutputFile().Path()) 190 flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,--wrap,getenv") 191 } 192 } else if clangCoverage { 193 flags.Local.LdFlags = append(flags.Local.LdFlags, profileInstrFlag) 194 if EnableContinuousCoverage(ctx) { 195 flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,-mllvm=-runtime-counter-relocation") 196 } 197 198 if ctx.Device() { 199 coverage := ctx.GetDirectDepWithTag(getClangProfileLibraryName(ctx), CoverageDepTag).(*Module) 200 deps.WholeStaticLibs = append(deps.WholeStaticLibs, coverage.OutputFile().Path()) 201 flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,--wrap,open") 202 } 203 } 204 } 205 206 return flags, deps 207} 208 209func (cov *coverage) begin(ctx BaseModuleContext) { 210 if ctx.Host() && !ctx.Os().Linux() { 211 // TODO(dwillemsen): because of -nodefaultlibs, we must depend on libclang_rt.profile-*.a 212 // Just turn off for now. 213 } else { 214 cov.Properties = SetCoverageProperties(ctx, cov.Properties, ctx.nativeCoverage(), ctx.useSdk(), ctx.sdkVersion()) 215 } 216} 217 218func SetCoverageProperties(ctx android.BaseModuleContext, properties CoverageProperties, moduleTypeHasCoverage bool, 219 useSdk bool, sdkVersion string) CoverageProperties { 220 // Coverage is disabled globally 221 if !ctx.DeviceConfig().NativeCoverageEnabled() { 222 return properties 223 } 224 225 var needCoverageVariant bool 226 var needCoverageBuild bool 227 228 if moduleTypeHasCoverage { 229 // Check if Native_coverage is set to false. This property defaults to true. 230 needCoverageVariant = BoolDefault(properties.Native_coverage, true) 231 if useSdk && sdkVersion != "current" { 232 // Native coverage is not supported for SDK versions < 23 233 if fromApi, err := strconv.Atoi(sdkVersion); err == nil && fromApi < 23 { 234 needCoverageVariant = false 235 } 236 } 237 238 if needCoverageVariant { 239 // Coverage variant is actually built with coverage if enabled for its module path 240 needCoverageBuild = ctx.DeviceConfig().NativeCoverageEnabledForPath(ctx.ModuleDir()) 241 } 242 } 243 244 properties.NeedCoverageBuild = needCoverageBuild 245 properties.NeedCoverageVariant = needCoverageVariant 246 247 return properties 248} 249 250type IsNativeCoverageNeededContext interface { 251 Config() android.Config 252 DeviceConfig() android.DeviceConfig 253 Device() bool 254} 255 256var _ IsNativeCoverageNeededContext = android.IncomingTransitionContext(nil) 257var _ IsNativeCoverageNeededContext = android.BaseModuleContext(nil) 258var _ IsNativeCoverageNeededContext = android.BottomUpMutatorContext(nil) 259 260type UseCoverage interface { 261 android.Module 262 IsNativeCoverageNeeded(ctx IsNativeCoverageNeededContext) bool 263} 264 265// Coverage is an interface for non-CC modules to implement to be mutated for coverage 266type Coverage interface { 267 UseCoverage 268 SetPreventInstall() 269 HideFromMake() 270 MarkAsCoverageVariant(bool) 271 EnableCoverageIfNeeded() 272} 273 274type coverageTransitionMutator struct{} 275 276var _ android.TransitionMutator = (*coverageTransitionMutator)(nil) 277 278func (c coverageTransitionMutator) Split(ctx android.BaseModuleContext) []string { 279 if c, ok := ctx.Module().(*Module); ok && c.coverage != nil { 280 if c.coverage.Properties.NeedCoverageVariant { 281 return []string{"", "cov"} 282 } 283 } else if cov, ok := ctx.Module().(Coverage); ok && cov.IsNativeCoverageNeeded(ctx) { 284 // APEX and Rust modules fall here 285 286 // Note: variant "" is also created because an APEX can be depended on by another 287 // module which are split into "" and "cov" variants. e.g. when cc_test refers 288 // to an APEX via 'data' property. 289 return []string{"", "cov"} 290 } else if cov, ok := ctx.Module().(UseCoverage); ok && cov.IsNativeCoverageNeeded(ctx) { 291 // Module itself doesn't have to have "cov" variant, but it should use "cov" variants of 292 // deps. 293 return []string{"cov"} 294 } 295 296 return []string{""} 297} 298 299func (c coverageTransitionMutator) OutgoingTransition(ctx android.OutgoingTransitionContext, sourceVariation string) string { 300 return sourceVariation 301} 302 303func (c coverageTransitionMutator) IncomingTransition(ctx android.IncomingTransitionContext, incomingVariation string) string { 304 if c, ok := ctx.Module().(*Module); ok && c.coverage != nil { 305 if !c.coverage.Properties.NeedCoverageVariant { 306 return "" 307 } 308 } else if cov, ok := ctx.Module().(Coverage); ok { 309 if !cov.IsNativeCoverageNeeded(ctx) { 310 return "" 311 } 312 } else if cov, ok := ctx.Module().(UseCoverage); ok && cov.IsNativeCoverageNeeded(ctx) { 313 // Module only has a "cov" variation, so all incoming variations should use "cov". 314 return "cov" 315 } else { 316 return "" 317 } 318 319 return incomingVariation 320} 321 322func (c coverageTransitionMutator) Mutate(ctx android.BottomUpMutatorContext, variation string) { 323 if c, ok := ctx.Module().(*Module); ok && c.coverage != nil { 324 if variation == "" && c.coverage.Properties.NeedCoverageVariant { 325 // Setup the non-coverage version and set HideFromMake and 326 // PreventInstall to true. 327 c.coverage.Properties.CoverageEnabled = false 328 c.coverage.Properties.IsCoverageVariant = false 329 c.Properties.HideFromMake = true 330 c.Properties.PreventInstall = true 331 } else if variation == "cov" { 332 // The coverage-enabled version inherits HideFromMake, 333 // PreventInstall from the original module. 334 c.coverage.Properties.CoverageEnabled = c.coverage.Properties.NeedCoverageBuild 335 c.coverage.Properties.IsCoverageVariant = true 336 } 337 } else if cov, ok := ctx.Module().(Coverage); ok && cov.IsNativeCoverageNeeded(ctx) { 338 // APEX and Rust modules fall here 339 340 // Note: variant "" is also created because an APEX can be depended on by another 341 // module which are split into "" and "cov" variants. e.g. when cc_test refers 342 // to an APEX via 'data' property. 343 if variation == "" { 344 cov.MarkAsCoverageVariant(false) 345 cov.SetPreventInstall() 346 cov.HideFromMake() 347 } else if variation == "cov" { 348 cov.MarkAsCoverageVariant(true) 349 cov.EnableCoverageIfNeeded() 350 } 351 } else if cov, ok := ctx.Module().(UseCoverage); ok && cov.IsNativeCoverageNeeded(ctx) { 352 // Module itself doesn't have to have "cov" variant, but it should use "cov" variants of 353 // deps. 354 } 355} 356 357func parseSymbolFileForAPICoverage(ctx ModuleContext, symbolFile string) android.ModuleOutPath { 358 apiLevelsJson := android.GetApiLevelsJson(ctx) 359 symbolFilePath := android.PathForModuleSrc(ctx, symbolFile) 360 outputFile := ctx.baseModuleName() + ".xml" 361 parsedApiCoveragePath := android.PathForModuleOut(ctx, outputFile) 362 rule := android.NewRuleBuilder(pctx, ctx) 363 rule.Command(). 364 BuiltTool("ndk_api_coverage_parser"). 365 Input(symbolFilePath). 366 Output(parsedApiCoveragePath). 367 Implicit(apiLevelsJson). 368 FlagWithArg("--api-map ", apiLevelsJson.String()) 369 rule.Build("native_library_api_list", "Generate native API list based on symbol files for coverage measurement") 370 return parsedApiCoveragePath 371} 372