blob: 5804a46edab5f1720a57ac6557ee0f0f329d2e43 [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 Parsons944e7d02021-03-11 11:08:46 -050030 "android/soong/bazel/cquery"
Jingwen Chen1e347862021-09-02 12:11:49 +000031 "android/soong/shared"
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) {
57 ctx.PostDepsMutators(func(ctx RegisterMutatorsContext) {
58 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:
82 // - `target` is the only parameter to this function (a configured target).
83 // - 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
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700105func (c cqueryKey) String() string {
106 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
107
108}
109
Chris Parsonsf874e462022-05-10 13:50:12 -0400110// BazelContext is a context object useful for interacting with Bazel during
111// the course of a build. Use of Bazel to evaluate part of the build graph
112// is referred to as a "mixed build". (Some modules are managed by Soong,
113// some are managed by Bazel). To facilitate interop between these build
114// subgraphs, Soong may make requests to Bazel and evaluate their responses
115// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400116type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400117 // Add a cquery request to the bazel request queue. All queued requests
118 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
119 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
120
121 // ** Cquery Results Retrieval Functions
122 // The below functions pertain to retrieving cquery results from a prior
123 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400124
125 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400126 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500127
Chris Parsons944e7d02021-03-11 11:08:46 -0500128 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400129 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400130
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000131 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400132 // TODO(b/232976601): Remove.
133 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000134
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700135 // Returns the results of the GetApexInfo query (including output files)
136 GetApexInfo(label string, cfgkey configKey) (cquery.ApexCqueryInfo, error)
137
Chris Parsonsf874e462022-05-10 13:50:12 -0400138 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400139
140 // Issues commands to Bazel to receive results for all cquery requests
141 // queued in the BazelContext.
Yu Liu8d82ac52022-05-17 15:13:28 -0700142 InvokeBazel(config Config) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400143
144 // Returns true if bazel is enabled for the given configuration.
145 BazelEnabled() bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500146
147 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
148 OutputBase() string
149
150 // Returns build statements which should get registered to reflect Bazel's outputs.
151 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400152
153 // Returns the depsets defined in Bazel's aquery response.
154 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400155}
156
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400157type bazelRunner interface {
158 issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) (string, string, error)
159}
160
161type bazelPaths struct {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400162 homeDir string
163 bazelPath string
164 outputBase string
165 workspaceDir string
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200166 soongOutDir string
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000167 metricsDir string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400168}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400169
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400170// A context object which tracks queued requests that need to be made to Bazel,
171// and their results after the requests have been made.
172type bazelContext struct {
173 bazelRunner
174 paths *bazelPaths
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400175 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
176 requestMutex sync.Mutex // requests can be written in parallel
177
178 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500179
180 // Build statements which should get registered to reflect Bazel's outputs.
181 buildStatements []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400182
183 // Depsets which should be used for Bazel's build statements.
184 depsets []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400185}
186
187var _ BazelContext = &bazelContext{}
188
189// A bazel context to use when Bazel is disabled.
190type noopBazelContext struct{}
191
192var _ BazelContext = noopBazelContext{}
193
194// A bazel context to use for tests.
195type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400196 OutputBaseDir string
197
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000198 LabelToOutputFiles map[string][]string
199 LabelToCcInfo map[string]cquery.CcInfo
200 LabelToPythonBinary map[string]string
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700201 LabelToApexInfo map[string]cquery.ApexCqueryInfo
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400202}
203
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700204func (m MockBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400205 panic("unimplemented")
Chris Parsons8d6e4332021-02-22 16:13:50 -0500206}
207
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700208func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400209 result, _ := m.LabelToOutputFiles[label]
210 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400211}
212
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700213func (m MockBazelContext) GetCcInfo(label string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400214 result, _ := m.LabelToCcInfo[label]
215 return result, nil
216}
217
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700218func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400219 result, _ := m.LabelToPythonBinary[label]
220 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000221}
222
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700223func (n MockBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexCqueryInfo, error) {
224 panic("unimplemented")
225}
226
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700227func (m MockBazelContext) InvokeBazel(_ Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400228 panic("unimplemented")
229}
230
231func (m MockBazelContext) BazelEnabled() bool {
232 return true
233}
234
Liz Kammera92e8442021-04-07 20:25:21 -0400235func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500236
237func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
238 return []bazel.BuildStatement{}
239}
240
Chris Parsons1a7aca02022-04-25 22:35:15 -0400241func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
242 return []bazel.AqueryDepset{}
243}
244
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400245var _ BazelContext = MockBazelContext{}
246
Chris Parsonsf874e462022-05-10 13:50:12 -0400247func (bazelCtx *bazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
248 key := cqueryKey{label, requestType, cfgKey}
249 bazelCtx.requestMutex.Lock()
250 defer bazelCtx.requestMutex.Unlock()
251 bazelCtx.requests[key] = true
252}
253
254func (bazelCtx *bazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
255 key := cqueryKey{label, cquery.GetOutputFiles, cfgKey}
256 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500257 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400258 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400259 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400260 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400261}
262
Chris Parsonsf874e462022-05-10 13:50:12 -0400263func (bazelCtx *bazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
264 key := cqueryKey{label, cquery.GetCcInfo, cfgKey}
265 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000266 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400267 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000268 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400269 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 +0000270}
271
Chris Parsonsf874e462022-05-10 13:50:12 -0400272func (bazelCtx *bazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
273 key := cqueryKey{label, cquery.GetPythonBinary, cfgKey}
274 if rawString, ok := bazelCtx.results[key]; ok {
275 bazelOutput := strings.TrimSpace(rawString)
276 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
277 }
278 return "", fmt.Errorf("no bazel response found for %v", key)
279}
280
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700281func (bazelCtx *bazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexCqueryInfo, error) {
282 key := cqueryKey{label, cquery.GetApexInfo, cfgKey}
283 if rawString, ok := bazelCtx.results[key]; ok {
284 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString)), nil
285 }
286 return cquery.ApexCqueryInfo{}, fmt.Errorf("no bazel response found for %v", key)
287}
288
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700289func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500290 panic("unimplemented")
291}
292
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700293func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500294 panic("unimplemented")
295}
296
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700297func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400298 panic("unimplemented")
299}
300
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700301func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000302 panic("unimplemented")
303}
304
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700305func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexCqueryInfo, error) {
306 panic("unimplemented")
307}
308
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700309func (n noopBazelContext) InvokeBazel(_ Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400310 panic("unimplemented")
311}
312
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500313func (m noopBazelContext) OutputBase() string {
314 return ""
315}
316
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400317func (n noopBazelContext) BazelEnabled() bool {
318 return false
319}
320
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500321func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
322 return []bazel.BuildStatement{}
323}
324
Chris Parsons1a7aca02022-04-25 22:35:15 -0400325func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
326 return []bazel.AqueryDepset{}
327}
328
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400329func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons8b77a002020-10-27 18:59:25 -0400330 // TODO(cparsons): Assess USE_BAZEL=1 instead once "mixed Soong/Bazel builds"
331 // are production ready.
Jingwen Chen442b1a42021-06-17 07:02:15 +0000332 if !c.IsEnvTrue("USE_BAZEL_ANALYSIS") {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400333 return noopBazelContext{}, nil
334 }
335
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400336 p, err := bazelPathsFromConfig(c)
337 if err != nil {
338 return nil, err
339 }
340 return &bazelContext{
341 bazelRunner: &builtinBazelRunner{},
342 paths: p,
343 requests: make(map[cqueryKey]bool),
344 }, nil
345}
346
347func bazelPathsFromConfig(c *config) (*bazelPaths, error) {
348 p := bazelPaths{
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200349 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400350 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700351 var missingEnvVars []string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400352 if len(c.Getenv("BAZEL_HOME")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400353 p.homeDir = c.Getenv("BAZEL_HOME")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400354 } else {
355 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
356 }
357 if len(c.Getenv("BAZEL_PATH")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400358 p.bazelPath = c.Getenv("BAZEL_PATH")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400359 } else {
360 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
361 }
362 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400363 p.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400364 } else {
365 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
366 }
367 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400368 p.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400369 } else {
370 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
371 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000372 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400373 p.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000374 } else {
375 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
376 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400377 if len(missingEnvVars) > 0 {
378 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
379 } else {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400380 return &p, nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400381 }
382}
383
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400384func (p *bazelPaths) BazelMetricsDir() string {
385 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000386}
387
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400388func (context *bazelContext) BazelEnabled() bool {
389 return true
390}
391
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400392func pwdPrefix() string {
393 // Darwin doesn't have /proc
394 if runtime.GOOS != "darwin" {
395 return "PWD=/proc/self/cwd"
396 }
397 return ""
398}
399
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400400type bazelCommand struct {
401 command string
402 // query or label
403 expression string
404}
405
406type mockBazelRunner struct {
407 bazelCommandResults map[bazelCommand]string
408 commands []bazelCommand
Yu Liu8d82ac52022-05-17 15:13:28 -0700409 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400410}
411
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700412func (r *mockBazelRunner) issueBazelCommand(_ *bazelPaths, _ bazel.RunName,
413 command bazelCommand, extraFlags ...string) (string, string, error) {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400414 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700415 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400416 if ret, ok := r.bazelCommandResults[command]; ok {
417 return ret, "", nil
418 }
419 return "", "", nil
420}
421
422type builtinBazelRunner struct{}
423
Chris Parsons808d84c2021-03-09 20:43:32 -0500424// Issues the given bazel command with given build label and additional flags.
425// Returns (stdout, stderr, error). The first and second return values are strings
426// containing the stdout and stderr of the run command, and an error is returned if
427// the invocation returned an error code.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400428func (r *builtinBazelRunner) issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Chris Parsons808d84c2021-03-09 20:43:32 -0500429 extraFlags ...string) (string, string, error) {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000430 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000431 "--output_base=" + absolutePath(paths.outputBase),
432 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700433 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700434 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700435 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400436
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700437 // Set default platforms to canonicalized values for mixed builds requests.
438 // If these are set in the bazelrc, they will have values that are
439 // non-canonicalized to @sourceroot labels, and thus be invalid when
440 // referenced from the buildroot.
441 //
442 // The actual platform values here may be overridden by configuration
443 // transitions from the buildroot.
444 fmt.Sprintf("--platforms=%s", "//build/bazel/platforms:android_target"),
445 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Jingwen Chen91220d72021-03-24 02:18:33 -0400446
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700447 // This should be parameterized on the host OS, but let's restrict to linux
448 // to keep things simple for now.
449 fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"),
450
451 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
452 "--experimental_repository_disable_download",
453
454 // Suppress noise
455 "--ui_event_filters=-INFO",
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700456 "--noshow_progress"}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400457 cmdFlags = append(cmdFlags, extraFlags...)
458
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400459 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200460 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700461 extraEnv := []string{
462 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200463 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700464 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Jingwen Chen8c523582021-06-01 11:19:53 +0000465 // Make OUT_DIR absolute here so tools/bazel.sh uses the correct
466 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700467 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500468 // Disables local host detection of gcc; toolchain information is defined
469 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700470 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
471 }
472 bazelCmd.Env = append(os.Environ(), extraEnv...)
Colin Crossff0278b2020-10-09 19:24:15 -0700473 stderr := &bytes.Buffer{}
474 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400475
476 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500477 return "", string(stderr.Bytes()),
478 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400479 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500480 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400481 }
482}
483
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400484func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500485 // TODO(cparsons): Define configuration transitions programmatically based
486 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400487 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500488#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400489# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500490#####################################################
491
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400492def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500493 return {
Chris Parsons787fb362021-10-14 18:43:51 -0400494 "//command_line_option:platforms": "@//build/bazel/platforms:%s_%s" % (attr.os, attr.arch),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500495 }
496
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400497_config_node_transition = transition(
498 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500499 inputs = [],
500 outputs = [
501 "//command_line_option:platforms",
502 ],
503)
504
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400505def _passthrough_rule_impl(ctx):
506 return [DefaultInfo(files = depset(ctx.files.deps))]
507
508config_node = rule(
509 implementation = _passthrough_rule_impl,
510 attrs = {
511 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400512 "os" : attr.string(mandatory = True),
513 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400514 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
515 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500516)
517
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400518
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500519# Rule representing the root of the build, to depend on all Bazel targets that
520# are required for the build. Building this target will build the entire Bazel
521# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400522mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400523 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500524 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400525 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500526 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400527)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500528
529def _phony_root_impl(ctx):
530 return []
531
532# Rule to depend on other targets but build nothing.
533# This is useful as follows: building a target of this rule will generate
534# symlink forests for all dependencies of the target, without executing any
535# actions of the build.
536phony_root = rule(
537 implementation = _phony_root_impl,
538 attrs = {"deps" : attr.label_list()},
539)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400540`
541 return []byte(contents)
542}
543
544func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500545 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
546 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400547 formatString := `
548# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400549load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
550
551%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400552
553mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400554 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400555)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500556
557phony_root(name = "phonyroot",
558 deps = [":buildroot"],
559)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400560`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400561 configNodeFormatString := `
562config_node(name = "%s",
563 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400564 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400565 deps = [%s],
566)
567`
568
569 configNodesSection := ""
570
Chris Parsons787fb362021-10-14 18:43:51 -0400571 labelsByConfig := map[string][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400572 for val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200573 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400574 configString := getConfigString(val)
575 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400576 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400577
Jingwen Chen1e347862021-09-02 12:11:49 +0000578 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400579 for configString, labels := range labelsByConfig {
580 configTokens := strings.Split(configString, "|")
581 if len(configTokens) != 2 {
582 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000583 }
Chris Parsons787fb362021-10-14 18:43:51 -0400584 archString := configTokens[0]
585 osString := configTokens[1]
586 targetString := fmt.Sprintf("%s_%s", osString, archString)
587 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
588 labelsString := strings.Join(labels, ",\n ")
589 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400590 }
591
Jingwen Chen1e347862021-09-02 12:11:49 +0000592 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400593}
594
Chris Parsons944e7d02021-03-11 11:08:46 -0500595func indent(original string) string {
596 result := ""
597 for _, line := range strings.Split(original, "\n") {
598 result += " " + line + "\n"
599 }
600 return result
601}
602
Chris Parsons808d84c2021-03-09 20:43:32 -0500603// Returns the file contents of the buildroot.cquery file that should be used for the cquery
604// expression in order to obtain information about buildroot and its dependencies.
605// The contents of this file depend on the bazelContext's requests; requests are enumerated
606// and grouped by their request type. The data retrieved for each label depends on its
607// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400608func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400609 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400610 for val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500611 cqueryId := getCqueryId(val)
612 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
613 requestTypeToCqueryIdEntries[val.requestType] =
614 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
615 }
616 labelRegistrationMapSection := ""
617 functionDefSection := ""
618 mainSwitchSection := ""
619
620 mapDeclarationFormatString := `
621%s = {
622 %s
623}
624`
625 functionDefFormatString := `
626def %s(target):
627%s
628`
629 mainSwitchSectionFormatString := `
630 if id_string in %s:
631 return id_string + ">>" + %s(target)
632`
633
Usta Shrestha0b52d832022-02-04 21:37:39 -0500634 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500635 labelMapName := requestType.Name() + "_Labels"
636 functionName := requestType.Name() + "_Fn"
637 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
638 labelMapName,
639 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
640 functionDefSection += fmt.Sprintf(functionDefFormatString,
641 functionName,
642 indent(requestType.StarlarkFunctionBody()))
643 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
644 labelMapName, functionName)
645 }
646
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400647 formatString := `
648# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400649
Chris Parsons944e7d02021-03-11 11:08:46 -0500650# Label Map Section
651%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500652
Chris Parsons944e7d02021-03-11 11:08:46 -0500653# Function Def Section
654%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500655
656def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400657 # TODO(b/199363072): filegroups and file targets aren't associated with any
658 # specific platform architecture in mixed builds. This is consistent with how
659 # Soong treats filegroups, but it may not be the case with manually-written
660 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500661 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000662 if buildoptions == None:
663 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400664 # any specific platform architecture in mixed builds, so use the host.
665 return "x86_64|linux"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500666 platforms = build_options(target)["//command_line_option:platforms"]
667 if len(platforms) != 1:
668 # An individual configured target should have only one platform architecture.
669 # Note that it's fine for there to be multiple architectures for the same label,
670 # but each is its own configured target.
671 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
672 platform_name = build_options(target)["//command_line_option:platforms"][0].name
673 if platform_name == "host":
674 return "HOST"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400675 elif platform_name.startswith("android_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400676 return platform_name[len("android_"):] + "|" + platform_name[:len("android_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400677 elif platform_name.startswith("linux_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400678 return platform_name[len("linux_"):] + "|" + platform_name[:len("linux_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400679 else:
680 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500681 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500682
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700683def json_for_file(key, file):
684 return '"' + key + '":"' + file.path + '"'
685
686def json_for_files(key, files):
687 return '"' + key + '":[' + ",".join(['"' + f.path + '"' for f in files]) + ']'
688
689def json_for_labels(key, ll):
690 return '"' + key + '":[' + ",".join(['"' + str(x) + '"' for x in ll]) + ']'
691
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400692def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500693 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500694
695 # Main switch section
696 %s
697 # This target was not requested via cquery, and thus must be a dependency
698 # of a requested target.
699 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400700`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400701
Chris Parsons944e7d02021-03-11 11:08:46 -0500702 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
703 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400704}
705
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200706// Returns a path containing build-related metadata required for interfacing
707// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400708func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200709 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500710}
711
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200712// Returns the path where the contents of the @soong_injection repository live.
713// It is used by Soong to tell Bazel things it cannot over the command line.
714func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200715 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200716}
717
718// Returns the path of the synthetic Bazel workspace that contains a symlink
719// forest composed the whole source tree and BUILD files generated by bp2build.
720func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200721 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200722}
723
Jingwen Chen8c523582021-06-01 11:19:53 +0000724// Returns the path to the top level out dir ($OUT_DIR).
725func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200726 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000727}
728
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400729// Issues commands to Bazel to receive results for all cquery requests
730// queued in the BazelContext.
Yu Liu8d82ac52022-05-17 15:13:28 -0700731func (context *bazelContext) InvokeBazel(config Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400732 context.results = make(map[cqueryKey]string)
733
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400734 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500735
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200736 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200737 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
738 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
739 err = os.MkdirAll(mixedBuildsPath, 0777)
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500740 }
Chris Parsons8ccdb632020-11-17 15:41:01 -0500741 if err != nil {
742 return err
743 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500744 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
745 err = os.MkdirAll(metricsDir, 0777)
746 if err != nil {
747 return err
748 }
749 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700750 if err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200751 return err
752 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700753 if err = ioutil.WriteFile(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400754 return err
755 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700756 if err = ioutil.WriteFile(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400757 return err
758 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200759 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700760 if err = ioutil.WriteFile(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400761 return err
762 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000763
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700764 const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
765 cqueryCmd := bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
766 cqueryOutput, cqueryErr, err := context.issueBazelCommand(context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
767 "--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500768 if err != nil {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700769 _ = ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryOutput), 0666)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500770 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400771 if err != nil {
772 return err
773 }
774
775 cqueryResults := map[string]string{}
776 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
777 if strings.Contains(outputLine, ">>") {
778 splitLine := strings.SplitN(outputLine, ">>", 2)
779 cqueryResults[splitLine[0]] = splitLine[1]
780 }
781 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500782 for val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500783 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -0500784 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400785 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500786 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
787 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400788 }
789 }
790
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500791 // Issue an aquery command to retrieve action information about the bazel build tree.
792 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700793 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
794 // proto sources, which would add a number of unnecessary dependencies.
795 extraFlags := []string{"--output=jsonproto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -0700796 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700797 extraFlags = append(extraFlags, "--collect_code_coverage")
798 paths := make([]string, 0, 2)
799 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
800 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
801 }
802 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
803 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
804 }
805 if len(paths) > 0 {
806 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -0700807 }
808 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700809 aqueryCmd := bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
810 if aqueryOutput, _, err := context.issueBazelCommand(context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
811 extraFlags...); err == nil {
812 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400813 }
Chris Parsons4f069892021-01-15 12:22:41 -0500814 if err != nil {
815 return err
816 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500817
818 // Issue a build command of the phony root to generate symlink forests for dependencies of the
819 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
820 // but some of symlinks may be required to resolve source dependencies of the build.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700821 buildCmd := bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
822 if _, _, err = context.issueBazelCommand(context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd); err != nil {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500823 return err
824 }
825
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400826 // Clear requests.
827 context.requests = map[cqueryKey]bool{}
828 return nil
829}
Chris Parsonsa798d962020-10-12 23:44:08 -0400830
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500831func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
832 return context.buildStatements
833}
834
Chris Parsons1a7aca02022-04-25 22:35:15 -0400835func (context *bazelContext) AqueryDepsets() []bazel.AqueryDepset {
836 return context.depsets
837}
838
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500839func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400840 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500841}
842
Chris Parsonsa798d962020-10-12 23:44:08 -0400843// Singleton used for registering BUILD file ninja dependencies (needed
844// for correctness of builds which use Bazel.
845func BazelSingleton() Singleton {
846 return &bazelSingleton{}
847}
848
849type bazelSingleton struct{}
850
851func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500852 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
853 if !ctx.Config().BazelContext.BazelEnabled() {
854 return
855 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400856
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500857 // Add ninja file dependencies for files which all bazel invocations require.
858 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200859 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500860 ctx.AddNinjaFileDeps(bazelBuildList)
861
862 data, err := ioutil.ReadFile(bazelBuildList)
863 if err != nil {
864 ctx.Errorf(err.Error())
865 }
866 files := strings.Split(strings.TrimSpace(string(data)), "\n")
867 for _, file := range files {
868 ctx.AddNinjaFileDeps(file)
869 }
870
Chris Parsons1a7aca02022-04-25 22:35:15 -0400871 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
872 var outputs []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400873 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
874 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400875 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
876 }
877 for _, artifactPath := range depset.DirectArtifacts {
878 outputs = append(outputs, PathForBazelOut(ctx, artifactPath))
879 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400880 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400881 ctx.Build(pctx, BuildParams{
882 Rule: blueprint.Phony,
883 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
884 Implicits: outputs,
885 })
886 }
887
Usta Shresthaacd5a0c2022-06-22 11:20:50 -0400888 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
889 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500890 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -0700891 if len(buildStatement.Command) > 0 {
892 rule := NewRuleBuilder(pctx, ctx)
893 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
894 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
895 rule.Build(fmt.Sprintf("bazel %d", index), desc)
896 continue
897 }
898 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
899 // and thus require special treatment. If BuildStatement were an interface implementing
900 // buildRule(ctx) function, the code here would just call it.
901 // Unfortunately, the BuildStatement is defined in
902 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
903 // because this would cause circular dependency. So, until we move aquery processing
904 // to the 'android' package, we need to handle special cases here.
905 if buildStatement.Mnemonic == "FileWrite" || buildStatement.Mnemonic == "SourceSymlinkManifest" {
906 // Pass file contents as the value of the rule's "content" argument.
907 // Escape newlines and $ in the contents (the action "writeBazelFile" restores "\\n"
908 // back to the newline, and Ninja reads $$ as $.
909 escaped := strings.ReplaceAll(strings.ReplaceAll(buildStatement.FileContents, "\n", "\\n"),
910 "$", "$$")
911 ctx.Build(pctx, BuildParams{
912 Rule: writeBazelFile,
913 Output: PathForBazelOut(ctx, buildStatement.OutputPaths[0]),
914 Description: fmt.Sprintf("%s %s", buildStatement.Mnemonic, buildStatement.OutputPaths[0]),
915 Args: map[string]string{
916 "content": escaped,
917 },
918 })
Sasha Smundakc180dbd2022-07-03 14:55:58 -0700919 } else if buildStatement.Mnemonic == "SymlinkTree" {
920 // build-runfiles arguments are the manifest file and the target directory
921 // where it creates the symlink tree according to this manifest (and then
922 // writes the MANIFEST file to it).
923 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
924 outManifestPath := outManifest.String()
925 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
926 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
927 }
928 outDir := filepath.Dir(outManifestPath)
929 ctx.Build(pctx, BuildParams{
930 Rule: buildRunfilesRule,
931 Output: outManifest,
932 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
933 Description: "symlink tree for " + outDir,
934 Args: map[string]string{
935 "outDir": outDir,
936 },
937 })
Sasha Smundak1da064c2022-06-08 16:36:16 -0700938 } else {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000939 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500940 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400941 }
942}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500943
Usta Shresthaacd5a0c2022-06-22 11:20:50 -0400944// Register bazel-owned build statements (obtained from the aquery invocation).
945func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx PathContext) {
946 // executionRoot is the action cwd.
947 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
948
949 // Remove old outputs, as some actions might not rerun if the outputs are detected.
950 if len(buildStatement.OutputPaths) > 0 {
951 cmd.Text("rm -f")
952 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -0400953 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -0400954 }
955 cmd.Text("&&")
956 }
957
958 for _, pair := range buildStatement.Env {
959 // Set per-action env variables, if any.
960 cmd.Flag(pair.Key + "=" + pair.Value)
961 }
962
963 // The actual Bazel action.
964 cmd.Text(buildStatement.Command)
965
966 for _, outputPath := range buildStatement.OutputPaths {
967 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
968 }
969 for _, inputPath := range buildStatement.InputPaths {
970 cmd.Implicit(PathForBazelOut(ctx, inputPath))
971 }
972 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
973 otherDepsetName := bazelDepsetName(inputDepsetHash)
974 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
975 }
976
977 if depfile := buildStatement.Depfile; depfile != nil {
978 // The paths in depfile are relative to `executionRoot`.
979 // Hence, they need to be corrected by replacing "bazel-out"
980 // with the full `bazelOutDir`.
981 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
982 // would be deemed missing.
983 // (Note: The regexp uses a capture group because the version of sed
984 // does not support a look-behind pattern.)
985 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
986 bazelOutDir, *depfile)
987 cmd.Text(replacement)
988 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
989 }
990
991 for _, symlinkPath := range buildStatement.SymlinkPaths {
992 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
993 }
994}
995
Chris Parsons8d6e4332021-02-22 16:13:50 -0500996func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -0400997 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500998}
999
Chris Parsons787fb362021-10-14 18:43:51 -04001000func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001001 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001002 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001003 if key.configKey.osType.Class == Device {
1004 // For the generic Android, the expected result is "target|android", which
1005 // corresponds to the product_variable_config named "android_target" in
1006 // build/bazel/platforms/BUILD.bazel.
1007 arch = "target"
1008 } else {
1009 // Use host platform, which is currently hardcoded to be x86_64.
1010 arch = "x86_64"
1011 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001012 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001013 osName := key.configKey.osType.Name
1014 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" {
Chris Parsons787fb362021-10-14 18:43:51 -04001015 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001016 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001017 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001018 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -04001019}
1020
Chris Parsonsf874e462022-05-10 13:50:12 -04001021func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001022 return configKey{
1023 // use string because Arch is not a valid key in go
1024 arch: ctx.Arch().String(),
1025 osType: ctx.Os(),
1026 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001027}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001028
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001029func bazelDepsetName(contentHash string) string {
1030 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001031}