blob: d77d59acf027531be6af38555302f37b940f9053 [file] [log] [blame]
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001// Copyright 2020 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 bazel
16
17import (
Chris Parsons0bfb1c02022-05-12 16:43:01 -040018 "crypto/sha256"
Usta Shrestha2ccdb422022-06-02 10:19:13 -040019 "encoding/base64"
Cole Faustbc65a3f2023-08-01 16:38:55 +000020 "encoding/json"
Chris Parsonsaffbb602020-12-23 12:02:11 -050021 "fmt"
22 "path/filepath"
Cole Faustbc65a3f2023-08-01 16:38:55 +000023 analysis_v2_proto "prebuilts/bazel/common/proto/analysis_v2"
Chris Parsons0bfb1c02022-05-12 16:43:01 -040024 "reflect"
Chris Parsons0bfb1c02022-05-12 16:43:01 -040025 "sort"
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050026 "strings"
Liz Kammera4655a92023-02-10 17:17:28 -050027 "sync"
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050028
Liz Kammer690fbac2023-02-10 11:11:17 -050029 "github.com/google/blueprint/metrics"
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050030 "github.com/google/blueprint/proptools"
Jason Wu118fd2b2022-10-27 18:41:15 +000031 "google.golang.org/protobuf/proto"
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050032)
33
Usta Shrestha6298cc52022-05-27 17:40:21 -040034type artifactId int
35type depsetId int
36type pathFragmentId int
37
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050038// artifact contains relevant portions of Bazel's aquery proto, Artifact.
39// Represents a single artifact, whether it's a source file or a derived output file.
40type artifact struct {
Usta Shrestha6298cc52022-05-27 17:40:21 -040041 Id artifactId
42 PathFragmentId pathFragmentId
Chris Parsonsaffbb602020-12-23 12:02:11 -050043}
44
45type pathFragment struct {
Usta Shrestha6298cc52022-05-27 17:40:21 -040046 Id pathFragmentId
Chris Parsonsaffbb602020-12-23 12:02:11 -050047 Label string
Usta Shrestha6298cc52022-05-27 17:40:21 -040048 ParentId pathFragmentId
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050049}
50
51// KeyValuePair represents Bazel's aquery proto, KeyValuePair.
52type KeyValuePair struct {
53 Key string
54 Value string
55}
56
Chris Parsons1a7aca02022-04-25 22:35:15 -040057// AqueryDepset is a depset definition from Bazel's aquery response. This is
Chris Parsons0bfb1c02022-05-12 16:43:01 -040058// akin to the `depSetOfFiles` in the response proto, except:
Colin Crossd079e0b2022-08-16 10:27:33 -070059// - direct artifacts are enumerated by full path instead of by ID
60// - it has a hash of the depset contents, instead of an int ID (for determinism)
61//
Chris Parsons1a7aca02022-04-25 22:35:15 -040062// A depset is a data structure for efficient transitive handling of artifact
63// paths. A single depset consists of one or more artifact paths and one or
64// more "child" depsets.
65type AqueryDepset struct {
Chris Parsons0bfb1c02022-05-12 16:43:01 -040066 ContentHash string
67 DirectArtifacts []string
68 TransitiveDepSetHashes []string
Chris Parsons1a7aca02022-04-25 22:35:15 -040069}
70
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050071// depSetOfFiles contains relevant portions of Bazel's aquery proto, DepSetOfFiles.
72// Represents a data structure containing one or more files. Depsets in Bazel are an efficient
73// data structure for storing large numbers of file paths.
74type depSetOfFiles struct {
Usta Shrestha6298cc52022-05-27 17:40:21 -040075 Id depsetId
76 DirectArtifactIds []artifactId
77 TransitiveDepSetIds []depsetId
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050078}
79
80// action contains relevant portions of Bazel's aquery proto, Action.
81// Represents a single command line invocation in the Bazel build graph.
82type action struct {
83 Arguments []string
84 EnvironmentVariables []KeyValuePair
Usta Shrestha6298cc52022-05-27 17:40:21 -040085 InputDepSetIds []depsetId
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050086 Mnemonic string
Usta Shrestha6298cc52022-05-27 17:40:21 -040087 OutputIds []artifactId
Wei Li455ba832021-11-04 22:58:12 +000088 TemplateContent string
89 Substitutions []KeyValuePair
Sasha Smundak1da064c2022-06-08 16:36:16 -070090 FileContents string
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050091}
92
93// actionGraphContainer contains relevant portions of Bazel's aquery proto, ActionGraphContainer.
94// An aquery response from Bazel contains a single ActionGraphContainer proto.
95type actionGraphContainer struct {
96 Artifacts []artifact
97 Actions []action
98 DepSetOfFiles []depSetOfFiles
Chris Parsonsaffbb602020-12-23 12:02:11 -050099 PathFragments []pathFragment
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500100}
101
102// BuildStatement contains information to register a build statement corresponding (one to one)
103// with a Bazel action from Bazel's action graph.
104type BuildStatement struct {
Liz Kammerc49e6822021-06-08 15:04:11 -0400105 Command string
106 Depfile *string
107 OutputPaths []string
Liz Kammerc49e6822021-06-08 15:04:11 -0400108 SymlinkPaths []string
Liz Kammer00629db2023-02-09 14:28:15 -0500109 Env []*analysis_v2_proto.KeyValuePair
Liz Kammerc49e6822021-06-08 15:04:11 -0400110 Mnemonic string
Chris Parsons1a7aca02022-04-25 22:35:15 -0400111
112 // Inputs of this build statement, either as unexpanded depsets or expanded
113 // input paths. There should be no overlap between these fields; an input
114 // path should either be included as part of an unexpanded depset or a raw
115 // input path string, but not both.
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400116 InputDepsetHashes []string
117 InputPaths []string
Sasha Smundak1da064c2022-06-08 16:36:16 -0700118 FileContents string
Spandan Dasaf4ccaa2023-06-29 01:15:51 +0000119 // If ShouldRunInSbox is true, Soong will use sbox to created an isolated environment
120 // and run the mixed build action there
121 ShouldRunInSbox bool
Cole Faustbc65a3f2023-08-01 16:38:55 +0000122 // A list of files to add as implicit deps to the outputs of this BuildStatement.
123 // Unlike most properties in BuildStatement, these paths must be relative to the root of
124 // the whole out/ folder, instead of relative to ctx.Config().BazelContext.OutputBase()
125 ImplicitDeps []string
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500126}
127
Chris Parsonsc4fb1332021-05-18 12:31:25 -0400128// A helper type for aquery processing which facilitates retrieval of path IDs from their
129// less readable Bazel structures (depset and path fragment).
130type aqueryArtifactHandler struct {
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400131 // Maps depset id to AqueryDepset, a representation of depset which is
132 // post-processed for middleman artifact handling, unhandled artifact
133 // dropping, content hashing, etc.
Usta Shrestha6298cc52022-05-27 17:40:21 -0400134 depsetIdToAqueryDepset map[depsetId]AqueryDepset
Usta Shrestha13fd5ae2023-01-27 10:55:34 -0500135 emptyDepsetIds map[depsetId]struct{}
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400136 // Maps content hash to AqueryDepset.
137 depsetHashToAqueryDepset map[string]AqueryDepset
138
Chris Parsonsc4fb1332021-05-18 12:31:25 -0400139 // depsetIdToArtifactIdsCache is a memoization of depset flattening, because flattening
140 // may be an expensive operation.
Liz Kammera4655a92023-02-10 17:17:28 -0500141 depsetHashToArtifactPathsCache sync.Map
Usta Shrestha6298cc52022-05-27 17:40:21 -0400142 // Maps artifact ids to fully expanded paths.
143 artifactIdToPath map[artifactId]string
Chris Parsonsc4fb1332021-05-18 12:31:25 -0400144}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500145
Wei Li455ba832021-11-04 22:58:12 +0000146// The tokens should be substituted with the value specified here, instead of the
147// one returned in 'substitutions' of TemplateExpand action.
Usta Shrestha6298cc52022-05-27 17:40:21 -0400148var templateActionOverriddenTokens = map[string]string{
Wei Li455ba832021-11-04 22:58:12 +0000149 // Uses "python3" for %python_binary% instead of the value returned by aquery
150 // which is "py3wrapper.sh". See removePy3wrapperScript.
151 "%python_binary%": "python3",
152}
153
Liz Kammer00629db2023-02-09 14:28:15 -0500154const (
155 middlemanMnemonic = "Middleman"
156 // The file name of py3wrapper.sh, which is used by py_binary targets.
157 py3wrapperFileName = "/py3wrapper.sh"
158)
Wei Li455ba832021-11-04 22:58:12 +0000159
Usta Shrestha6298cc52022-05-27 17:40:21 -0400160func indexBy[K comparable, V any](values []V, keyFn func(v V) K) map[K]V {
161 m := map[K]V{}
162 for _, v := range values {
163 m[keyFn(v)] = v
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500164 }
Usta Shrestha6298cc52022-05-27 17:40:21 -0400165 return m
166}
Chris Parsonsc4fb1332021-05-18 12:31:25 -0400167
Liz Kammer00629db2023-02-09 14:28:15 -0500168func newAqueryHandler(aqueryResult *analysis_v2_proto.ActionGraphContainer) (*aqueryArtifactHandler, error) {
169 pathFragments := indexBy(aqueryResult.PathFragments, func(pf *analysis_v2_proto.PathFragment) pathFragmentId {
170 return pathFragmentId(pf.Id)
Usta Shrestha6298cc52022-05-27 17:40:21 -0400171 })
172
Liz Kammer00629db2023-02-09 14:28:15 -0500173 artifactIdToPath := make(map[artifactId]string, len(aqueryResult.Artifacts))
Chris Parsonsaffbb602020-12-23 12:02:11 -0500174 for _, artifact := range aqueryResult.Artifacts {
Liz Kammer00629db2023-02-09 14:28:15 -0500175 artifactPath, err := expandPathFragment(pathFragmentId(artifact.PathFragmentId), pathFragments)
Chris Parsonsaffbb602020-12-23 12:02:11 -0500176 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -0500177 return nil, err
Chris Parsonsaffbb602020-12-23 12:02:11 -0500178 }
Romain Jobredeauxe3989a12023-07-19 20:58:27 +0000179 artifactIdToPath[artifactId(artifact.Id)] = artifactPath
Chris Parsonsaffbb602020-12-23 12:02:11 -0500180 }
Chris Parsons943f2432021-01-19 11:36:50 -0500181
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400182 // Map middleman artifact ContentHash to input artifact depset ID.
Chris Parsons1a7aca02022-04-25 22:35:15 -0400183 // Middleman artifacts are treated as "substitute" artifacts for mixed builds. For example,
Usta Shrestha16ac1352022-06-22 11:01:55 -0400184 // if we find a middleman action which has inputs [foo, bar], and output [baz_middleman], then,
Chris Parsons1a7aca02022-04-25 22:35:15 -0400185 // for each other action which has input [baz_middleman], we add [foo, bar] to the inputs for
186 // that action instead.
Liz Kammer00629db2023-02-09 14:28:15 -0500187 middlemanIdToDepsetIds := map[artifactId][]uint32{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500188 for _, actionEntry := range aqueryResult.Actions {
Liz Kammer00629db2023-02-09 14:28:15 -0500189 if actionEntry.Mnemonic == middlemanMnemonic {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500190 for _, outputId := range actionEntry.OutputIds {
Liz Kammer00629db2023-02-09 14:28:15 -0500191 middlemanIdToDepsetIds[artifactId(outputId)] = actionEntry.InputDepSetIds
Chris Parsons8d6e4332021-02-22 16:13:50 -0500192 }
193 }
194 }
Chris Parsons1a7aca02022-04-25 22:35:15 -0400195
Liz Kammer00629db2023-02-09 14:28:15 -0500196 depsetIdToDepset := indexBy(aqueryResult.DepSetOfFiles, func(d *analysis_v2_proto.DepSetOfFiles) depsetId {
197 return depsetId(d.Id)
Usta Shrestha6298cc52022-05-27 17:40:21 -0400198 })
Chris Parsons1a7aca02022-04-25 22:35:15 -0400199
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400200 aqueryHandler := aqueryArtifactHandler{
Usta Shrestha6298cc52022-05-27 17:40:21 -0400201 depsetIdToAqueryDepset: map[depsetId]AqueryDepset{},
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400202 depsetHashToAqueryDepset: map[string]AqueryDepset{},
Liz Kammera4655a92023-02-10 17:17:28 -0500203 depsetHashToArtifactPathsCache: sync.Map{},
Usta Shrestha13fd5ae2023-01-27 10:55:34 -0500204 emptyDepsetIds: make(map[depsetId]struct{}, 0),
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400205 artifactIdToPath: artifactIdToPath,
206 }
207
208 // Validate and adjust aqueryResult.DepSetOfFiles values.
209 for _, depset := range aqueryResult.DepSetOfFiles {
210 _, err := aqueryHandler.populateDepsetMaps(depset, middlemanIdToDepsetIds, depsetIdToDepset)
211 if err != nil {
212 return nil, err
213 }
214 }
215
216 return &aqueryHandler, nil
217}
218
219// Ensures that the handler's depsetIdToAqueryDepset map contains an entry for the given
220// depset.
Liz Kammer00629db2023-02-09 14:28:15 -0500221func (a *aqueryArtifactHandler) populateDepsetMaps(depset *analysis_v2_proto.DepSetOfFiles, middlemanIdToDepsetIds map[artifactId][]uint32, depsetIdToDepset map[depsetId]*analysis_v2_proto.DepSetOfFiles) (*AqueryDepset, error) {
222 if aqueryDepset, containsDepset := a.depsetIdToAqueryDepset[depsetId(depset.Id)]; containsDepset {
Usta Shrestha13fd5ae2023-01-27 10:55:34 -0500223 return &aqueryDepset, nil
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400224 }
225 transitiveDepsetIds := depset.TransitiveDepSetIds
Liz Kammer00629db2023-02-09 14:28:15 -0500226 directArtifactPaths := make([]string, 0, len(depset.DirectArtifactIds))
227 for _, id := range depset.DirectArtifactIds {
228 aId := artifactId(id)
229 path, pathExists := a.artifactIdToPath[aId]
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400230 if !pathExists {
Liz Kammer00629db2023-02-09 14:28:15 -0500231 return nil, fmt.Errorf("undefined input artifactId %d", aId)
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400232 }
233 // Filter out any inputs which are universally dropped, and swap middleman
234 // artifacts with their corresponding depsets.
Liz Kammer00629db2023-02-09 14:28:15 -0500235 if depsetsToUse, isMiddleman := middlemanIdToDepsetIds[aId]; isMiddleman {
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400236 // Swap middleman artifacts with their corresponding depsets and drop the middleman artifacts.
237 transitiveDepsetIds = append(transitiveDepsetIds, depsetsToUse...)
Usta Shresthaef922252022-06-02 14:23:02 -0400238 } else if strings.HasSuffix(path, py3wrapperFileName) ||
Usta Shresthaef922252022-06-02 14:23:02 -0400239 strings.HasPrefix(path, "../bazel_tools") {
Usta Shrestha13fd5ae2023-01-27 10:55:34 -0500240 continue
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400241 // Drop these artifacts.
242 // See go/python-binary-host-mixed-build for more details.
Sasha Smundakc180dbd2022-07-03 14:55:58 -0700243 // 1) Drop py3wrapper.sh, just use python binary, the launcher script generated by the
244 // TemplateExpandAction handles everything necessary to launch a Pythin application.
245 // 2) ../bazel_tools: they have MODIFY timestamp 10years in the future and would cause the
Usta Shresthaef922252022-06-02 14:23:02 -0400246 // containing depset to always be considered newer than their outputs.
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400247 } else {
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400248 directArtifactPaths = append(directArtifactPaths, path)
249 }
250 }
251
Liz Kammer00629db2023-02-09 14:28:15 -0500252 childDepsetHashes := make([]string, 0, len(transitiveDepsetIds))
253 for _, id := range transitiveDepsetIds {
254 childDepsetId := depsetId(id)
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400255 childDepset, exists := depsetIdToDepset[childDepsetId]
256 if !exists {
Usta Shrestha13fd5ae2023-01-27 10:55:34 -0500257 if _, empty := a.emptyDepsetIds[childDepsetId]; empty {
258 continue
259 } else {
260 return nil, fmt.Errorf("undefined input depsetId %d (referenced by depsetId %d)", childDepsetId, depset.Id)
261 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400262 }
Usta Shrestha13fd5ae2023-01-27 10:55:34 -0500263 if childAqueryDepset, err := a.populateDepsetMaps(childDepset, middlemanIdToDepsetIds, depsetIdToDepset); err != nil {
264 return nil, err
265 } else if childAqueryDepset == nil {
266 continue
267 } else {
268 childDepsetHashes = append(childDepsetHashes, childAqueryDepset.ContentHash)
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400269 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400270 }
Usta Shresthaef922252022-06-02 14:23:02 -0400271 if len(directArtifactPaths) == 0 && len(childDepsetHashes) == 0 {
Liz Kammer00629db2023-02-09 14:28:15 -0500272 a.emptyDepsetIds[depsetId(depset.Id)] = struct{}{}
Usta Shrestha13fd5ae2023-01-27 10:55:34 -0500273 return nil, nil
Usta Shresthaef922252022-06-02 14:23:02 -0400274 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400275 aqueryDepset := AqueryDepset{
276 ContentHash: depsetContentHash(directArtifactPaths, childDepsetHashes),
277 DirectArtifacts: directArtifactPaths,
278 TransitiveDepSetHashes: childDepsetHashes,
279 }
Liz Kammer00629db2023-02-09 14:28:15 -0500280 a.depsetIdToAqueryDepset[depsetId(depset.Id)] = aqueryDepset
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400281 a.depsetHashToAqueryDepset[aqueryDepset.ContentHash] = aqueryDepset
Usta Shrestha13fd5ae2023-01-27 10:55:34 -0500282 return &aqueryDepset, nil
Chris Parsonsc4fb1332021-05-18 12:31:25 -0400283}
284
Chris Parsons1a7aca02022-04-25 22:35:15 -0400285// getInputPaths flattens the depsets of the given IDs and returns all transitive
286// input paths contained in these depsets.
287// This is a potentially expensive operation, and should not be invoked except
288// for actions which need specialized input handling.
Liz Kammer00629db2023-02-09 14:28:15 -0500289func (a *aqueryArtifactHandler) getInputPaths(depsetIds []uint32) ([]string, error) {
Usta Shrestha6298cc52022-05-27 17:40:21 -0400290 var inputPaths []string
Chris Parsonsc4fb1332021-05-18 12:31:25 -0400291
Liz Kammer00629db2023-02-09 14:28:15 -0500292 for _, id := range depsetIds {
293 inputDepSetId := depsetId(id)
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400294 depset := a.depsetIdToAqueryDepset[inputDepSetId]
295 inputArtifacts, err := a.artifactPathsFromDepsetHash(depset.ContentHash)
Chris Parsonsc4fb1332021-05-18 12:31:25 -0400296 if err != nil {
297 return nil, err
298 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400299 for _, inputPath := range inputArtifacts {
Chris Parsons1a7aca02022-04-25 22:35:15 -0400300 inputPaths = append(inputPaths, inputPath)
Chris Parsonsc4fb1332021-05-18 12:31:25 -0400301 }
302 }
Wei Li455ba832021-11-04 22:58:12 +0000303
Chris Parsons1a7aca02022-04-25 22:35:15 -0400304 return inputPaths, nil
Chris Parsonsc4fb1332021-05-18 12:31:25 -0400305}
306
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400307func (a *aqueryArtifactHandler) artifactPathsFromDepsetHash(depsetHash string) ([]string, error) {
Liz Kammera4655a92023-02-10 17:17:28 -0500308 if result, exists := a.depsetHashToArtifactPathsCache.Load(depsetHash); exists {
309 return result.([]string), nil
Chris Parsonsc4fb1332021-05-18 12:31:25 -0400310 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400311 if depset, exists := a.depsetHashToAqueryDepset[depsetHash]; exists {
312 result := depset.DirectArtifacts
313 for _, childHash := range depset.TransitiveDepSetHashes {
314 childArtifactIds, err := a.artifactPathsFromDepsetHash(childHash)
Chris Parsonsc4fb1332021-05-18 12:31:25 -0400315 if err != nil {
316 return nil, err
317 }
318 result = append(result, childArtifactIds...)
319 }
Liz Kammera4655a92023-02-10 17:17:28 -0500320 a.depsetHashToArtifactPathsCache.Store(depsetHash, result)
Chris Parsonsc4fb1332021-05-18 12:31:25 -0400321 return result, nil
322 } else {
Usta Shrestha2ccdb422022-06-02 10:19:13 -0400323 return nil, fmt.Errorf("undefined input depset hash %s", depsetHash)
Chris Parsonsc4fb1332021-05-18 12:31:25 -0400324 }
325}
326
Chris Parsons1a7aca02022-04-25 22:35:15 -0400327// AqueryBuildStatements returns a slice of BuildStatements and a slice of AqueryDepset
Usta Shrestha6298cc52022-05-27 17:40:21 -0400328// which should be registered (and output to a ninja file) to correspond with Bazel's
Chris Parsons1a7aca02022-04-25 22:35:15 -0400329// action graph, as described by the given action graph json proto.
330// BuildStatements are one-to-one with actions in the given action graph, and AqueryDepsets
331// are one-to-one with Bazel's depSetOfFiles objects.
Liz Kammera4655a92023-02-10 17:17:28 -0500332func AqueryBuildStatements(aqueryJsonProto []byte, eventHandler *metrics.EventHandler) ([]*BuildStatement, []AqueryDepset, error) {
Jason Wu118fd2b2022-10-27 18:41:15 +0000333 aqueryProto := &analysis_v2_proto.ActionGraphContainer{}
334 err := proto.Unmarshal(aqueryJsonProto, aqueryProto)
Chris Parsonsc4fb1332021-05-18 12:31:25 -0400335 if err != nil {
Chris Parsons1a7aca02022-04-25 22:35:15 -0400336 return nil, nil, err
Chris Parsonsc4fb1332021-05-18 12:31:25 -0400337 }
Chris Parsons8d6e4332021-02-22 16:13:50 -0500338
Liz Kammer690fbac2023-02-10 11:11:17 -0500339 var aqueryHandler *aqueryArtifactHandler
340 {
341 eventHandler.Begin("init_handler")
342 defer eventHandler.End("init_handler")
Liz Kammer00629db2023-02-09 14:28:15 -0500343 aqueryHandler, err = newAqueryHandler(aqueryProto)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400344 if err != nil {
345 return nil, nil, err
Chris Parsons8d6e4332021-02-22 16:13:50 -0500346 }
Liz Kammer690fbac2023-02-10 11:11:17 -0500347 }
348
Liz Kammera4655a92023-02-10 17:17:28 -0500349 // allocate both length and capacity so each goroutine can write to an index independently without
350 // any need for synchronization for slice access.
351 buildStatements := make([]*BuildStatement, len(aqueryProto.Actions))
Liz Kammer690fbac2023-02-10 11:11:17 -0500352 {
353 eventHandler.Begin("build_statements")
354 defer eventHandler.End("build_statements")
Liz Kammera4655a92023-02-10 17:17:28 -0500355 wg := sync.WaitGroup{}
356 var errOnce sync.Once
357
358 for i, actionEntry := range aqueryProto.Actions {
359 wg.Add(1)
360 go func(i int, actionEntry *analysis_v2_proto.Action) {
361 buildStatement, aErr := aqueryHandler.actionToBuildStatement(actionEntry)
362 if aErr != nil {
363 errOnce.Do(func() {
364 err = aErr
365 })
366 } else {
367 // set build statement at an index rather than appending such that each goroutine does not
368 // impact other goroutines
369 buildStatements[i] = buildStatement
370 }
371 wg.Done()
372 }(i, actionEntry)
Liz Kammer690fbac2023-02-10 11:11:17 -0500373 }
Liz Kammera4655a92023-02-10 17:17:28 -0500374 wg.Wait()
375 }
376 if err != nil {
377 return nil, nil, err
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500378 }
379
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400380 depsetsByHash := map[string]AqueryDepset{}
Liz Kammer00629db2023-02-09 14:28:15 -0500381 depsets := make([]AqueryDepset, 0, len(aqueryHandler.depsetIdToAqueryDepset))
Liz Kammer690fbac2023-02-10 11:11:17 -0500382 {
383 eventHandler.Begin("depsets")
384 defer eventHandler.End("depsets")
385 for _, aqueryDepset := range aqueryHandler.depsetIdToAqueryDepset {
386 if prevEntry, hasKey := depsetsByHash[aqueryDepset.ContentHash]; hasKey {
387 // Two depsets collide on hash. Ensure that their contents are identical.
388 if !reflect.DeepEqual(aqueryDepset, prevEntry) {
389 return nil, nil, fmt.Errorf("two different depsets have the same hash: %v, %v", prevEntry, aqueryDepset)
390 }
391 } else {
392 depsetsByHash[aqueryDepset.ContentHash] = aqueryDepset
393 depsets = append(depsets, aqueryDepset)
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400394 }
Chris Parsons1a7aca02022-04-25 22:35:15 -0400395 }
Chris Parsons1a7aca02022-04-25 22:35:15 -0400396 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400397
Liz Kammer690fbac2023-02-10 11:11:17 -0500398 eventHandler.Do("build_statement_sort", func() {
399 // Build Statements and depsets must be sorted by their content hash to
400 // preserve determinism between builds (this will result in consistent ninja file
401 // output). Note they are not sorted by their original IDs nor their Bazel ordering,
402 // as Bazel gives nondeterministic ordering / identifiers in aquery responses.
403 sort.Slice(buildStatements, func(i, j int) bool {
Liz Kammera4655a92023-02-10 17:17:28 -0500404 // Sort all nil statements to the end of the slice
405 if buildStatements[i] == nil {
406 return false
407 } else if buildStatements[j] == nil {
408 return true
409 }
410 //For build statements, compare output lists. In Bazel, each output file
Liz Kammer690fbac2023-02-10 11:11:17 -0500411 // may only have one action which generates it, so this will provide
412 // a deterministic ordering.
413 outputs_i := buildStatements[i].OutputPaths
414 outputs_j := buildStatements[j].OutputPaths
415 if len(outputs_i) != len(outputs_j) {
416 return len(outputs_i) < len(outputs_j)
417 }
418 if len(outputs_i) == 0 {
419 // No outputs for these actions, so compare commands.
420 return buildStatements[i].Command < buildStatements[j].Command
421 }
422 // There may be multiple outputs, but the output ordering is deterministic.
423 return outputs_i[0] < outputs_j[0]
424 })
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400425 })
Liz Kammer690fbac2023-02-10 11:11:17 -0500426 eventHandler.Do("depset_sort", func() {
427 sort.Slice(depsets, func(i, j int) bool {
428 return depsets[i].ContentHash < depsets[j].ContentHash
429 })
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400430 })
Chris Parsons1a7aca02022-04-25 22:35:15 -0400431 return buildStatements, depsets, nil
432}
433
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400434// depsetContentHash computes and returns a SHA256 checksum of the contents of
435// the given depset. This content hash may serve as the depset's identifier.
436// Using a content hash for an identifier is superior for determinism. (For example,
437// using an integer identifier which depends on the order in which the depsets are
438// created would result in nondeterministic depset IDs.)
439func depsetContentHash(directPaths []string, transitiveDepsetHashes []string) string {
440 h := sha256.New()
441 // Use newline as delimiter, as paths cannot contain newline.
442 h.Write([]byte(strings.Join(directPaths, "\n")))
Usta Shrestha2ccdb422022-06-02 10:19:13 -0400443 h.Write([]byte(strings.Join(transitiveDepsetHashes, "")))
444 fullHash := base64.RawURLEncoding.EncodeToString(h.Sum(nil))
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400445 return fullHash
446}
447
Liz Kammer00629db2023-02-09 14:28:15 -0500448func (a *aqueryArtifactHandler) depsetContentHashes(inputDepsetIds []uint32) ([]string, error) {
Usta Shrestha6298cc52022-05-27 17:40:21 -0400449 var hashes []string
Liz Kammer00629db2023-02-09 14:28:15 -0500450 for _, id := range inputDepsetIds {
451 dId := depsetId(id)
452 if aqueryDepset, exists := a.depsetIdToAqueryDepset[dId]; !exists {
453 if _, empty := a.emptyDepsetIds[dId]; !empty {
454 return nil, fmt.Errorf("undefined (not even empty) input depsetId %d", dId)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -0500455 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400456 } else {
457 hashes = append(hashes, aqueryDepset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400458 }
459 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400460 return hashes, nil
Chris Parsons1a7aca02022-04-25 22:35:15 -0400461}
462
Spandan Dasda724862023-06-16 23:35:55 +0000463// escapes the args received from aquery and creates a command string
464func commandString(actionEntry *analysis_v2_proto.Action) string {
465 switch actionEntry.Mnemonic {
Spandan Das2d93ebb2023-07-27 23:46:24 +0000466 case "GoCompilePkg", "GoStdlib":
Spandan Dasda724862023-06-16 23:35:55 +0000467 argsEscaped := []string{}
468 for _, arg := range actionEntry.Arguments {
469 if arg == "" {
470 // If this is an empty string, add ''
471 // And not
472 // 1. (literal empty)
473 // 2. `''\'''\'''` (escaped version of '')
474 //
475 // If we had used (1), then this would appear as a whitespace when we strings.Join
476 argsEscaped = append(argsEscaped, "''")
477 } else {
478 argsEscaped = append(argsEscaped, proptools.ShellEscapeIncludingSpaces(arg))
479 }
480 }
481 return strings.Join(argsEscaped, " ")
482 default:
483 return strings.Join(proptools.ShellEscapeListIncludingSpaces(actionEntry.Arguments), " ")
484 }
485}
486
Liz Kammer00629db2023-02-09 14:28:15 -0500487func (a *aqueryArtifactHandler) normalActionBuildStatement(actionEntry *analysis_v2_proto.Action) (*BuildStatement, error) {
Spandan Dasda724862023-06-16 23:35:55 +0000488 command := commandString(actionEntry)
Usta Shresthac2372492022-05-27 10:45:00 -0400489 inputDepsetHashes, err := a.depsetContentHashes(actionEntry.InputDepSetIds)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400490 if err != nil {
Liz Kammer00629db2023-02-09 14:28:15 -0500491 return nil, err
Chris Parsons1a7aca02022-04-25 22:35:15 -0400492 }
Usta Shresthac2372492022-05-27 10:45:00 -0400493 outputPaths, depfile, err := a.getOutputPaths(actionEntry)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400494 if err != nil {
Liz Kammer00629db2023-02-09 14:28:15 -0500495 return nil, err
Chris Parsons1a7aca02022-04-25 22:35:15 -0400496 }
497
Liz Kammer00629db2023-02-09 14:28:15 -0500498 buildStatement := &BuildStatement{
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400499 Command: command,
500 Depfile: depfile,
501 OutputPaths: outputPaths,
502 InputDepsetHashes: inputDepsetHashes,
503 Env: actionEntry.EnvironmentVariables,
504 Mnemonic: actionEntry.Mnemonic,
Chris Parsons1a7aca02022-04-25 22:35:15 -0400505 }
Spandan Dasaf4ccaa2023-06-29 01:15:51 +0000506 if buildStatement.Mnemonic == "GoToolchainBinaryBuild" {
507 // Unlike b's execution root, mixed build execution root contains a symlink to prebuilts/go
508 // This causes issues for `GOCACHE=$(mktemp -d) go build ...`
509 // To prevent this, sandbox this action in mixed builds as well
510 buildStatement.ShouldRunInSbox = true
511 }
Chris Parsons1a7aca02022-04-25 22:35:15 -0400512 return buildStatement, nil
513}
514
Liz Kammer00629db2023-02-09 14:28:15 -0500515func (a *aqueryArtifactHandler) templateExpandActionBuildStatement(actionEntry *analysis_v2_proto.Action) (*BuildStatement, error) {
Usta Shresthac2372492022-05-27 10:45:00 -0400516 outputPaths, depfile, err := a.getOutputPaths(actionEntry)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400517 if err != nil {
Liz Kammer00629db2023-02-09 14:28:15 -0500518 return nil, err
Chris Parsons1a7aca02022-04-25 22:35:15 -0400519 }
520 if len(outputPaths) != 1 {
Liz Kammer00629db2023-02-09 14:28:15 -0500521 return nil, fmt.Errorf("Expect 1 output to template expand action, got: output %q", outputPaths)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400522 }
523 expandedTemplateContent := expandTemplateContent(actionEntry)
524 // The expandedTemplateContent is escaped for being used in double quotes and shell unescape,
525 // and the new line characters (\n) are also changed to \\n which avoids some Ninja escape on \n, which might
526 // change \n to space and mess up the format of Python programs.
527 // sed is used to convert \\n back to \n before saving to output file.
528 // See go/python-binary-host-mixed-build for more details.
529 command := fmt.Sprintf(`/bin/bash -c 'echo "%[1]s" | sed "s/\\\\n/\\n/g" > %[2]s && chmod a+x %[2]s'`,
530 escapeCommandlineArgument(expandedTemplateContent), outputPaths[0])
Usta Shresthac2372492022-05-27 10:45:00 -0400531 inputDepsetHashes, err := a.depsetContentHashes(actionEntry.InputDepSetIds)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400532 if err != nil {
Liz Kammer00629db2023-02-09 14:28:15 -0500533 return nil, err
Chris Parsons1a7aca02022-04-25 22:35:15 -0400534 }
535
Liz Kammer00629db2023-02-09 14:28:15 -0500536 buildStatement := &BuildStatement{
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400537 Command: command,
538 Depfile: depfile,
539 OutputPaths: outputPaths,
540 InputDepsetHashes: inputDepsetHashes,
541 Env: actionEntry.EnvironmentVariables,
542 Mnemonic: actionEntry.Mnemonic,
Chris Parsons1a7aca02022-04-25 22:35:15 -0400543 }
544 return buildStatement, nil
545}
546
Liz Kammer00629db2023-02-09 14:28:15 -0500547func (a *aqueryArtifactHandler) fileWriteActionBuildStatement(actionEntry *analysis_v2_proto.Action) (*BuildStatement, error) {
Sasha Smundak1da064c2022-06-08 16:36:16 -0700548 outputPaths, _, err := a.getOutputPaths(actionEntry)
549 var depsetHashes []string
550 if err == nil {
551 depsetHashes, err = a.depsetContentHashes(actionEntry.InputDepSetIds)
552 }
553 if err != nil {
Liz Kammer00629db2023-02-09 14:28:15 -0500554 return nil, err
Sasha Smundak1da064c2022-06-08 16:36:16 -0700555 }
Liz Kammer00629db2023-02-09 14:28:15 -0500556 return &BuildStatement{
Sasha Smundak1da064c2022-06-08 16:36:16 -0700557 Depfile: nil,
558 OutputPaths: outputPaths,
559 Env: actionEntry.EnvironmentVariables,
560 Mnemonic: actionEntry.Mnemonic,
561 InputDepsetHashes: depsetHashes,
562 FileContents: actionEntry.FileContents,
563 }, nil
564}
565
Liz Kammer00629db2023-02-09 14:28:15 -0500566func (a *aqueryArtifactHandler) symlinkTreeActionBuildStatement(actionEntry *analysis_v2_proto.Action) (*BuildStatement, error) {
Sasha Smundakc180dbd2022-07-03 14:55:58 -0700567 outputPaths, _, err := a.getOutputPaths(actionEntry)
568 if err != nil {
Liz Kammer00629db2023-02-09 14:28:15 -0500569 return nil, err
Sasha Smundakc180dbd2022-07-03 14:55:58 -0700570 }
571 inputPaths, err := a.getInputPaths(actionEntry.InputDepSetIds)
572 if err != nil {
Liz Kammer00629db2023-02-09 14:28:15 -0500573 return nil, err
Sasha Smundakc180dbd2022-07-03 14:55:58 -0700574 }
575 if len(inputPaths) != 1 || len(outputPaths) != 1 {
Liz Kammer00629db2023-02-09 14:28:15 -0500576 return nil, fmt.Errorf("Expect 1 input and 1 output to symlink action, got: input %q, output %q", inputPaths, outputPaths)
Sasha Smundakc180dbd2022-07-03 14:55:58 -0700577 }
578 // The actual command is generated in bazelSingleton.GenerateBuildActions
Liz Kammer00629db2023-02-09 14:28:15 -0500579 return &BuildStatement{
Sasha Smundakc180dbd2022-07-03 14:55:58 -0700580 Depfile: nil,
581 OutputPaths: outputPaths,
582 Env: actionEntry.EnvironmentVariables,
583 Mnemonic: actionEntry.Mnemonic,
584 InputPaths: inputPaths,
585 }, nil
586}
587
Cole Faustbc65a3f2023-08-01 16:38:55 +0000588type bazelSandwichJson struct {
589 Target string `json:"target"`
590 DependOnTarget *bool `json:"depend_on_target,omitempty"`
591 ImplicitDeps []string `json:"implicit_deps"`
592}
593
594func (a *aqueryArtifactHandler) unresolvedSymlinkActionBuildStatement(actionEntry *analysis_v2_proto.Action) (*BuildStatement, error) {
595 outputPaths, depfile, err := a.getOutputPaths(actionEntry)
596 if err != nil {
597 return nil, err
598 }
599 if len(actionEntry.InputDepSetIds) != 0 || len(outputPaths) != 1 {
600 return nil, fmt.Errorf("expected 0 inputs and 1 output to symlink action, got: input %q, output %q", actionEntry.InputDepSetIds, outputPaths)
601 }
602 target := actionEntry.UnresolvedSymlinkTarget
603 if target == "" {
604 return nil, fmt.Errorf("expected an unresolved_symlink_target, but didn't get one")
605 }
606 if filepath.Clean(target) != target {
607 return nil, fmt.Errorf("expected %q, got %q", filepath.Clean(target), target)
608 }
609 if strings.HasPrefix(target, "/") {
610 return nil, fmt.Errorf("no absolute symlinks allowed: %s", target)
611 }
612
613 out := outputPaths[0]
614 outDir := filepath.Dir(out)
615 var implicitDeps []string
616 if strings.HasPrefix(target, "bazel_sandwich:") {
617 j := bazelSandwichJson{}
618 err := json.Unmarshal([]byte(target[len("bazel_sandwich:"):]), &j)
619 if err != nil {
620 return nil, err
621 }
622 if proptools.BoolDefault(j.DependOnTarget, true) {
623 implicitDeps = append(implicitDeps, j.Target)
624 }
625 implicitDeps = append(implicitDeps, j.ImplicitDeps...)
626 dotDotsToReachCwd := ""
627 if outDir != "." {
628 dotDotsToReachCwd = strings.Repeat("../", strings.Count(outDir, "/")+1)
629 }
630 target = proptools.ShellEscapeIncludingSpaces(j.Target)
631 target = "{DOTDOTS_TO_OUTPUT_ROOT}" + dotDotsToReachCwd + target
632 } else {
633 target = proptools.ShellEscapeIncludingSpaces(target)
634 }
635
636 outDir = proptools.ShellEscapeIncludingSpaces(outDir)
637 out = proptools.ShellEscapeIncludingSpaces(out)
638 // Use absolute paths, because some soong actions don't play well with relative paths (for example, `cp -d`).
639 command := fmt.Sprintf("mkdir -p %[1]s && rm -f %[2]s && ln -sf %[3]s %[2]s", outDir, out, target)
640 symlinkPaths := outputPaths[:]
641
642 buildStatement := &BuildStatement{
643 Command: command,
644 Depfile: depfile,
645 OutputPaths: outputPaths,
646 Env: actionEntry.EnvironmentVariables,
647 Mnemonic: actionEntry.Mnemonic,
648 SymlinkPaths: symlinkPaths,
649 ImplicitDeps: implicitDeps,
650 }
651 return buildStatement, nil
652}
653
Liz Kammer00629db2023-02-09 14:28:15 -0500654func (a *aqueryArtifactHandler) symlinkActionBuildStatement(actionEntry *analysis_v2_proto.Action) (*BuildStatement, error) {
Usta Shresthac2372492022-05-27 10:45:00 -0400655 outputPaths, depfile, err := a.getOutputPaths(actionEntry)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400656 if err != nil {
Liz Kammer00629db2023-02-09 14:28:15 -0500657 return nil, err
Chris Parsons1a7aca02022-04-25 22:35:15 -0400658 }
659
Usta Shresthac2372492022-05-27 10:45:00 -0400660 inputPaths, err := a.getInputPaths(actionEntry.InputDepSetIds)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400661 if err != nil {
Liz Kammer00629db2023-02-09 14:28:15 -0500662 return nil, err
Chris Parsons1a7aca02022-04-25 22:35:15 -0400663 }
664 if len(inputPaths) != 1 || len(outputPaths) != 1 {
Liz Kammer00629db2023-02-09 14:28:15 -0500665 return nil, fmt.Errorf("Expect 1 input and 1 output to symlink action, got: input %q, output %q", inputPaths, outputPaths)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400666 }
667 out := outputPaths[0]
668 outDir := proptools.ShellEscapeIncludingSpaces(filepath.Dir(out))
669 out = proptools.ShellEscapeIncludingSpaces(out)
670 in := filepath.Join("$PWD", proptools.ShellEscapeIncludingSpaces(inputPaths[0]))
671 // Use absolute paths, because some soong actions don't play well with relative paths (for example, `cp -d`).
672 command := fmt.Sprintf("mkdir -p %[1]s && rm -f %[2]s && ln -sf %[3]s %[2]s", outDir, out, in)
673 symlinkPaths := outputPaths[:]
674
Liz Kammer00629db2023-02-09 14:28:15 -0500675 buildStatement := &BuildStatement{
Chris Parsons1a7aca02022-04-25 22:35:15 -0400676 Command: command,
677 Depfile: depfile,
678 OutputPaths: outputPaths,
679 InputPaths: inputPaths,
680 Env: actionEntry.EnvironmentVariables,
681 Mnemonic: actionEntry.Mnemonic,
682 SymlinkPaths: symlinkPaths,
683 }
684 return buildStatement, nil
685}
686
Liz Kammer00629db2023-02-09 14:28:15 -0500687func (a *aqueryArtifactHandler) getOutputPaths(actionEntry *analysis_v2_proto.Action) (outputPaths []string, depfile *string, err error) {
Chris Parsons1a7aca02022-04-25 22:35:15 -0400688 for _, outputId := range actionEntry.OutputIds {
Liz Kammer00629db2023-02-09 14:28:15 -0500689 outputPath, exists := a.artifactIdToPath[artifactId(outputId)]
Chris Parsons1a7aca02022-04-25 22:35:15 -0400690 if !exists {
691 err = fmt.Errorf("undefined outputId %d", outputId)
692 return
693 }
694 ext := filepath.Ext(outputPath)
695 if ext == ".d" {
696 if depfile != nil {
697 err = fmt.Errorf("found multiple potential depfiles %q, %q", *depfile, outputPath)
698 return
699 } else {
700 depfile = &outputPath
701 }
702 } else {
703 outputPaths = append(outputPaths, outputPath)
704 }
705 }
706 return
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500707}
Chris Parsonsaffbb602020-12-23 12:02:11 -0500708
Wei Li455ba832021-11-04 22:58:12 +0000709// expandTemplateContent substitutes the tokens in a template.
Liz Kammer00629db2023-02-09 14:28:15 -0500710func expandTemplateContent(actionEntry *analysis_v2_proto.Action) string {
711 replacerString := make([]string, len(actionEntry.Substitutions)*2)
712 for i, pair := range actionEntry.Substitutions {
Wei Li455ba832021-11-04 22:58:12 +0000713 value := pair.Value
Usta Shrestha6298cc52022-05-27 17:40:21 -0400714 if val, ok := templateActionOverriddenTokens[pair.Key]; ok {
Wei Li455ba832021-11-04 22:58:12 +0000715 value = val
716 }
Liz Kammer00629db2023-02-09 14:28:15 -0500717 replacerString[i*2] = pair.Key
718 replacerString[i*2+1] = value
Wei Li455ba832021-11-04 22:58:12 +0000719 }
720 replacer := strings.NewReplacer(replacerString...)
721 return replacer.Replace(actionEntry.TemplateContent)
722}
723
Liz Kammerf15a0792023-02-09 14:28:36 -0500724// \->\\, $->\$, `->\`, "->\", \n->\\n, '->'"'"'
725var commandLineArgumentReplacer = strings.NewReplacer(
726 `\`, `\\`,
727 `$`, `\$`,
728 "`", "\\`",
729 `"`, `\"`,
730 "\n", "\\n",
731 `'`, `'"'"'`,
732)
733
Wei Li455ba832021-11-04 22:58:12 +0000734func escapeCommandlineArgument(str string) string {
Liz Kammerf15a0792023-02-09 14:28:36 -0500735 return commandLineArgumentReplacer.Replace(str)
Wei Li455ba832021-11-04 22:58:12 +0000736}
737
Liz Kammer00629db2023-02-09 14:28:15 -0500738func (a *aqueryArtifactHandler) actionToBuildStatement(actionEntry *analysis_v2_proto.Action) (*BuildStatement, error) {
739 switch actionEntry.Mnemonic {
Chris Parsonsc4fb1332021-05-18 12:31:25 -0400740 // Middleman actions are not handled like other actions; they are handled separately as a
741 // preparatory step so that their inputs may be relayed to actions depending on middleman
742 // artifacts.
Liz Kammer00629db2023-02-09 14:28:15 -0500743 case middlemanMnemonic:
744 return nil, nil
Sasha Smundakc180dbd2022-07-03 14:55:58 -0700745 // PythonZipper is bogus action returned by aquery, ignore it (b/236198693)
Liz Kammer00629db2023-02-09 14:28:15 -0500746 case "PythonZipper":
747 return nil, nil
Chris Parsons8d6e4332021-02-22 16:13:50 -0500748 // Skip "Fail" actions, which are placeholder actions designed to always fail.
Liz Kammer00629db2023-02-09 14:28:15 -0500749 case "Fail":
750 return nil, nil
751 case "BaselineCoverage":
752 return nil, nil
753 case "Symlink", "SolibSymlink", "ExecutableSymlink":
754 return a.symlinkActionBuildStatement(actionEntry)
755 case "TemplateExpand":
756 if len(actionEntry.Arguments) < 1 {
757 return a.templateExpandActionBuildStatement(actionEntry)
758 }
Cole Faust950689a2023-06-21 15:07:21 -0700759 case "FileWrite", "SourceSymlinkManifest", "RepoMappingManifest":
Liz Kammer00629db2023-02-09 14:28:15 -0500760 return a.fileWriteActionBuildStatement(actionEntry)
761 case "SymlinkTree":
762 return a.symlinkTreeActionBuildStatement(actionEntry)
Cole Faustbc65a3f2023-08-01 16:38:55 +0000763 case "UnresolvedSymlink":
764 return a.unresolvedSymlinkActionBuildStatement(actionEntry)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500765 }
Liz Kammer00629db2023-02-09 14:28:15 -0500766
767 if len(actionEntry.Arguments) < 1 {
768 return nil, fmt.Errorf("received action with no command: [%s]", actionEntry.Mnemonic)
Yu Liu8d82ac52022-05-17 15:13:28 -0700769 }
Liz Kammer00629db2023-02-09 14:28:15 -0500770 return a.normalActionBuildStatement(actionEntry)
771
Chris Parsons8d6e4332021-02-22 16:13:50 -0500772}
773
Liz Kammer00629db2023-02-09 14:28:15 -0500774func expandPathFragment(id pathFragmentId, pathFragmentsMap map[pathFragmentId]*analysis_v2_proto.PathFragment) (string, error) {
Usta Shrestha6298cc52022-05-27 17:40:21 -0400775 var labels []string
Chris Parsonsaffbb602020-12-23 12:02:11 -0500776 currId := id
777 // Only positive IDs are valid for path fragments. An ID of zero indicates a terminal node.
778 for currId > 0 {
779 currFragment, ok := pathFragmentsMap[currId]
780 if !ok {
Chris Parsons4f069892021-01-15 12:22:41 -0500781 return "", fmt.Errorf("undefined path fragment id %d", currId)
Chris Parsonsaffbb602020-12-23 12:02:11 -0500782 }
783 labels = append([]string{currFragment.Label}, labels...)
Liz Kammer00629db2023-02-09 14:28:15 -0500784 parentId := pathFragmentId(currFragment.ParentId)
785 if currId == parentId {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700786 return "", fmt.Errorf("fragment cannot refer to itself as parent %#v", currFragment)
Liz Kammerc49e6822021-06-08 15:04:11 -0400787 }
Liz Kammer00629db2023-02-09 14:28:15 -0500788 currId = parentId
Chris Parsonsaffbb602020-12-23 12:02:11 -0500789 }
790 return filepath.Join(labels...), nil
791}