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
15package rust
16
17import (
18	"github.com/google/blueprint"
19
20	"android/soong/cc"
21)
22
23var CovLibraryName = "libprofile-clang-extras"
24
25const profileInstrFlag = "-fprofile-instr-generate=/data/misc/trace/clang-%p-%m.profraw"
26
27type coverage struct {
28	Properties cc.CoverageProperties
29
30	// Whether binaries containing this module need --coverage added to their ldflags
31	linkCoverage bool
32}
33
34func (cov *coverage) props() []interface{} {
35	return []interface{}{&cov.Properties}
36}
37
38func (cov *coverage) deps(ctx DepsContext, deps Deps) Deps {
39	if cov.Properties.NeedCoverageVariant {
40		ctx.AddVariationDependencies([]blueprint.Variation{
41			{Mutator: "link", Variation: "static"},
42		}, cc.CoverageDepTag, CovLibraryName)
43	}
44
45	return deps
46}
47
48func (cov *coverage) flags(ctx ModuleContext, flags Flags, deps PathDeps) (Flags, PathDeps) {
49
50	if !ctx.DeviceConfig().NativeCoverageEnabled() {
51		return flags, deps
52	}
53
54	if cov.Properties.CoverageEnabled {
55		flags.Coverage = true
56		coverage := ctx.GetDirectDepWithTag(CovLibraryName, cc.CoverageDepTag).(cc.LinkableInterface)
57		flags.RustFlags = append(flags.RustFlags,
58			"-Z instrument-coverage", "-g", "-C link-dead-code")
59		flags.LinkFlags = append(flags.LinkFlags,
60			profileInstrFlag, "-g", coverage.OutputFile().Path().String(), "-Wl,--wrap,open")
61		deps.StaticLibs = append(deps.StaticLibs, coverage.OutputFile().Path())
62	}
63
64	return flags, deps
65}
66
67func (cov *coverage) begin(ctx BaseModuleContext) {
68	if ctx.Host() {
69		// Host coverage not yet supported.
70	} else {
71		// Update useSdk and sdkVersion args if Rust modules become SDK aware.
72		cov.Properties = cc.SetCoverageProperties(ctx, cov.Properties, ctx.RustModule().nativeCoverage(), false, "")
73	}
74}
75