blob: 9ed8f78b896b07db3d9bfcafe09edc3c5bc05fff [file] [log] [blame]
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001// 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 android
16
17import (
18 "bytes"
19 "errors"
20 "fmt"
Chris Parsonsa798d962020-10-12 23:44:08 -040021 "io/ioutil"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040022 "os"
23 "os/exec"
Usta Shresthaacd5a0c2022-06-22 11:20:50 -040024 "path"
Chris Parsonsa798d962020-10-12 23:44:08 -040025 "path/filepath"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040026 "runtime"
27 "strings"
28 "sync"
Chris Parsonsa798d962020-10-12 23:44:08 -040029
Chris Parsonsad876012022-08-20 14:48:32 -040030 "android/soong/android/allowlists"
Chris Parsons944e7d02021-03-11 11:08:46 -050031 "android/soong/bazel/cquery"
Jingwen Chen1e347862021-09-02 12:11:49 +000032 "android/soong/shared"
Liz Kammer337e9032022-08-03 15:49:43 -040033
Chris Parsons1a7aca02022-04-25 22:35:15 -040034 "github.com/google/blueprint"
Liz Kammer8206d4f2021-03-03 16:40:52 -050035
Patrice Arruda05ab2d02020-12-12 06:24:26 +000036 "android/soong/bazel"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040037)
38
Sasha Smundak1da064c2022-06-08 16:36:16 -070039var (
40 writeBazelFile = pctx.AndroidStaticRule("bazelWriteFileRule", blueprint.RuleParams{
41 Command: `sed "s/\\\\n/\n/g" ${out}.rsp >${out}`,
42 Rspfile: "${out}.rsp",
43 RspfileContent: "${content}",
44 }, "content")
Sasha Smundakc180dbd2022-07-03 14:55:58 -070045 _ = pctx.HostBinToolVariable("bazelBuildRunfilesTool", "build-runfiles")
46 buildRunfilesRule = pctx.AndroidStaticRule("bazelBuildRunfiles", blueprint.RuleParams{
47 Command: "${bazelBuildRunfilesTool} ${in} ${outDir}",
48 Depfile: "",
49 Description: "",
50 CommandDeps: []string{"${bazelBuildRunfilesTool}"},
51 }, "outDir")
Sasha Smundak1da064c2022-06-08 16:36:16 -070052)
53
Chris Parsonsf874e462022-05-10 13:50:12 -040054func init() {
55 RegisterMixedBuildsMutator(InitRegistrationContext)
56}
57
58func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammer337e9032022-08-03 15:49:43 -040059 ctx.FinalDepsMutators(func(ctx RegisterMutatorsContext) {
Chris Parsonsf874e462022-05-10 13:50:12 -040060 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
61 })
62}
63
64func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
65 if m := ctx.Module(); m.Enabled() {
66 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
67 if mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx) {
68 mixedBuildMod.QueueBazelCall(ctx)
69 }
70 }
71 }
72}
73
Liz Kammerf29df7c2021-04-02 13:37:39 -040074type cqueryRequest interface {
75 // Name returns a string name for this request type. Such request type names must be unique,
76 // and must only consist of alphanumeric characters.
77 Name() string
78
79 // StarlarkFunctionBody returns a starlark function body to process this request type.
80 // The returned string is the body of a Starlark function which obtains
81 // all request-relevant information about a target and returns a string containing
82 // this information.
83 // The function should have the following properties:
84 // - `target` is the only parameter to this function (a configured target).
85 // - The return value must be a string.
86 // - The function body should not be indented outside of its own scope.
87 StarlarkFunctionBody() string
88}
89
Chris Parsons787fb362021-10-14 18:43:51 -040090// Portion of cquery map key to describe target configuration.
91type configKey struct {
Liz Kammer0940b892022-03-18 15:55:04 -040092 arch string
93 osType OsType
Chris Parsons787fb362021-10-14 18:43:51 -040094}
95
Sasha Smundakfe9a5b82022-07-27 14:51:45 -070096func (c configKey) String() string {
97 return fmt.Sprintf("%s::%s", c.arch, c.osType)
98}
99
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400100// Map key to describe bazel cquery requests.
101type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400102 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400103 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400104 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400105}
106
Chris Parsons86dc2c22022-09-28 14:58:41 -0400107func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
108 if strings.HasPrefix(label, "//") {
109 // Normalize Bazel labels to specify main repository explicitly.
110 label = "@" + label
111 }
112 return cqueryKey{label, cqueryRequest, cfgKey}
113}
114
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700115func (c cqueryKey) String() string {
116 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700117}
118
Chris Parsonsf874e462022-05-10 13:50:12 -0400119// BazelContext is a context object useful for interacting with Bazel during
120// the course of a build. Use of Bazel to evaluate part of the build graph
121// is referred to as a "mixed build". (Some modules are managed by Soong,
122// some are managed by Bazel). To facilitate interop between these build
123// subgraphs, Soong may make requests to Bazel and evaluate their responses
124// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400125type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400126 // Add a cquery request to the bazel request queue. All queued requests
127 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
128 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
129
130 // ** Cquery Results Retrieval Functions
131 // The below functions pertain to retrieving cquery results from a prior
132 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400133
134 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400135 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500136
Chris Parsons944e7d02021-03-11 11:08:46 -0500137 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400138 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400139
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000140 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400141 // TODO(b/232976601): Remove.
142 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000143
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700144 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400145 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700146
Sasha Smundakedd16662022-10-07 14:44:50 -0700147 // Returns the results of the GetCcUnstrippedInfo query
148 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
149
Chris Parsonsf874e462022-05-10 13:50:12 -0400150 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400151
152 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800153 // queued in the BazelContext. The ctx argument is optional and is only
154 // used for performance data collection
155 InvokeBazel(config Config, ctx *Context) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400156
Chris Parsonsad876012022-08-20 14:48:32 -0400157 // Returns true if Bazel handling is enabled for the module with the given name.
158 // Note that this only implies "bazel mixed build" allowlisting. The caller
159 // should independently verify the module is eligible for Bazel handling
160 // (for example, that it is MixedBuildBuildable).
161 BazelAllowlisted(moduleName string) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500162
163 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
164 OutputBase() string
165
166 // Returns build statements which should get registered to reflect Bazel's outputs.
167 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400168
169 // Returns the depsets defined in Bazel's aquery response.
170 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400171}
172
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400173type bazelRunner interface {
Jason Wu52cd1942022-09-08 15:37:57 +0000174 createBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) *exec.Cmd
175 issueBazelCommand(bazelCmd *exec.Cmd) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400176}
177
178type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000179 homeDir string
180 bazelPath string
181 outputBase string
182 workspaceDir string
183 soongOutDir string
184 metricsDir string
185 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400186}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400187
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400188// A context object which tracks queued requests that need to be made to Bazel,
189// and their results after the requests have been made.
190type bazelContext struct {
191 bazelRunner
192 paths *bazelPaths
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400193 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
194 requestMutex sync.Mutex // requests can be written in parallel
195
196 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500197
198 // Build statements which should get registered to reflect Bazel's outputs.
199 buildStatements []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400200
201 // Depsets which should be used for Bazel's build statements.
202 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400203
204 // Per-module allowlist/denylist functionality to control whether analysis of
205 // modules are handled by Bazel. For modules which do not have a Bazel definition
206 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
207 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
208 // Per-module denylist to opt modules out of bazel handling.
209 bazelDisabledModules map[string]bool
210 // Per-module allowlist to opt modules in to bazel handling.
211 bazelEnabledModules map[string]bool
212 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
213 modulesDefaultToBazel bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400214}
215
216var _ BazelContext = &bazelContext{}
217
218// A bazel context to use when Bazel is disabled.
219type noopBazelContext struct{}
220
221var _ BazelContext = noopBazelContext{}
222
223// A bazel context to use for tests.
224type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400225 OutputBaseDir string
226
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000227 LabelToOutputFiles map[string][]string
228 LabelToCcInfo map[string]cquery.CcInfo
229 LabelToPythonBinary map[string]string
Liz Kammerbe6a7122022-11-04 16:05:11 -0400230 LabelToApexInfo map[string]cquery.ApexInfo
Sasha Smundakedd16662022-10-07 14:44:50 -0700231 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400232}
233
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700234func (m MockBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400235 panic("unimplemented")
Chris Parsons8d6e4332021-02-22 16:13:50 -0500236}
237
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700238func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400239 result, _ := m.LabelToOutputFiles[label]
240 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400241}
242
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700243func (m MockBazelContext) GetCcInfo(label string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400244 result, _ := m.LabelToCcInfo[label]
245 return result, nil
246}
247
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700248func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400249 result, _ := m.LabelToPythonBinary[label]
250 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000251}
252
Liz Kammerbe6a7122022-11-04 16:05:11 -0400253func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Liz Kammer0e255ef2022-11-04 16:07:04 -0400254 result, _ := m.LabelToApexInfo[label]
255 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700256}
257
Sasha Smundakedd16662022-10-07 14:44:50 -0700258func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
259 result, _ := m.LabelToCcBinary[label]
260 return result, nil
261}
262
Sasha Smundak4975c822022-11-16 15:28:18 -0800263func (m MockBazelContext) InvokeBazel(_ Config, ctx *Context) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400264 panic("unimplemented")
265}
266
Chris Parsonsad876012022-08-20 14:48:32 -0400267func (m MockBazelContext) BazelAllowlisted(moduleName string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400268 return true
269}
270
Liz Kammera92e8442021-04-07 20:25:21 -0400271func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500272
273func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
274 return []bazel.BuildStatement{}
275}
276
Chris Parsons1a7aca02022-04-25 22:35:15 -0400277func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
278 return []bazel.AqueryDepset{}
279}
280
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400281var _ BazelContext = MockBazelContext{}
282
Chris Parsonsf874e462022-05-10 13:50:12 -0400283func (bazelCtx *bazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400284 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400285 bazelCtx.requestMutex.Lock()
286 defer bazelCtx.requestMutex.Unlock()
287 bazelCtx.requests[key] = true
288}
289
290func (bazelCtx *bazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400291 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400292 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500293 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400294
Chris Parsonsf874e462022-05-10 13:50:12 -0400295 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400296 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400297 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400298}
299
Chris Parsonsf874e462022-05-10 13:50:12 -0400300func (bazelCtx *bazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400301 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400302 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000303 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400304 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000305 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400306 return cquery.CcInfo{}, fmt.Errorf("no bazel response found for %v", key)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000307}
308
Chris Parsonsf874e462022-05-10 13:50:12 -0400309func (bazelCtx *bazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400310 key := makeCqueryKey(label, cquery.GetPythonBinary, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400311 if rawString, ok := bazelCtx.results[key]; ok {
312 bazelOutput := strings.TrimSpace(rawString)
313 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
314 }
315 return "", fmt.Errorf("no bazel response found for %v", key)
316}
317
Liz Kammerbe6a7122022-11-04 16:05:11 -0400318func (bazelCtx *bazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400319 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700320 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500321 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700322 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400323 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700324}
325
Sasha Smundakedd16662022-10-07 14:44:50 -0700326func (bazelCtx *bazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
327 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
328 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500329 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700330 }
331 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
332}
333
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700334func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500335 panic("unimplemented")
336}
337
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700338func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500339 panic("unimplemented")
340}
341
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700342func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400343 panic("unimplemented")
344}
345
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700346func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000347 panic("unimplemented")
348}
349
Liz Kammerbe6a7122022-11-04 16:05:11 -0400350func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700351 panic("unimplemented")
352}
353
Sasha Smundakedd16662022-10-07 14:44:50 -0700354func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
355 //TODO implement me
356 panic("implement me")
357}
358
Sasha Smundak4975c822022-11-16 15:28:18 -0800359func (n noopBazelContext) InvokeBazel(_ Config, ctx *Context) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400360 panic("unimplemented")
361}
362
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500363func (m noopBazelContext) OutputBase() string {
364 return ""
365}
366
Chris Parsonsad876012022-08-20 14:48:32 -0400367func (n noopBazelContext) BazelAllowlisted(moduleName string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400368 return false
369}
370
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500371func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
372 return []bazel.BuildStatement{}
373}
374
Chris Parsons1a7aca02022-04-25 22:35:15 -0400375func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
376 return []bazel.AqueryDepset{}
377}
378
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400379func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400380 var modulesDefaultToBazel bool
381 disabledModules := map[string]bool{}
382 enabledModules := map[string]bool{}
383
384 switch c.BuildMode {
385 case BazelProdMode:
386 modulesDefaultToBazel = false
387
388 for _, enabledProdModule := range allowlists.ProdMixedBuildsEnabledList {
389 enabledModules[enabledProdModule] = true
390 }
MarkDacekb78465d2022-10-18 20:10:16 +0000391 case BazelStagingMode:
392 modulesDefaultToBazel = false
Chris Parsons66fc7452022-11-04 13:26:17 -0400393 // Staging mode includes all prod modules plus all staging modules.
394 for _, enabledProdModule := range allowlists.ProdMixedBuildsEnabledList {
395 enabledModules[enabledProdModule] = true
396 }
MarkDacekb78465d2022-10-18 20:10:16 +0000397 for _, enabledStagingMode := range allowlists.StagingMixedBuildsEnabledList {
398 enabledModules[enabledStagingMode] = true
MarkDacekb78465d2022-10-18 20:10:16 +0000399 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400400 case BazelDevMode:
401 modulesDefaultToBazel = true
402
403 // Don't use partially-converted cc_library targets in mixed builds,
404 // since mixed builds would generally rely on both static and shared
405 // variants of a cc_library.
406 for staticOnlyModule, _ := range GetBp2BuildAllowList().ccLibraryStaticOnly {
407 disabledModules[staticOnlyModule] = true
408 }
409 for _, disabledDevModule := range allowlists.MixedBuildsDisabledList {
410 disabledModules[disabledDevModule] = true
411 }
412 default:
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400413 return noopBazelContext{}, nil
414 }
415
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400416 p, err := bazelPathsFromConfig(c)
417 if err != nil {
418 return nil, err
419 }
Chris Parsonsad876012022-08-20 14:48:32 -0400420
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400421 return &bazelContext{
Chris Parsonsad876012022-08-20 14:48:32 -0400422 bazelRunner: &builtinBazelRunner{},
423 paths: p,
424 requests: make(map[cqueryKey]bool),
Chris Parsonsef615e52022-08-18 22:04:11 -0400425 modulesDefaultToBazel: modulesDefaultToBazel,
426 bazelEnabledModules: enabledModules,
Chris Parsonsad876012022-08-20 14:48:32 -0400427 bazelDisabledModules: disabledModules,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400428 }, nil
429}
430
431func bazelPathsFromConfig(c *config) (*bazelPaths, error) {
432 p := bazelPaths{
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200433 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400434 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700435 var missingEnvVars []string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400436 if len(c.Getenv("BAZEL_HOME")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400437 p.homeDir = c.Getenv("BAZEL_HOME")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400438 } else {
439 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
440 }
441 if len(c.Getenv("BAZEL_PATH")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400442 p.bazelPath = c.Getenv("BAZEL_PATH")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400443 } else {
444 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
445 }
446 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400447 p.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400448 } else {
449 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
450 }
451 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400452 p.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400453 } else {
454 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
455 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000456 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400457 p.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000458 } else {
459 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
460 }
MarkDacek0d5bca52022-10-10 20:07:48 +0000461 if len(c.Getenv("BAZEL_DEPS_FILE")) > 1 {
462 p.bazelDepsFile = c.Getenv("BAZEL_DEPS_FILE")
463 } else {
464 missingEnvVars = append(missingEnvVars, "BAZEL_DEPS_FILE")
465 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400466 if len(missingEnvVars) > 0 {
467 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
468 } else {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400469 return &p, nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400470 }
471}
472
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400473func (p *bazelPaths) BazelMetricsDir() string {
474 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000475}
476
Chris Parsonsad876012022-08-20 14:48:32 -0400477func (context *bazelContext) BazelAllowlisted(moduleName string) bool {
478 if context.bazelDisabledModules[moduleName] {
479 return false
480 }
481 if context.bazelEnabledModules[moduleName] {
482 return true
483 }
484 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400485}
486
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400487func pwdPrefix() string {
488 // Darwin doesn't have /proc
489 if runtime.GOOS != "darwin" {
490 return "PWD=/proc/self/cwd"
491 }
492 return ""
493}
494
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400495type bazelCommand struct {
496 command string
497 // query or label
498 expression string
499}
500
501type mockBazelRunner struct {
502 bazelCommandResults map[bazelCommand]string
Jason Wu52cd1942022-09-08 15:37:57 +0000503 // use *exec.Cmd as a key to get the bazelCommand, the map will be used in issueBazelCommand()
504 // Register createBazelCommand() invocations. Later, an
505 // issueBazelCommand() invocation can be mapped to the *exec.Cmd instance
506 // and then to the expected result via bazelCommandResults
507 tokens map[*exec.Cmd]bazelCommand
508 commands []bazelCommand
509 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400510}
511
Jason Wu52cd1942022-09-08 15:37:57 +0000512func (r *mockBazelRunner) createBazelCommand(paths *bazelPaths, runName bazel.RunName,
513 command bazelCommand, extraFlags ...string) *exec.Cmd {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400514 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700515 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Jason Wu52cd1942022-09-08 15:37:57 +0000516 cmd := &exec.Cmd{}
517 if r.tokens == nil {
518 r.tokens = make(map[*exec.Cmd]bazelCommand)
519 }
520 r.tokens[cmd] = command
521 return cmd
522}
523
524func (r *mockBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
525 if command, ok := r.tokens[bazelCmd]; ok {
526 return r.bazelCommandResults[command], "", nil
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400527 }
528 return "", "", nil
529}
530
531type builtinBazelRunner struct{}
532
Chris Parsons808d84c2021-03-09 20:43:32 -0500533// Issues the given bazel command with given build label and additional flags.
534// Returns (stdout, stderr, error). The first and second return values are strings
535// containing the stdout and stderr of the run command, and an error is returned if
536// the invocation returned an error code.
Jason Wu52cd1942022-09-08 15:37:57 +0000537
538func (r *builtinBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
539 stderr := &bytes.Buffer{}
540 bazelCmd.Stderr = stderr
541 if output, err := bazelCmd.Output(); err != nil {
542 return "", string(stderr.Bytes()),
543 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
544 } else {
545 return string(output), string(stderr.Bytes()), nil
546 }
547}
548
549func (r *builtinBazelRunner) createBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
550 extraFlags ...string) *exec.Cmd {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000551 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000552 "--output_base=" + absolutePath(paths.outputBase),
553 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700554 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700555 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700556 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400557
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700558 // Set default platforms to canonicalized values for mixed builds requests.
559 // If these are set in the bazelrc, they will have values that are
560 // non-canonicalized to @sourceroot labels, and thus be invalid when
561 // referenced from the buildroot.
562 //
563 // The actual platform values here may be overridden by configuration
564 // transitions from the buildroot.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700565 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700566 // This should be parameterized on the host OS, but let's restrict to linux
567 // to keep things simple for now.
568 fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"),
569
570 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
571 "--experimental_repository_disable_download",
572
573 // Suppress noise
574 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500575 "--noshow_progress",
576 "--norun_validations",
577 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400578 cmdFlags = append(cmdFlags, extraFlags...)
579
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400580 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200581 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700582 extraEnv := []string{
583 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200584 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700585 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700586 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000587 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700588 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500589 // Disables local host detection of gcc; toolchain information is defined
590 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700591 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
592 }
593 bazelCmd.Env = append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400594
Jason Wu52cd1942022-09-08 15:37:57 +0000595 return bazelCmd
596}
597
598func printableCqueryCommand(bazelCmd *exec.Cmd) string {
599 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(bazelCmd.Args, "\" \"") + "\""
600 return outputString
601
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400602}
603
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400604func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500605 // TODO(cparsons): Define configuration transitions programmatically based
606 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400607 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500608#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400609# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500610#####################################################
611
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400612def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500613 return {
Chris Parsons787fb362021-10-14 18:43:51 -0400614 "//command_line_option:platforms": "@//build/bazel/platforms:%s_%s" % (attr.os, attr.arch),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500615 }
616
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400617_config_node_transition = transition(
618 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500619 inputs = [],
620 outputs = [
621 "//command_line_option:platforms",
622 ],
623)
624
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400625def _passthrough_rule_impl(ctx):
626 return [DefaultInfo(files = depset(ctx.files.deps))]
627
628config_node = rule(
629 implementation = _passthrough_rule_impl,
630 attrs = {
631 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400632 "os" : attr.string(mandatory = True),
633 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400634 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
635 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500636)
637
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400638
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500639# Rule representing the root of the build, to depend on all Bazel targets that
640# are required for the build. Building this target will build the entire Bazel
641# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400642mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400643 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500644 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400645 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500646 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400647)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500648
649def _phony_root_impl(ctx):
650 return []
651
652# Rule to depend on other targets but build nothing.
653# This is useful as follows: building a target of this rule will generate
654# symlink forests for all dependencies of the target, without executing any
655# actions of the build.
656phony_root = rule(
657 implementation = _phony_root_impl,
658 attrs = {"deps" : attr.label_list()},
659)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400660`
661 return []byte(contents)
662}
663
664func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500665 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
666 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400667 formatString := `
668# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400669load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
670
671%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400672
673mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400674 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400675)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500676
677phony_root(name = "phonyroot",
678 deps = [":buildroot"],
679)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400680`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400681 configNodeFormatString := `
682config_node(name = "%s",
683 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400684 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400685 deps = [%s],
686)
687`
688
689 configNodesSection := ""
690
Chris Parsons787fb362021-10-14 18:43:51 -0400691 labelsByConfig := map[string][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400692 for val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200693 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400694 configString := getConfigString(val)
695 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400696 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400697
Jingwen Chen1e347862021-09-02 12:11:49 +0000698 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400699 for configString, labels := range labelsByConfig {
700 configTokens := strings.Split(configString, "|")
701 if len(configTokens) != 2 {
702 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000703 }
Chris Parsons787fb362021-10-14 18:43:51 -0400704 archString := configTokens[0]
705 osString := configTokens[1]
706 targetString := fmt.Sprintf("%s_%s", osString, archString)
707 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
708 labelsString := strings.Join(labels, ",\n ")
709 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400710 }
711
Jingwen Chen1e347862021-09-02 12:11:49 +0000712 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400713}
714
Chris Parsons944e7d02021-03-11 11:08:46 -0500715func indent(original string) string {
716 result := ""
717 for _, line := range strings.Split(original, "\n") {
718 result += " " + line + "\n"
719 }
720 return result
721}
722
Chris Parsons808d84c2021-03-09 20:43:32 -0500723// Returns the file contents of the buildroot.cquery file that should be used for the cquery
724// expression in order to obtain information about buildroot and its dependencies.
725// The contents of this file depend on the bazelContext's requests; requests are enumerated
726// and grouped by their request type. The data retrieved for each label depends on its
727// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400728func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400729 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400730 for val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500731 cqueryId := getCqueryId(val)
732 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
733 requestTypeToCqueryIdEntries[val.requestType] =
734 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
735 }
736 labelRegistrationMapSection := ""
737 functionDefSection := ""
738 mainSwitchSection := ""
739
740 mapDeclarationFormatString := `
741%s = {
742 %s
743}
744`
745 functionDefFormatString := `
746def %s(target):
747%s
748`
749 mainSwitchSectionFormatString := `
750 if id_string in %s:
751 return id_string + ">>" + %s(target)
752`
753
Usta Shrestha0b52d832022-02-04 21:37:39 -0500754 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500755 labelMapName := requestType.Name() + "_Labels"
756 functionName := requestType.Name() + "_Fn"
757 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
758 labelMapName,
759 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
760 functionDefSection += fmt.Sprintf(functionDefFormatString,
761 functionName,
762 indent(requestType.StarlarkFunctionBody()))
763 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
764 labelMapName, functionName)
765 }
766
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400767 formatString := `
768# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400769
Usta Shrestha79fccef2022-09-02 18:37:40 -0400770# a drop-in replacement for json.encode(), not available in cquery environment
771# TODO(cparsons): bring json module in and remove this function
772def json_encode(input):
773 # Avoiding recursion by limiting
774 # - a dict to contain anything except a dict
775 # - a list to contain only primitives
776 def encode_primitive(p):
777 t = type(p)
778 if t == "string" or t == "int":
779 return repr(p)
780 fail("unsupported value '%%s' of type '%%s'" %% (p, type(p)))
781
782 def encode_list(list):
783 return "[%%s]" %% ", ".join([encode_primitive(item) for item in list])
784
785 def encode_list_or_primitive(v):
786 return encode_list(v) if type(v) == "list" else encode_primitive(v)
787
788 if type(input) == "dict":
789 # TODO(juu): the result is read line by line so can't use '\n' yet
790 kv_pairs = [("%%s: %%s" %% (encode_primitive(k), encode_list_or_primitive(v))) for (k, v) in input.items()]
791 return "{ %%s }" %% ", ".join(kv_pairs)
792 else:
793 return encode_list_or_primitive(input)
794
Chris Parsons944e7d02021-03-11 11:08:46 -0500795# Label Map Section
796%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500797
Chris Parsons944e7d02021-03-11 11:08:46 -0500798# Function Def Section
799%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500800
801def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400802 # TODO(b/199363072): filegroups and file targets aren't associated with any
803 # specific platform architecture in mixed builds. This is consistent with how
804 # Soong treats filegroups, but it may not be the case with manually-written
805 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500806 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000807 if buildoptions == None:
808 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400809 # any specific platform architecture in mixed builds, so use the host.
810 return "x86_64|linux"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500811 platforms = build_options(target)["//command_line_option:platforms"]
812 if len(platforms) != 1:
813 # An individual configured target should have only one platform architecture.
814 # Note that it's fine for there to be multiple architectures for the same label,
815 # but each is its own configured target.
816 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
817 platform_name = build_options(target)["//command_line_option:platforms"][0].name
818 if platform_name == "host":
819 return "HOST"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400820 elif platform_name.startswith("android_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400821 return platform_name[len("android_"):] + "|" + platform_name[:len("android_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400822 elif platform_name.startswith("linux_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400823 return platform_name[len("linux_"):] + "|" + platform_name[:len("linux_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400824 else:
825 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500826 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500827
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400828def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500829 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500830
Chris Parsons86dc2c22022-09-28 14:58:41 -0400831 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
832 if id_string.startswith("//"):
833 id_string = "@" + id_string
834
Chris Parsons944e7d02021-03-11 11:08:46 -0500835 # Main switch section
836 %s
837 # This target was not requested via cquery, and thus must be a dependency
838 # of a requested target.
839 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400840`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400841
Chris Parsons944e7d02021-03-11 11:08:46 -0500842 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
843 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400844}
845
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200846// Returns a path containing build-related metadata required for interfacing
847// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400848func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200849 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500850}
851
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200852// Returns the path where the contents of the @soong_injection repository live.
853// It is used by Soong to tell Bazel things it cannot over the command line.
854func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200855 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200856}
857
858// Returns the path of the synthetic Bazel workspace that contains a symlink
859// forest composed the whole source tree and BUILD files generated by bp2build.
860func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200861 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200862}
863
Jingwen Chen8c523582021-06-01 11:19:53 +0000864// Returns the path to the top level out dir ($OUT_DIR).
865func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200866 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000867}
868
Sasha Smundak4975c822022-11-16 15:28:18 -0800869const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
870
871var (
872 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
873 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
874 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
875)
876
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400877// Issues commands to Bazel to receive results for all cquery requests
878// queued in the BazelContext.
Sasha Smundak4975c822022-11-16 15:28:18 -0800879func (context *bazelContext) InvokeBazel(config Config, ctx *Context) error {
880 if ctx != nil {
881 ctx.EventHandler.Begin("bazel")
882 defer ctx.EventHandler.End("bazel")
883 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400884
Sasha Smundak4975c822022-11-16 15:28:18 -0800885 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
886 if err := os.MkdirAll(metricsDir, 0777); err != nil {
887 return err
888 }
889 }
890 context.results = make(map[cqueryKey]string)
891 if err := context.runCquery(ctx); err != nil {
892 return err
893 }
894 if err := context.runAquery(config, ctx); err != nil {
895 return err
896 }
897 if err := context.generateBazelSymlinks(ctx); err != nil {
898 return err
899 }
900
901 // Clear requests.
902 context.requests = map[cqueryKey]bool{}
903 return nil
904}
905
906func (context *bazelContext) runCquery(ctx *Context) error {
907 if ctx != nil {
908 ctx.EventHandler.Begin("cquery")
909 defer ctx.EventHandler.End("cquery")
910 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200911 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200912 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
913 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
914 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -0500915 if err != nil {
916 return err
917 }
918 }
Wei Licbd181c2022-11-16 08:59:23 -0800919 if err := ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200920 return err
921 }
Wei Licbd181c2022-11-16 08:59:23 -0800922 if err := ioutil.WriteFile(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400923 return err
924 }
Wei Licbd181c2022-11-16 08:59:23 -0800925 if err := ioutil.WriteFile(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400926 return err
927 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200928 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Wei Licbd181c2022-11-16 08:59:23 -0800929 if err := ioutil.WriteFile(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400930 return err
931 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000932
Jason Wu52cd1942022-09-08 15:37:57 +0000933 cqueryCommandWithFlag := context.createBazelCommand(context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700934 "--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
Wei Licbd181c2022-11-16 08:59:23 -0800935 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCommandWithFlag)
936 if cqueryErr != nil {
937 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -0500938 }
Jason Wu52cd1942022-09-08 15:37:57 +0000939 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", printableCqueryCommand(cqueryCommandWithFlag))
Wei Licbd181c2022-11-16 08:59:23 -0800940 if err := ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400941 return err
942 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400943 cqueryResults := map[string]string{}
944 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
945 if strings.Contains(outputLine, ">>") {
946 splitLine := strings.SplitN(outputLine, ">>", 2)
947 cqueryResults[splitLine[0]] = splitLine[1]
948 }
949 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500950 for val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500951 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -0500952 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400953 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500954 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -0800955 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400956 }
957 }
Sasha Smundak4975c822022-11-16 15:28:18 -0800958 return nil
959}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400960
Sasha Smundak4975c822022-11-16 15:28:18 -0800961func (context *bazelContext) runAquery(config Config, ctx *Context) error {
962 if ctx != nil {
963 ctx.EventHandler.Begin("aquery")
964 defer ctx.EventHandler.End("aquery")
965 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500966 // Issue an aquery command to retrieve action information about the bazel build tree.
967 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700968 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
969 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +0000970 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -0700971 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700972 extraFlags = append(extraFlags, "--collect_code_coverage")
973 paths := make([]string, 0, 2)
974 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Wei Licbd181c2022-11-16 08:59:23 -0800975 for i, _ := range p {
976 // TODO(b/259404593) convert path wildcard to regex values
977 if p[i] == "*" {
978 p[i] = ".*"
979 }
980 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700981 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
982 }
983 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
984 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
985 }
986 if len(paths) > 0 {
987 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -0700988 }
989 }
Sasha Smundak4975c822022-11-16 15:28:18 -0800990 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
991 extraFlags...))
992 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -0500993 return err
994 }
Sasha Smundak4975c822022-11-16 15:28:18 -0800995 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
996 return err
997}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500998
Sasha Smundak4975c822022-11-16 15:28:18 -0800999func (context *bazelContext) generateBazelSymlinks(ctx *Context) error {
1000 if ctx != nil {
1001 ctx.EventHandler.Begin("symlinks")
1002 defer ctx.EventHandler.End("symlinks")
1003 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001004 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1005 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1006 // but some of symlinks may be required to resolve source dependencies of the build.
Sasha Smundak4975c822022-11-16 15:28:18 -08001007 _, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd))
1008 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001009}
Chris Parsonsa798d962020-10-12 23:44:08 -04001010
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001011func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
1012 return context.buildStatements
1013}
1014
Chris Parsons1a7aca02022-04-25 22:35:15 -04001015func (context *bazelContext) AqueryDepsets() []bazel.AqueryDepset {
1016 return context.depsets
1017}
1018
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001019func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001020 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001021}
1022
Chris Parsonsa798d962020-10-12 23:44:08 -04001023// Singleton used for registering BUILD file ninja dependencies (needed
1024// for correctness of builds which use Bazel.
1025func BazelSingleton() Singleton {
1026 return &bazelSingleton{}
1027}
1028
1029type bazelSingleton struct{}
1030
1031func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001032 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001033 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001034 return
1035 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001036
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001037 // Add ninja file dependencies for files which all bazel invocations require.
1038 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001039 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001040 ctx.AddNinjaFileDeps(bazelBuildList)
1041
1042 data, err := ioutil.ReadFile(bazelBuildList)
1043 if err != nil {
1044 ctx.Errorf(err.Error())
1045 }
1046 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1047 for _, file := range files {
1048 ctx.AddNinjaFileDeps(file)
1049 }
1050
Chris Parsons1a7aca02022-04-25 22:35:15 -04001051 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1052 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001053 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001054 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1055 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001056 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1057 }
1058 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001059 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1060 if artifactPath == "bazel-out/volatile-status.txt" {
1061 // See https://bazel.build/docs/user-manual#workspace-status
1062 orderOnlies = append(orderOnlies, pathInBazelOut)
1063 } else {
1064 outputs = append(outputs, pathInBazelOut)
1065 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001066 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001067 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001068 ctx.Build(pctx, BuildParams{
1069 Rule: blueprint.Phony,
1070 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1071 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001072 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001073 })
1074 }
1075
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001076 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1077 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001078 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -07001079 if len(buildStatement.Command) > 0 {
1080 rule := NewRuleBuilder(pctx, ctx)
1081 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1082 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1083 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1084 continue
1085 }
1086 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1087 // and thus require special treatment. If BuildStatement were an interface implementing
1088 // buildRule(ctx) function, the code here would just call it.
1089 // Unfortunately, the BuildStatement is defined in
1090 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1091 // because this would cause circular dependency. So, until we move aquery processing
1092 // to the 'android' package, we need to handle special cases here.
1093 if buildStatement.Mnemonic == "FileWrite" || buildStatement.Mnemonic == "SourceSymlinkManifest" {
1094 // Pass file contents as the value of the rule's "content" argument.
1095 // Escape newlines and $ in the contents (the action "writeBazelFile" restores "\\n"
1096 // back to the newline, and Ninja reads $$ as $.
1097 escaped := strings.ReplaceAll(strings.ReplaceAll(buildStatement.FileContents, "\n", "\\n"),
1098 "$", "$$")
1099 ctx.Build(pctx, BuildParams{
1100 Rule: writeBazelFile,
1101 Output: PathForBazelOut(ctx, buildStatement.OutputPaths[0]),
1102 Description: fmt.Sprintf("%s %s", buildStatement.Mnemonic, buildStatement.OutputPaths[0]),
1103 Args: map[string]string{
1104 "content": escaped,
1105 },
1106 })
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001107 } else if buildStatement.Mnemonic == "SymlinkTree" {
1108 // build-runfiles arguments are the manifest file and the target directory
1109 // where it creates the symlink tree according to this manifest (and then
1110 // writes the MANIFEST file to it).
1111 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1112 outManifestPath := outManifest.String()
1113 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1114 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1115 }
1116 outDir := filepath.Dir(outManifestPath)
1117 ctx.Build(pctx, BuildParams{
1118 Rule: buildRunfilesRule,
1119 Output: outManifest,
1120 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1121 Description: "symlink tree for " + outDir,
1122 Args: map[string]string{
1123 "outDir": outDir,
1124 },
1125 })
Sasha Smundak1da064c2022-06-08 16:36:16 -07001126 } else {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001127 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001128 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001129 }
1130}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001131
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001132// Register bazel-owned build statements (obtained from the aquery invocation).
1133func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx PathContext) {
1134 // executionRoot is the action cwd.
1135 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1136
1137 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1138 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001139 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001140 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001141 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001142 }
1143 cmd.Text("&&")
1144 }
1145
1146 for _, pair := range buildStatement.Env {
1147 // Set per-action env variables, if any.
1148 cmd.Flag(pair.Key + "=" + pair.Value)
1149 }
1150
1151 // The actual Bazel action.
1152 cmd.Text(buildStatement.Command)
1153
1154 for _, outputPath := range buildStatement.OutputPaths {
1155 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1156 }
1157 for _, inputPath := range buildStatement.InputPaths {
1158 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1159 }
1160 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1161 otherDepsetName := bazelDepsetName(inputDepsetHash)
1162 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1163 }
1164
1165 if depfile := buildStatement.Depfile; depfile != nil {
1166 // The paths in depfile are relative to `executionRoot`.
1167 // Hence, they need to be corrected by replacing "bazel-out"
1168 // with the full `bazelOutDir`.
1169 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1170 // would be deemed missing.
1171 // (Note: The regexp uses a capture group because the version of sed
1172 // does not support a look-behind pattern.)
1173 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1174 bazelOutDir, *depfile)
1175 cmd.Text(replacement)
1176 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1177 }
1178
1179 for _, symlinkPath := range buildStatement.SymlinkPaths {
1180 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1181 }
1182}
1183
Chris Parsons8d6e4332021-02-22 16:13:50 -05001184func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001185 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001186}
1187
Chris Parsons787fb362021-10-14 18:43:51 -04001188func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001189 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001190 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001191 if key.configKey.osType.Class == Device {
1192 // For the generic Android, the expected result is "target|android", which
1193 // corresponds to the product_variable_config named "android_target" in
1194 // build/bazel/platforms/BUILD.bazel.
1195 arch = "target"
1196 } else {
1197 // Use host platform, which is currently hardcoded to be x86_64.
1198 arch = "x86_64"
1199 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001200 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001201 osName := key.configKey.osType.Name
1202 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" {
Chris Parsons787fb362021-10-14 18:43:51 -04001203 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001204 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001205 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001206 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -04001207}
1208
Chris Parsonsf874e462022-05-10 13:50:12 -04001209func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001210 return configKey{
1211 // use string because Arch is not a valid key in go
1212 arch: ctx.Arch().String(),
1213 osType: ctx.Os(),
1214 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001215}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001216
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001217func bazelDepsetName(contentHash string) string {
1218 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001219}