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 UseCoverage interface {
251	android.Module
252	IsNativeCoverageNeeded(ctx android.IncomingTransitionContext) bool
253}
254
255// Coverage is an interface for non-CC modules to implement to be mutated for coverage
256type Coverage interface {
257	UseCoverage
258	SetPreventInstall()
259	HideFromMake()
260	MarkAsCoverageVariant(bool)
261	EnableCoverageIfNeeded()
262}
263
264type coverageTransitionMutator struct{}
265
266var _ android.TransitionMutator = (*coverageTransitionMutator)(nil)
267
268func (c coverageTransitionMutator) Split(ctx android.BaseModuleContext) []string {
269	if c, ok := ctx.Module().(*Module); ok && c.coverage != nil {
270		if c.coverage.Properties.NeedCoverageVariant {
271			return []string{"", "cov"}
272		}
273	} else if cov, ok := ctx.Module().(Coverage); ok && cov.IsNativeCoverageNeeded(ctx) {
274		// APEX and Rust modules fall here
275
276		// Note: variant "" is also created because an APEX can be depended on by another
277		// module which are split into "" and "cov" variants. e.g. when cc_test refers
278		// to an APEX via 'data' property.
279		return []string{"", "cov"}
280	} else if cov, ok := ctx.Module().(UseCoverage); ok && cov.IsNativeCoverageNeeded(ctx) {
281		// Module itself doesn't have to have "cov" variant, but it should use "cov" variants of
282		// deps.
283		return []string{"cov"}
284	}
285
286	return []string{""}
287}
288
289func (c coverageTransitionMutator) OutgoingTransition(ctx android.OutgoingTransitionContext, sourceVariation string) string {
290	return sourceVariation
291}
292
293func (c coverageTransitionMutator) IncomingTransition(ctx android.IncomingTransitionContext, incomingVariation string) string {
294	if c, ok := ctx.Module().(*Module); ok && c.coverage != nil {
295		if !c.coverage.Properties.NeedCoverageVariant {
296			return ""
297		}
298	} else if cov, ok := ctx.Module().(Coverage); ok {
299		if !cov.IsNativeCoverageNeeded(ctx) {
300			return ""
301		}
302	} else if cov, ok := ctx.Module().(UseCoverage); ok && cov.IsNativeCoverageNeeded(ctx) {
303		// Module only has a "cov" variation, so all incoming variations should use "cov".
304		return "cov"
305	} else {
306		return ""
307	}
308
309	return incomingVariation
310}
311
312func (c coverageTransitionMutator) Mutate(ctx android.BottomUpMutatorContext, variation string) {
313	if c, ok := ctx.Module().(*Module); ok && c.coverage != nil {
314		if variation == "" && c.coverage.Properties.NeedCoverageVariant {
315			// Setup the non-coverage version and set HideFromMake and
316			// PreventInstall to true.
317			c.coverage.Properties.CoverageEnabled = false
318			c.coverage.Properties.IsCoverageVariant = false
319			c.Properties.HideFromMake = true
320			c.Properties.PreventInstall = true
321		} else if variation == "cov" {
322			// The coverage-enabled version inherits HideFromMake,
323			// PreventInstall from the original module.
324			c.coverage.Properties.CoverageEnabled = c.coverage.Properties.NeedCoverageBuild
325			c.coverage.Properties.IsCoverageVariant = true
326		}
327	} else if cov, ok := ctx.Module().(Coverage); ok && cov.IsNativeCoverageNeeded(ctx) {
328		// APEX and Rust modules fall here
329
330		// Note: variant "" is also created because an APEX can be depended on by another
331		// module which are split into "" and "cov" variants. e.g. when cc_test refers
332		// to an APEX via 'data' property.
333		if variation == "" {
334			cov.MarkAsCoverageVariant(false)
335			cov.SetPreventInstall()
336			cov.HideFromMake()
337		} else if variation == "cov" {
338			cov.MarkAsCoverageVariant(true)
339			cov.EnableCoverageIfNeeded()
340		}
341	} else if cov, ok := ctx.Module().(UseCoverage); ok && cov.IsNativeCoverageNeeded(ctx) {
342		// Module itself doesn't have to have "cov" variant, but it should use "cov" variants of
343		// deps.
344	}
345}
346
347func parseSymbolFileForAPICoverage(ctx ModuleContext, symbolFile string) android.ModuleOutPath {
348	apiLevelsJson := android.GetApiLevelsJson(ctx)
349	symbolFilePath := android.PathForModuleSrc(ctx, symbolFile)
350	outputFile := ctx.baseModuleName() + ".xml"
351	parsedApiCoveragePath := android.PathForModuleOut(ctx, outputFile)
352	rule := android.NewRuleBuilder(pctx, ctx)
353	rule.Command().
354		BuiltTool("ndk_api_coverage_parser").
355		Input(symbolFilePath).
356		Output(parsedApiCoveragePath).
357		Implicit(apiLevelsJson).
358		FlagWithArg("--api-map ", apiLevelsJson.String())
359	rule.Build("native_library_api_list", "Generate native API list based on symbol files for coverage measurement")
360	return parsedApiCoveragePath
361}
362