blob: a820b3855d61e152a5703c37859760d060aa91c8 [file] [log] [blame]
Colin Crosscb933592017-11-22 13:49:43 -08001// 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 java
16
17// Rules for instrumenting classes using jacoco
18
19import (
Colin Cross7a3139e2017-12-19 13:57:50 -080020 "fmt"
Colin Cross84c38822018-01-03 15:59:46 -080021 "path/filepath"
Colin Crosscb933592017-11-22 13:49:43 -080022 "strings"
23
24 "github.com/google/blueprint"
Nan Zhangffe2c1c2018-01-25 13:53:22 -080025 "github.com/google/blueprint/proptools"
Colin Crosscb933592017-11-22 13:49:43 -080026
27 "android/soong/android"
Chris Gross2f748692020-06-24 20:36:59 +000028 "android/soong/java/config"
Colin Crosscb933592017-11-22 13:49:43 -080029)
30
31var (
32 jacoco = pctx.AndroidStaticRule("jacoco", blueprint.RuleParams{
Colin Cross84c38822018-01-03 15:59:46 -080033 Command: `rm -rf $tmpDir && mkdir -p $tmpDir && ` +
34 `${config.Zip2ZipCmd} -i $in -o $strippedJar $stripSpec && ` +
Sasha Smundak26c6d9e2019-06-11 13:30:13 -070035 `${config.JavaCmd} ${config.JavaVmFlags} -jar ${config.JacocoCLIJar} ` +
Colin Cross84c38822018-01-03 15:59:46 -080036 ` instrument --quiet --dest $tmpDir $strippedJar && ` +
Colin Cross84c38822018-01-03 15:59:46 -080037 `${config.MergeZipsCmd} --ignore-duplicates -j $out $tmpJar $in`,
Colin Crosscb933592017-11-22 13:49:43 -080038 CommandDeps: []string{
39 "${config.Zip2ZipCmd}",
40 "${config.JavaCmd}",
41 "${config.JacocoCLIJar}",
Colin Crosscb933592017-11-22 13:49:43 -080042 "${config.MergeZipsCmd}",
43 },
44 },
Colin Cross84c38822018-01-03 15:59:46 -080045 "strippedJar", "stripSpec", "tmpDir", "tmpJar")
Colin Crosscb933592017-11-22 13:49:43 -080046)
47
Sam Delmerico1e3f78f2022-09-07 12:07:07 -040048func jacocoDepsMutator(ctx android.BottomUpMutatorContext) {
49 type instrumentable interface {
50 shouldInstrument(ctx android.BaseModuleContext) bool
51 shouldInstrumentInApex(ctx android.BaseModuleContext) bool
52 setInstrument(value bool)
53 }
54
55 j, ok := ctx.Module().(instrumentable)
56 if !ctx.Module().Enabled() || !ok {
57 return
58 }
59
60 if j.shouldInstrumentInApex(ctx) {
61 j.setInstrument(true)
62 }
63
64 if j.shouldInstrument(ctx) && ctx.ModuleName() != "jacocoagent" {
65 // We can use AddFarVariationDependencies here because, since this dep
66 // is added as libs only (i.e. a compiletime CLASSPATH entry only),
67 // the first variant of jacocoagent is sufficient to prevent
68 // compile time errors.
69 // At this stage in the build, AddVariationDependencies is not always
70 // able to procure a variant of jacocoagent that matches the calling
71 // module.
72 ctx.AddFarVariationDependencies(ctx.Module().Target().Variations(), libTag, "jacocoagent")
73 }
74}
75
Colin Cross84c38822018-01-03 15:59:46 -080076// Instruments a jar using the Jacoco command line interface. Uses stripSpec to extract a subset
77// of the classes in inputJar into strippedJar, instruments strippedJar into tmpJar, and then
78// combines the classes in tmpJar with inputJar (preferring the instrumented classes in tmpJar)
79// to produce instrumentedJar.
80func jacocoInstrumentJar(ctx android.ModuleContext, instrumentedJar, strippedJar android.WritablePath,
Colin Crosscb933592017-11-22 13:49:43 -080081 inputJar android.Path, stripSpec string) {
Colin Cross84c38822018-01-03 15:59:46 -080082
83 // The basename of tmpJar has to be the same as the basename of strippedJar
84 tmpJar := android.PathForModuleOut(ctx, "jacoco", "tmp", strippedJar.Base())
Colin Crosscb933592017-11-22 13:49:43 -080085
86 ctx.Build(pctx, android.BuildParams{
87 Rule: jacoco,
88 Description: "jacoco",
Colin Cross84c38822018-01-03 15:59:46 -080089 Output: instrumentedJar,
Colin Crosscb933592017-11-22 13:49:43 -080090 ImplicitOutput: strippedJar,
91 Input: inputJar,
92 Args: map[string]string{
Colin Cross84c38822018-01-03 15:59:46 -080093 "strippedJar": strippedJar.String(),
94 "stripSpec": stripSpec,
95 "tmpDir": filepath.Dir(tmpJar.String()),
96 "tmpJar": tmpJar.String(),
Colin Crosscb933592017-11-22 13:49:43 -080097 },
98 })
99}
100
Colin Cross7a3139e2017-12-19 13:57:50 -0800101func (j *Module) jacocoModuleToZipCommand(ctx android.ModuleContext) string {
102 includes, err := jacocoFiltersToSpecs(j.properties.Jacoco.Include_filter)
103 if err != nil {
104 ctx.PropertyErrorf("jacoco.include_filter", "%s", err.Error())
105 }
Chris Gross2f748692020-06-24 20:36:59 +0000106 // Also include the default list of classes to exclude from instrumentation.
107 excludes, err := jacocoFiltersToSpecs(append(j.properties.Jacoco.Exclude_filter, config.DefaultJacocoExcludeFilter...))
Colin Cross7a3139e2017-12-19 13:57:50 -0800108 if err != nil {
109 ctx.PropertyErrorf("jacoco.exclude_filter", "%s", err.Error())
110 }
Colin Crosscb933592017-11-22 13:49:43 -0800111
Colin Cross7a3139e2017-12-19 13:57:50 -0800112 return jacocoFiltersToZipCommand(includes, excludes)
113}
114
115func jacocoFiltersToZipCommand(includes, excludes []string) string {
Colin Crosscb933592017-11-22 13:49:43 -0800116 specs := ""
117 if len(excludes) > 0 {
Colin Crossd7deceb2017-12-19 13:59:44 -0800118 specs += android.JoinWithPrefix(excludes, "-x ") + " "
Colin Crosscb933592017-11-22 13:49:43 -0800119 }
Colin Crosscb933592017-11-22 13:49:43 -0800120 if len(includes) > 0 {
121 specs += strings.Join(includes, " ")
122 } else {
Maxim Pleshivenkov9d773842021-06-30 10:31:46 -0400123 specs += "'**/*.class'"
Colin Crosscb933592017-11-22 13:49:43 -0800124 }
Colin Crosscb933592017-11-22 13:49:43 -0800125 return specs
126}
127
Colin Cross7a3139e2017-12-19 13:57:50 -0800128func jacocoFiltersToSpecs(filters []string) ([]string, error) {
Colin Crosscb933592017-11-22 13:49:43 -0800129 specs := make([]string, len(filters))
Colin Cross7a3139e2017-12-19 13:57:50 -0800130 var err error
Colin Crosscb933592017-11-22 13:49:43 -0800131 for i, f := range filters {
Colin Cross7a3139e2017-12-19 13:57:50 -0800132 specs[i], err = jacocoFilterToSpec(f)
133 if err != nil {
134 return nil, err
135 }
Colin Crosscb933592017-11-22 13:49:43 -0800136 }
Colin Cross0b9f31f2019-02-28 11:00:01 -0800137 return proptools.NinjaAndShellEscapeList(specs), nil
Colin Crosscb933592017-11-22 13:49:43 -0800138}
139
Colin Cross7a3139e2017-12-19 13:57:50 -0800140func jacocoFilterToSpec(filter string) (string, error) {
Nan Zhangffe2c1c2018-01-25 13:53:22 -0800141 recursiveWildcard := strings.HasSuffix(filter, "**")
142 nonRecursiveWildcard := false
143 if !recursiveWildcard {
144 nonRecursiveWildcard = strings.HasSuffix(filter, "*")
145 filter = strings.TrimSuffix(filter, "*")
146 } else {
147 filter = strings.TrimSuffix(filter, "**")
148 }
149
150 if recursiveWildcard && !(strings.HasSuffix(filter, ".") || filter == "") {
151 return "", fmt.Errorf("only '**' or '.**' is supported as recursive wildcard in a filter")
152 }
Colin Crosscb933592017-11-22 13:49:43 -0800153
154 if strings.ContainsRune(filter, '*') {
Colin Cross7a3139e2017-12-19 13:57:50 -0800155 return "", fmt.Errorf("'*' is only supported as the last character in a filter")
Colin Crosscb933592017-11-22 13:49:43 -0800156 }
157
158 spec := strings.Replace(filter, ".", "/", -1)
159
160 if recursiveWildcard {
161 spec += "**/*.class"
Nan Zhangffe2c1c2018-01-25 13:53:22 -0800162 } else if nonRecursiveWildcard {
Colin Crosscb933592017-11-22 13:49:43 -0800163 spec += "*.class"
Colin Crossd7deceb2017-12-19 13:59:44 -0800164 } else {
165 spec += ".class"
Colin Crosscb933592017-11-22 13:49:43 -0800166 }
167
Colin Cross7a3139e2017-12-19 13:57:50 -0800168 return spec, nil
Colin Crosscb933592017-11-22 13:49:43 -0800169}