blob: 1c5860a5a231f79e2e3f54d1027d760468b8e113 [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"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040019 "fmt"
20 "os"
21 "os/exec"
Usta Shresthaacd5a0c2022-06-22 11:20:50 -040022 "path"
Chris Parsonsa798d962020-10-12 23:44:08 -040023 "path/filepath"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040024 "runtime"
25 "strings"
26 "sync"
Chris Parsonsa798d962020-10-12 23:44:08 -040027
Chris Parsonsad876012022-08-20 14:48:32 -040028 "android/soong/android/allowlists"
Chris Parsons944e7d02021-03-11 11:08:46 -050029 "android/soong/bazel/cquery"
Jingwen Chen1e347862021-09-02 12:11:49 +000030 "android/soong/shared"
Liz Kammer337e9032022-08-03 15:49:43 -040031
Chris Parsons1a7aca02022-04-25 22:35:15 -040032 "github.com/google/blueprint"
Liz Kammer8206d4f2021-03-03 16:40:52 -050033
Patrice Arruda05ab2d02020-12-12 06:24:26 +000034 "android/soong/bazel"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040035)
36
Sasha Smundak1da064c2022-06-08 16:36:16 -070037var (
38 writeBazelFile = pctx.AndroidStaticRule("bazelWriteFileRule", blueprint.RuleParams{
39 Command: `sed "s/\\\\n/\n/g" ${out}.rsp >${out}`,
40 Rspfile: "${out}.rsp",
41 RspfileContent: "${content}",
42 }, "content")
Sasha Smundakc180dbd2022-07-03 14:55:58 -070043 _ = pctx.HostBinToolVariable("bazelBuildRunfilesTool", "build-runfiles")
44 buildRunfilesRule = pctx.AndroidStaticRule("bazelBuildRunfiles", blueprint.RuleParams{
45 Command: "${bazelBuildRunfilesTool} ${in} ${outDir}",
46 Depfile: "",
47 Description: "",
48 CommandDeps: []string{"${bazelBuildRunfilesTool}"},
49 }, "outDir")
Sasha Smundak1da064c2022-06-08 16:36:16 -070050)
51
Chris Parsonsf874e462022-05-10 13:50:12 -040052func init() {
53 RegisterMixedBuildsMutator(InitRegistrationContext)
54}
55
56func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammer337e9032022-08-03 15:49:43 -040057 ctx.FinalDepsMutators(func(ctx RegisterMutatorsContext) {
Chris Parsonsf874e462022-05-10 13:50:12 -040058 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
59 })
60}
61
62func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
63 if m := ctx.Module(); m.Enabled() {
64 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
65 if mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx) {
66 mixedBuildMod.QueueBazelCall(ctx)
67 }
68 }
69 }
70}
71
Liz Kammerf29df7c2021-04-02 13:37:39 -040072type cqueryRequest interface {
73 // Name returns a string name for this request type. Such request type names must be unique,
74 // and must only consist of alphanumeric characters.
75 Name() string
76
77 // StarlarkFunctionBody returns a starlark function body to process this request type.
78 // The returned string is the body of a Starlark function which obtains
79 // all request-relevant information about a target and returns a string containing
80 // this information.
81 // The function should have the following properties:
Cole Faust97d15272022-11-22 14:08:59 -080082 // - The arguments are `target` (a configured target) and `id_string` (the label + configuration).
Liz Kammerf29df7c2021-04-02 13:37:39 -040083 // - The return value must be a string.
84 // - The function body should not be indented outside of its own scope.
85 StarlarkFunctionBody() string
86}
87
Chris Parsons787fb362021-10-14 18:43:51 -040088// Portion of cquery map key to describe target configuration.
89type configKey struct {
Liz Kammer0940b892022-03-18 15:55:04 -040090 arch string
91 osType OsType
Chris Parsons787fb362021-10-14 18:43:51 -040092}
93
Sasha Smundakfe9a5b82022-07-27 14:51:45 -070094func (c configKey) String() string {
95 return fmt.Sprintf("%s::%s", c.arch, c.osType)
96}
97
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040098// Map key to describe bazel cquery requests.
99type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400100 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400101 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400102 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400103}
104
Chris Parsons86dc2c22022-09-28 14:58:41 -0400105func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
106 if strings.HasPrefix(label, "//") {
107 // Normalize Bazel labels to specify main repository explicitly.
108 label = "@" + label
109 }
110 return cqueryKey{label, cqueryRequest, cfgKey}
111}
112
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700113func (c cqueryKey) String() string {
114 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700115}
116
Chris Parsonsf874e462022-05-10 13:50:12 -0400117// BazelContext is a context object useful for interacting with Bazel during
118// the course of a build. Use of Bazel to evaluate part of the build graph
119// is referred to as a "mixed build". (Some modules are managed by Soong,
120// some are managed by Bazel). To facilitate interop between these build
121// subgraphs, Soong may make requests to Bazel and evaluate their responses
122// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400123type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400124 // Add a cquery request to the bazel request queue. All queued requests
125 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
126 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
127
128 // ** Cquery Results Retrieval Functions
129 // The below functions pertain to retrieving cquery results from a prior
130 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400131
132 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400133 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500134
Chris Parsons944e7d02021-03-11 11:08:46 -0500135 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400136 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400137
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000138 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400139 // TODO(b/232976601): Remove.
140 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000141
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700142 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400143 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700144
Sasha Smundakedd16662022-10-07 14:44:50 -0700145 // Returns the results of the GetCcUnstrippedInfo query
146 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
147
Chris Parsonsf874e462022-05-10 13:50:12 -0400148 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400149
150 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800151 // queued in the BazelContext. The ctx argument is optional and is only
152 // used for performance data collection
153 InvokeBazel(config Config, ctx *Context) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400154
Chris Parsonsad876012022-08-20 14:48:32 -0400155 // Returns true if Bazel handling is enabled for the module with the given name.
156 // Note that this only implies "bazel mixed build" allowlisting. The caller
157 // should independently verify the module is eligible for Bazel handling
158 // (for example, that it is MixedBuildBuildable).
159 BazelAllowlisted(moduleName string) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500160
161 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
162 OutputBase() string
163
164 // Returns build statements which should get registered to reflect Bazel's outputs.
165 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400166
167 // Returns the depsets defined in Bazel's aquery response.
168 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400169}
170
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400171type bazelRunner interface {
Jason Wu52cd1942022-09-08 15:37:57 +0000172 createBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) *exec.Cmd
173 issueBazelCommand(bazelCmd *exec.Cmd) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400174}
175
176type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000177 homeDir string
178 bazelPath string
179 outputBase string
180 workspaceDir string
181 soongOutDir string
182 metricsDir string
183 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400184}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400185
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400186// A context object which tracks queued requests that need to be made to Bazel,
187// and their results after the requests have been made.
188type bazelContext struct {
189 bazelRunner
190 paths *bazelPaths
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400191 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
192 requestMutex sync.Mutex // requests can be written in parallel
193
194 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500195
196 // Build statements which should get registered to reflect Bazel's outputs.
197 buildStatements []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400198
199 // Depsets which should be used for Bazel's build statements.
200 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400201
202 // Per-module allowlist/denylist functionality to control whether analysis of
203 // modules are handled by Bazel. For modules which do not have a Bazel definition
204 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
205 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
206 // Per-module denylist to opt modules out of bazel handling.
207 bazelDisabledModules map[string]bool
208 // Per-module allowlist to opt modules in to bazel handling.
209 bazelEnabledModules map[string]bool
210 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
211 modulesDefaultToBazel bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400212}
213
214var _ BazelContext = &bazelContext{}
215
216// A bazel context to use when Bazel is disabled.
217type noopBazelContext struct{}
218
219var _ BazelContext = noopBazelContext{}
220
221// A bazel context to use for tests.
222type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400223 OutputBaseDir string
224
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000225 LabelToOutputFiles map[string][]string
226 LabelToCcInfo map[string]cquery.CcInfo
227 LabelToPythonBinary map[string]string
Liz Kammerbe6a7122022-11-04 16:05:11 -0400228 LabelToApexInfo map[string]cquery.ApexInfo
Sasha Smundakedd16662022-10-07 14:44:50 -0700229 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400230}
231
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700232func (m MockBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400233 panic("unimplemented")
Chris Parsons8d6e4332021-02-22 16:13:50 -0500234}
235
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700236func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400237 result, _ := m.LabelToOutputFiles[label]
238 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400239}
240
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700241func (m MockBazelContext) GetCcInfo(label string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400242 result, _ := m.LabelToCcInfo[label]
243 return result, nil
244}
245
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700246func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400247 result, _ := m.LabelToPythonBinary[label]
248 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000249}
250
Liz Kammerbe6a7122022-11-04 16:05:11 -0400251func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Liz Kammer0e255ef2022-11-04 16:07:04 -0400252 result, _ := m.LabelToApexInfo[label]
253 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700254}
255
Sasha Smundakedd16662022-10-07 14:44:50 -0700256func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
257 result, _ := m.LabelToCcBinary[label]
258 return result, nil
259}
260
Sasha Smundak0e87b182022-12-01 11:46:11 -0800261func (m MockBazelContext) InvokeBazel(_ Config, _ *Context) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400262 panic("unimplemented")
263}
264
Sasha Smundak0e87b182022-12-01 11:46:11 -0800265func (m MockBazelContext) BazelAllowlisted(_ string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400266 return true
267}
268
Liz Kammera92e8442021-04-07 20:25:21 -0400269func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500270
271func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
272 return []bazel.BuildStatement{}
273}
274
Chris Parsons1a7aca02022-04-25 22:35:15 -0400275func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
276 return []bazel.AqueryDepset{}
277}
278
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400279var _ BazelContext = MockBazelContext{}
280
Chris Parsonsf874e462022-05-10 13:50:12 -0400281func (bazelCtx *bazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400282 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400283 bazelCtx.requestMutex.Lock()
284 defer bazelCtx.requestMutex.Unlock()
285 bazelCtx.requests[key] = true
286}
287
288func (bazelCtx *bazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400289 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400290 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500291 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400292
Chris Parsonsf874e462022-05-10 13:50:12 -0400293 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400294 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400295 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400296}
297
Chris Parsonsf874e462022-05-10 13:50:12 -0400298func (bazelCtx *bazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400299 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400300 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000301 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400302 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000303 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400304 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 +0000305}
306
Chris Parsonsf874e462022-05-10 13:50:12 -0400307func (bazelCtx *bazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400308 key := makeCqueryKey(label, cquery.GetPythonBinary, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400309 if rawString, ok := bazelCtx.results[key]; ok {
310 bazelOutput := strings.TrimSpace(rawString)
311 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
312 }
313 return "", fmt.Errorf("no bazel response found for %v", key)
314}
315
Liz Kammerbe6a7122022-11-04 16:05:11 -0400316func (bazelCtx *bazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400317 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700318 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500319 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700320 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400321 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700322}
323
Sasha Smundakedd16662022-10-07 14:44:50 -0700324func (bazelCtx *bazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
325 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
326 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500327 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700328 }
329 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
330}
331
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700332func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500333 panic("unimplemented")
334}
335
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700336func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500337 panic("unimplemented")
338}
339
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700340func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400341 panic("unimplemented")
342}
343
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700344func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000345 panic("unimplemented")
346}
347
Liz Kammerbe6a7122022-11-04 16:05:11 -0400348func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700349 panic("unimplemented")
350}
351
Sasha Smundakedd16662022-10-07 14:44:50 -0700352func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
353 //TODO implement me
354 panic("implement me")
355}
356
Sasha Smundak0e87b182022-12-01 11:46:11 -0800357func (n noopBazelContext) InvokeBazel(_ Config, _ *Context) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400358 panic("unimplemented")
359}
360
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500361func (m noopBazelContext) OutputBase() string {
362 return ""
363}
364
Sasha Smundak0e87b182022-12-01 11:46:11 -0800365func (n noopBazelContext) BazelAllowlisted(_ string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400366 return false
367}
368
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500369func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
370 return []bazel.BuildStatement{}
371}
372
Chris Parsons1a7aca02022-04-25 22:35:15 -0400373func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
374 return []bazel.AqueryDepset{}
375}
376
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400377func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400378 disabledModules := map[string]bool{}
379 enabledModules := map[string]bool{}
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800380 addToStringSet := func(set map[string]bool, items []string) {
381 for _, item := range items {
382 set[item] = true
383 }
384 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400385
386 switch c.BuildMode {
387 case BazelProdMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800388 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
MarkDacekd06db5d2022-11-29 00:47:59 +0000389 for enabledAdHocModule := range c.BazelModulesForceEnabledByFlag() {
390 enabledModules[enabledAdHocModule] = true
391 }
MarkDacekb78465d2022-10-18 20:10:16 +0000392 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400393 // Staging mode includes all prod modules plus all staging modules.
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800394 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
395 addToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
MarkDacekd06db5d2022-11-29 00:47:59 +0000396 for enabledAdHocModule := range c.BazelModulesForceEnabledByFlag() {
397 enabledModules[enabledAdHocModule] = true
398 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400399 case BazelDevMode:
Chris Parsonsef615e52022-08-18 22:04:11 -0400400 // Don't use partially-converted cc_library targets in mixed builds,
401 // since mixed builds would generally rely on both static and shared
402 // variants of a cc_library.
Sasha Smundak0e87b182022-12-01 11:46:11 -0800403 for staticOnlyModule := range GetBp2BuildAllowList().ccLibraryStaticOnly {
Chris Parsonsef615e52022-08-18 22:04:11 -0400404 disabledModules[staticOnlyModule] = true
405 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800406 addToStringSet(disabledModules, allowlists.MixedBuildsDisabledList)
Chris Parsonsef615e52022-08-18 22:04:11 -0400407 default:
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400408 return noopBazelContext{}, nil
409 }
410
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800411 paths := bazelPaths{
412 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400413 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800414 var missing []string
415 vars := []struct {
416 name string
417 ptr *string
418 }{
419 {"BAZEL_HOME", &paths.homeDir},
420 {"BAZEL_PATH", &paths.bazelPath},
421 {"BAZEL_OUTPUT_BASE", &paths.outputBase},
422 {"BAZEL_WORKSPACE", &paths.workspaceDir},
423 {"BAZEL_METRICS_DIR", &paths.metricsDir},
424 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile},
425 }
426 for _, v := range vars {
427 if s := c.Getenv(v.name); len(s) > 1 {
428 *v.ptr = s
429 } else {
430 missing = append(missing, v.name)
431 }
432 }
433 if len(missing) > 0 {
434 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
435 }
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400436 return &bazelContext{
Chris Parsonsad876012022-08-20 14:48:32 -0400437 bazelRunner: &builtinBazelRunner{},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800438 paths: &paths,
Chris Parsonsad876012022-08-20 14:48:32 -0400439 requests: make(map[cqueryKey]bool),
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800440 modulesDefaultToBazel: c.BuildMode == BazelDevMode,
Chris Parsonsef615e52022-08-18 22:04:11 -0400441 bazelEnabledModules: enabledModules,
Chris Parsonsad876012022-08-20 14:48:32 -0400442 bazelDisabledModules: disabledModules,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400443 }, nil
444}
445
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400446func (p *bazelPaths) BazelMetricsDir() string {
447 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000448}
449
Chris Parsonsad876012022-08-20 14:48:32 -0400450func (context *bazelContext) BazelAllowlisted(moduleName string) bool {
451 if context.bazelDisabledModules[moduleName] {
452 return false
453 }
454 if context.bazelEnabledModules[moduleName] {
455 return true
456 }
457 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400458}
459
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400460func pwdPrefix() string {
461 // Darwin doesn't have /proc
462 if runtime.GOOS != "darwin" {
463 return "PWD=/proc/self/cwd"
464 }
465 return ""
466}
467
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400468type bazelCommand struct {
469 command string
470 // query or label
471 expression string
472}
473
474type mockBazelRunner struct {
475 bazelCommandResults map[bazelCommand]string
Jason Wu52cd1942022-09-08 15:37:57 +0000476 // use *exec.Cmd as a key to get the bazelCommand, the map will be used in issueBazelCommand()
477 // Register createBazelCommand() invocations. Later, an
478 // issueBazelCommand() invocation can be mapped to the *exec.Cmd instance
479 // and then to the expected result via bazelCommandResults
480 tokens map[*exec.Cmd]bazelCommand
481 commands []bazelCommand
482 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400483}
484
Sasha Smundak0e87b182022-12-01 11:46:11 -0800485func (r *mockBazelRunner) createBazelCommand(_ *bazelPaths, _ bazel.RunName,
Jason Wu52cd1942022-09-08 15:37:57 +0000486 command bazelCommand, extraFlags ...string) *exec.Cmd {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400487 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700488 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Jason Wu52cd1942022-09-08 15:37:57 +0000489 cmd := &exec.Cmd{}
490 if r.tokens == nil {
491 r.tokens = make(map[*exec.Cmd]bazelCommand)
492 }
493 r.tokens[cmd] = command
494 return cmd
495}
496
497func (r *mockBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
498 if command, ok := r.tokens[bazelCmd]; ok {
499 return r.bazelCommandResults[command], "", nil
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400500 }
501 return "", "", nil
502}
503
504type builtinBazelRunner struct{}
505
Chris Parsons808d84c2021-03-09 20:43:32 -0500506// Issues the given bazel command with given build label and additional flags.
507// Returns (stdout, stderr, error). The first and second return values are strings
508// containing the stdout and stderr of the run command, and an error is returned if
509// the invocation returned an error code.
Jason Wu52cd1942022-09-08 15:37:57 +0000510func (r *builtinBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
511 stderr := &bytes.Buffer{}
512 bazelCmd.Stderr = stderr
513 if output, err := bazelCmd.Output(); err != nil {
514 return "", string(stderr.Bytes()),
Sasha Smundak0e87b182022-12-01 11:46:11 -0800515 fmt.Errorf("bazel command failed: %s\n---command---\n%s\n---env---\n%s\n---stderr---\n%s---",
516 err, bazelCmd, strings.Join(bazelCmd.Env, "\n"), stderr)
Jason Wu52cd1942022-09-08 15:37:57 +0000517 } else {
518 return string(output), string(stderr.Bytes()), nil
519 }
520}
521
522func (r *builtinBazelRunner) createBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
523 extraFlags ...string) *exec.Cmd {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000524 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000525 "--output_base=" + absolutePath(paths.outputBase),
526 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700527 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700528 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700529 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400530
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700531 // Set default platforms to canonicalized values for mixed builds requests.
532 // If these are set in the bazelrc, they will have values that are
533 // non-canonicalized to @sourceroot labels, and thus be invalid when
534 // referenced from the buildroot.
535 //
536 // The actual platform values here may be overridden by configuration
537 // transitions from the buildroot.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700538 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700539 // This should be parameterized on the host OS, but let's restrict to linux
540 // to keep things simple for now.
541 fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"),
542
543 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
544 "--experimental_repository_disable_download",
545
546 // Suppress noise
547 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500548 "--noshow_progress",
549 "--norun_validations",
550 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400551 cmdFlags = append(cmdFlags, extraFlags...)
552
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400553 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200554 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700555 extraEnv := []string{
556 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200557 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700558 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700559 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000560 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700561 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500562 // Disables local host detection of gcc; toolchain information is defined
563 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700564 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
565 }
566 bazelCmd.Env = append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400567
Jason Wu52cd1942022-09-08 15:37:57 +0000568 return bazelCmd
569}
570
571func printableCqueryCommand(bazelCmd *exec.Cmd) string {
572 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(bazelCmd.Args, "\" \"") + "\""
573 return outputString
574
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400575}
576
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400577func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500578 // TODO(cparsons): Define configuration transitions programmatically based
579 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400580 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500581#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400582# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500583#####################################################
584
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400585def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500586 return {
Chris Parsons787fb362021-10-14 18:43:51 -0400587 "//command_line_option:platforms": "@//build/bazel/platforms:%s_%s" % (attr.os, attr.arch),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500588 }
589
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400590_config_node_transition = transition(
591 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500592 inputs = [],
593 outputs = [
594 "//command_line_option:platforms",
595 ],
596)
597
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400598def _passthrough_rule_impl(ctx):
599 return [DefaultInfo(files = depset(ctx.files.deps))]
600
601config_node = rule(
602 implementation = _passthrough_rule_impl,
603 attrs = {
604 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400605 "os" : attr.string(mandatory = True),
606 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400607 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
608 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500609)
610
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400611
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500612# Rule representing the root of the build, to depend on all Bazel targets that
613# are required for the build. Building this target will build the entire Bazel
614# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400615mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400616 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500617 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400618 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500619 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400620)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500621
622def _phony_root_impl(ctx):
623 return []
624
625# Rule to depend on other targets but build nothing.
626# This is useful as follows: building a target of this rule will generate
627# symlink forests for all dependencies of the target, without executing any
628# actions of the build.
629phony_root = rule(
630 implementation = _phony_root_impl,
631 attrs = {"deps" : attr.label_list()},
632)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400633`
634 return []byte(contents)
635}
636
637func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500638 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
639 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400640 formatString := `
641# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400642load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
643
644%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400645
646mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400647 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000648 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400649)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500650
651phony_root(name = "phonyroot",
652 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000653 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500654)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400655`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400656 configNodeFormatString := `
657config_node(name = "%s",
658 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400659 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400660 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000661 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400662)
663`
664
665 configNodesSection := ""
666
Chris Parsons787fb362021-10-14 18:43:51 -0400667 labelsByConfig := map[string][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400668 for val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200669 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400670 configString := getConfigString(val)
671 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400672 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400673
Jingwen Chen1e347862021-09-02 12:11:49 +0000674 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400675 for configString, labels := range labelsByConfig {
676 configTokens := strings.Split(configString, "|")
677 if len(configTokens) != 2 {
678 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000679 }
Chris Parsons787fb362021-10-14 18:43:51 -0400680 archString := configTokens[0]
681 osString := configTokens[1]
682 targetString := fmt.Sprintf("%s_%s", osString, archString)
683 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
684 labelsString := strings.Join(labels, ",\n ")
685 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400686 }
687
Jingwen Chen1e347862021-09-02 12:11:49 +0000688 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400689}
690
Chris Parsons944e7d02021-03-11 11:08:46 -0500691func indent(original string) string {
692 result := ""
693 for _, line := range strings.Split(original, "\n") {
694 result += " " + line + "\n"
695 }
696 return result
697}
698
Chris Parsons808d84c2021-03-09 20:43:32 -0500699// Returns the file contents of the buildroot.cquery file that should be used for the cquery
700// expression in order to obtain information about buildroot and its dependencies.
701// The contents of this file depend on the bazelContext's requests; requests are enumerated
702// and grouped by their request type. The data retrieved for each label depends on its
703// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400704func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400705 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400706 for val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500707 cqueryId := getCqueryId(val)
708 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
709 requestTypeToCqueryIdEntries[val.requestType] =
710 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
711 }
712 labelRegistrationMapSection := ""
713 functionDefSection := ""
714 mainSwitchSection := ""
715
716 mapDeclarationFormatString := `
717%s = {
718 %s
719}
720`
721 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800722def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500723%s
724`
725 mainSwitchSectionFormatString := `
726 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800727 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500728`
729
Usta Shrestha0b52d832022-02-04 21:37:39 -0500730 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500731 labelMapName := requestType.Name() + "_Labels"
732 functionName := requestType.Name() + "_Fn"
733 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
734 labelMapName,
735 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
736 functionDefSection += fmt.Sprintf(functionDefFormatString,
737 functionName,
738 indent(requestType.StarlarkFunctionBody()))
739 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
740 labelMapName, functionName)
741 }
742
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400743 formatString := `
744# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400745
Usta Shrestha79fccef2022-09-02 18:37:40 -0400746# a drop-in replacement for json.encode(), not available in cquery environment
747# TODO(cparsons): bring json module in and remove this function
748def json_encode(input):
749 # Avoiding recursion by limiting
750 # - a dict to contain anything except a dict
751 # - a list to contain only primitives
752 def encode_primitive(p):
753 t = type(p)
754 if t == "string" or t == "int":
755 return repr(p)
756 fail("unsupported value '%%s' of type '%%s'" %% (p, type(p)))
757
758 def encode_list(list):
759 return "[%%s]" %% ", ".join([encode_primitive(item) for item in list])
760
761 def encode_list_or_primitive(v):
762 return encode_list(v) if type(v) == "list" else encode_primitive(v)
763
764 if type(input) == "dict":
765 # TODO(juu): the result is read line by line so can't use '\n' yet
766 kv_pairs = [("%%s: %%s" %% (encode_primitive(k), encode_list_or_primitive(v))) for (k, v) in input.items()]
767 return "{ %%s }" %% ", ".join(kv_pairs)
768 else:
769 return encode_list_or_primitive(input)
770
Chris Parsons944e7d02021-03-11 11:08:46 -0500771# Label Map Section
772%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500773
Chris Parsons944e7d02021-03-11 11:08:46 -0500774# Function Def Section
775%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500776
777def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400778 # TODO(b/199363072): filegroups and file targets aren't associated with any
779 # specific platform architecture in mixed builds. This is consistent with how
780 # Soong treats filegroups, but it may not be the case with manually-written
781 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500782 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000783 if buildoptions == None:
784 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400785 # any specific platform architecture in mixed builds, so use the host.
786 return "x86_64|linux"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500787 platforms = build_options(target)["//command_line_option:platforms"]
788 if len(platforms) != 1:
789 # An individual configured target should have only one platform architecture.
790 # Note that it's fine for there to be multiple architectures for the same label,
791 # but each is its own configured target.
792 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
793 platform_name = build_options(target)["//command_line_option:platforms"][0].name
794 if platform_name == "host":
795 return "HOST"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400796 elif platform_name.startswith("android_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400797 return platform_name[len("android_"):] + "|" + platform_name[:len("android_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400798 elif platform_name.startswith("linux_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400799 return platform_name[len("linux_"):] + "|" + platform_name[:len("linux_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400800 else:
801 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500802 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500803
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400804def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500805 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500806
Chris Parsons86dc2c22022-09-28 14:58:41 -0400807 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
808 if id_string.startswith("//"):
809 id_string = "@" + id_string
810
Chris Parsons944e7d02021-03-11 11:08:46 -0500811 # Main switch section
812 %s
813 # This target was not requested via cquery, and thus must be a dependency
814 # of a requested target.
815 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400816`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400817
Chris Parsons944e7d02021-03-11 11:08:46 -0500818 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
819 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400820}
821
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200822// Returns a path containing build-related metadata required for interfacing
823// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400824func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200825 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500826}
827
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200828// Returns the path where the contents of the @soong_injection repository live.
829// It is used by Soong to tell Bazel things it cannot over the command line.
830func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200831 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200832}
833
834// Returns the path of the synthetic Bazel workspace that contains a symlink
835// forest composed the whole source tree and BUILD files generated by bp2build.
836func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200837 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200838}
839
Jingwen Chen8c523582021-06-01 11:19:53 +0000840// Returns the path to the top level out dir ($OUT_DIR).
841func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200842 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000843}
844
Sasha Smundak4975c822022-11-16 15:28:18 -0800845const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
846
847var (
848 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
849 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
850 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
851)
852
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400853// Issues commands to Bazel to receive results for all cquery requests
854// queued in the BazelContext.
Sasha Smundak4975c822022-11-16 15:28:18 -0800855func (context *bazelContext) InvokeBazel(config Config, ctx *Context) error {
856 if ctx != nil {
857 ctx.EventHandler.Begin("bazel")
858 defer ctx.EventHandler.End("bazel")
859 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400860
Sasha Smundak4975c822022-11-16 15:28:18 -0800861 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
862 if err := os.MkdirAll(metricsDir, 0777); err != nil {
863 return err
864 }
865 }
866 context.results = make(map[cqueryKey]string)
867 if err := context.runCquery(ctx); err != nil {
868 return err
869 }
870 if err := context.runAquery(config, ctx); err != nil {
871 return err
872 }
873 if err := context.generateBazelSymlinks(ctx); err != nil {
874 return err
875 }
876
877 // Clear requests.
878 context.requests = map[cqueryKey]bool{}
879 return nil
880}
881
882func (context *bazelContext) runCquery(ctx *Context) error {
883 if ctx != nil {
884 ctx.EventHandler.Begin("cquery")
885 defer ctx.EventHandler.End("cquery")
886 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200887 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200888 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
889 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
890 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -0500891 if err != nil {
892 return err
893 }
894 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800895 if err := os.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200896 return err
897 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800898 if err := os.WriteFile(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400899 return err
900 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800901 if err := os.WriteFile(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400902 return err
903 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200904 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Sasha Smundak0e87b182022-12-01 11:46:11 -0800905 if err := os.WriteFile(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400906 return err
907 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000908
Jason Wu52cd1942022-09-08 15:37:57 +0000909 cqueryCommandWithFlag := context.createBazelCommand(context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700910 "--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
Wei Licbd181c2022-11-16 08:59:23 -0800911 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCommandWithFlag)
912 if cqueryErr != nil {
913 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -0500914 }
Jason Wu52cd1942022-09-08 15:37:57 +0000915 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", printableCqueryCommand(cqueryCommandWithFlag))
Sasha Smundak0e87b182022-12-01 11:46:11 -0800916 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400917 return err
918 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400919 cqueryResults := map[string]string{}
920 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
921 if strings.Contains(outputLine, ">>") {
922 splitLine := strings.SplitN(outputLine, ">>", 2)
923 cqueryResults[splitLine[0]] = splitLine[1]
924 }
925 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500926 for val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500927 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -0500928 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400929 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500930 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -0800931 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400932 }
933 }
Sasha Smundak4975c822022-11-16 15:28:18 -0800934 return nil
935}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400936
Sasha Smundak4975c822022-11-16 15:28:18 -0800937func (context *bazelContext) runAquery(config Config, ctx *Context) error {
938 if ctx != nil {
939 ctx.EventHandler.Begin("aquery")
940 defer ctx.EventHandler.End("aquery")
941 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500942 // Issue an aquery command to retrieve action information about the bazel build tree.
943 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700944 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
945 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +0000946 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -0700947 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700948 extraFlags = append(extraFlags, "--collect_code_coverage")
949 paths := make([]string, 0, 2)
950 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -0800951 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -0800952 // TODO(b/259404593) convert path wildcard to regex values
953 if p[i] == "*" {
954 p[i] = ".*"
955 }
956 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700957 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
958 }
959 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
960 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
961 }
962 if len(paths) > 0 {
963 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -0700964 }
965 }
Sasha Smundak4975c822022-11-16 15:28:18 -0800966 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
967 extraFlags...))
968 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -0500969 return err
970 }
Sasha Smundak4975c822022-11-16 15:28:18 -0800971 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
972 return err
973}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500974
Sasha Smundak4975c822022-11-16 15:28:18 -0800975func (context *bazelContext) generateBazelSymlinks(ctx *Context) error {
976 if ctx != nil {
977 ctx.EventHandler.Begin("symlinks")
978 defer ctx.EventHandler.End("symlinks")
979 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500980 // Issue a build command of the phony root to generate symlink forests for dependencies of the
981 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
982 // but some of symlinks may be required to resolve source dependencies of the build.
Sasha Smundak4975c822022-11-16 15:28:18 -0800983 _, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd))
984 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400985}
Chris Parsonsa798d962020-10-12 23:44:08 -0400986
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500987func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
988 return context.buildStatements
989}
990
Chris Parsons1a7aca02022-04-25 22:35:15 -0400991func (context *bazelContext) AqueryDepsets() []bazel.AqueryDepset {
992 return context.depsets
993}
994
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500995func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400996 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500997}
998
Chris Parsonsa798d962020-10-12 23:44:08 -0400999// Singleton used for registering BUILD file ninja dependencies (needed
1000// for correctness of builds which use Bazel.
1001func BazelSingleton() Singleton {
1002 return &bazelSingleton{}
1003}
1004
1005type bazelSingleton struct{}
1006
1007func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001008 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001009 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001010 return
1011 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001012
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001013 // Add ninja file dependencies for files which all bazel invocations require.
1014 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001015 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001016 ctx.AddNinjaFileDeps(bazelBuildList)
1017
Sasha Smundak0e87b182022-12-01 11:46:11 -08001018 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001019 if err != nil {
1020 ctx.Errorf(err.Error())
1021 }
1022 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1023 for _, file := range files {
1024 ctx.AddNinjaFileDeps(file)
1025 }
1026
Chris Parsons1a7aca02022-04-25 22:35:15 -04001027 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1028 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001029 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001030 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1031 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001032 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1033 }
1034 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001035 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1036 if artifactPath == "bazel-out/volatile-status.txt" {
1037 // See https://bazel.build/docs/user-manual#workspace-status
1038 orderOnlies = append(orderOnlies, pathInBazelOut)
1039 } else {
1040 outputs = append(outputs, pathInBazelOut)
1041 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001042 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001043 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001044 ctx.Build(pctx, BuildParams{
1045 Rule: blueprint.Phony,
1046 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1047 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001048 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001049 })
1050 }
1051
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001052 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1053 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001054 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -07001055 if len(buildStatement.Command) > 0 {
1056 rule := NewRuleBuilder(pctx, ctx)
1057 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1058 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1059 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1060 continue
1061 }
1062 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1063 // and thus require special treatment. If BuildStatement were an interface implementing
1064 // buildRule(ctx) function, the code here would just call it.
1065 // Unfortunately, the BuildStatement is defined in
1066 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1067 // because this would cause circular dependency. So, until we move aquery processing
1068 // to the 'android' package, we need to handle special cases here.
1069 if buildStatement.Mnemonic == "FileWrite" || buildStatement.Mnemonic == "SourceSymlinkManifest" {
1070 // Pass file contents as the value of the rule's "content" argument.
1071 // Escape newlines and $ in the contents (the action "writeBazelFile" restores "\\n"
1072 // back to the newline, and Ninja reads $$ as $.
1073 escaped := strings.ReplaceAll(strings.ReplaceAll(buildStatement.FileContents, "\n", "\\n"),
1074 "$", "$$")
1075 ctx.Build(pctx, BuildParams{
1076 Rule: writeBazelFile,
1077 Output: PathForBazelOut(ctx, buildStatement.OutputPaths[0]),
1078 Description: fmt.Sprintf("%s %s", buildStatement.Mnemonic, buildStatement.OutputPaths[0]),
1079 Args: map[string]string{
1080 "content": escaped,
1081 },
1082 })
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001083 } else if buildStatement.Mnemonic == "SymlinkTree" {
1084 // build-runfiles arguments are the manifest file and the target directory
1085 // where it creates the symlink tree according to this manifest (and then
1086 // writes the MANIFEST file to it).
1087 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1088 outManifestPath := outManifest.String()
1089 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1090 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1091 }
1092 outDir := filepath.Dir(outManifestPath)
1093 ctx.Build(pctx, BuildParams{
1094 Rule: buildRunfilesRule,
1095 Output: outManifest,
1096 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1097 Description: "symlink tree for " + outDir,
1098 Args: map[string]string{
1099 "outDir": outDir,
1100 },
1101 })
Sasha Smundak1da064c2022-06-08 16:36:16 -07001102 } else {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001103 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001104 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001105 }
1106}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001107
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001108// Register bazel-owned build statements (obtained from the aquery invocation).
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001109func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001110 // executionRoot is the action cwd.
1111 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1112
1113 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1114 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001115 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001116 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001117 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001118 }
1119 cmd.Text("&&")
1120 }
1121
1122 for _, pair := range buildStatement.Env {
1123 // Set per-action env variables, if any.
1124 cmd.Flag(pair.Key + "=" + pair.Value)
1125 }
1126
1127 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001128 if len(buildStatement.Command) > 16*1024 {
1129 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1130 WriteFileRule(ctx, commandFile, buildStatement.Command)
1131
1132 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1133 } else {
1134 cmd.Text(buildStatement.Command)
1135 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001136
1137 for _, outputPath := range buildStatement.OutputPaths {
1138 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1139 }
1140 for _, inputPath := range buildStatement.InputPaths {
1141 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1142 }
1143 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1144 otherDepsetName := bazelDepsetName(inputDepsetHash)
1145 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1146 }
1147
1148 if depfile := buildStatement.Depfile; depfile != nil {
1149 // The paths in depfile are relative to `executionRoot`.
1150 // Hence, they need to be corrected by replacing "bazel-out"
1151 // with the full `bazelOutDir`.
1152 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1153 // would be deemed missing.
1154 // (Note: The regexp uses a capture group because the version of sed
1155 // does not support a look-behind pattern.)
1156 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1157 bazelOutDir, *depfile)
1158 cmd.Text(replacement)
1159 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1160 }
1161
1162 for _, symlinkPath := range buildStatement.SymlinkPaths {
1163 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1164 }
1165}
1166
Chris Parsons8d6e4332021-02-22 16:13:50 -05001167func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001168 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001169}
1170
Chris Parsons787fb362021-10-14 18:43:51 -04001171func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001172 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001173 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001174 if key.configKey.osType.Class == Device {
1175 // For the generic Android, the expected result is "target|android", which
1176 // corresponds to the product_variable_config named "android_target" in
1177 // build/bazel/platforms/BUILD.bazel.
1178 arch = "target"
1179 } else {
1180 // Use host platform, which is currently hardcoded to be x86_64.
1181 arch = "x86_64"
1182 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001183 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001184 osName := key.configKey.osType.Name
1185 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" {
Chris Parsons787fb362021-10-14 18:43:51 -04001186 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001187 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001188 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001189 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -04001190}
1191
Chris Parsonsf874e462022-05-10 13:50:12 -04001192func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001193 return configKey{
1194 // use string because Arch is not a valid key in go
1195 arch: ctx.Arch().String(),
1196 osType: ctx.Os(),
1197 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001198}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001199
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001200func bazelDepsetName(contentHash string) string {
1201 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001202}