blob: 93b677930cf5a44161e114f59a8ccdc45a501d67 [file] [log] [blame]
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001// Copyright 2020 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package android
16
17import (
18 "bytes"
19 "errors"
20 "fmt"
Chris Parsonsa798d962020-10-12 23:44:08 -040021 "io/ioutil"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040022 "os"
23 "os/exec"
Usta Shresthaacd5a0c2022-06-22 11:20:50 -040024 "path"
Chris Parsonsa798d962020-10-12 23:44:08 -040025 "path/filepath"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040026 "runtime"
27 "strings"
28 "sync"
Chris Parsonsa798d962020-10-12 23:44:08 -040029
Chris Parsonsad876012022-08-20 14:48:32 -040030 "android/soong/android/allowlists"
Chris Parsons944e7d02021-03-11 11:08:46 -050031 "android/soong/bazel/cquery"
Jingwen Chen1e347862021-09-02 12:11:49 +000032 "android/soong/shared"
Liz Kammer337e9032022-08-03 15:49:43 -040033
Chris Parsons1a7aca02022-04-25 22:35:15 -040034 "github.com/google/blueprint"
Liz Kammer8206d4f2021-03-03 16:40:52 -050035
Patrice Arruda05ab2d02020-12-12 06:24:26 +000036 "android/soong/bazel"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040037)
38
Sasha Smundak1da064c2022-06-08 16:36:16 -070039var (
40 writeBazelFile = pctx.AndroidStaticRule("bazelWriteFileRule", blueprint.RuleParams{
41 Command: `sed "s/\\\\n/\n/g" ${out}.rsp >${out}`,
42 Rspfile: "${out}.rsp",
43 RspfileContent: "${content}",
44 }, "content")
Sasha Smundakc180dbd2022-07-03 14:55:58 -070045 _ = pctx.HostBinToolVariable("bazelBuildRunfilesTool", "build-runfiles")
46 buildRunfilesRule = pctx.AndroidStaticRule("bazelBuildRunfiles", blueprint.RuleParams{
47 Command: "${bazelBuildRunfilesTool} ${in} ${outDir}",
48 Depfile: "",
49 Description: "",
50 CommandDeps: []string{"${bazelBuildRunfilesTool}"},
51 }, "outDir")
Sasha Smundak1da064c2022-06-08 16:36:16 -070052)
53
Chris Parsonsf874e462022-05-10 13:50:12 -040054func init() {
55 RegisterMixedBuildsMutator(InitRegistrationContext)
56}
57
58func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammer337e9032022-08-03 15:49:43 -040059 ctx.FinalDepsMutators(func(ctx RegisterMutatorsContext) {
Chris Parsonsf874e462022-05-10 13:50:12 -040060 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
61 })
62}
63
64func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
65 if m := ctx.Module(); m.Enabled() {
66 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
67 if mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx) {
68 mixedBuildMod.QueueBazelCall(ctx)
69 }
70 }
71 }
72}
73
Liz Kammerf29df7c2021-04-02 13:37:39 -040074type cqueryRequest interface {
75 // Name returns a string name for this request type. Such request type names must be unique,
76 // and must only consist of alphanumeric characters.
77 Name() string
78
79 // StarlarkFunctionBody returns a starlark function body to process this request type.
80 // The returned string is the body of a Starlark function which obtains
81 // all request-relevant information about a target and returns a string containing
82 // this information.
83 // The function should have the following properties:
84 // - `target` is the only parameter to this function (a configured target).
85 // - The return value must be a string.
86 // - The function body should not be indented outside of its own scope.
87 StarlarkFunctionBody() string
88}
89
Chris Parsons787fb362021-10-14 18:43:51 -040090// Portion of cquery map key to describe target configuration.
91type configKey struct {
Liz Kammer0940b892022-03-18 15:55:04 -040092 arch string
93 osType OsType
Chris Parsons787fb362021-10-14 18:43:51 -040094}
95
Sasha Smundakfe9a5b82022-07-27 14:51:45 -070096func (c configKey) String() string {
97 return fmt.Sprintf("%s::%s", c.arch, c.osType)
98}
99
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400100// Map key to describe bazel cquery requests.
101type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400102 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400103 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400104 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400105}
106
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700107func (c cqueryKey) String() string {
108 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
109
110}
111
Chris Parsonsf874e462022-05-10 13:50:12 -0400112// BazelContext is a context object useful for interacting with Bazel during
113// the course of a build. Use of Bazel to evaluate part of the build graph
114// is referred to as a "mixed build". (Some modules are managed by Soong,
115// some are managed by Bazel). To facilitate interop between these build
116// subgraphs, Soong may make requests to Bazel and evaluate their responses
117// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400118type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400119 // Add a cquery request to the bazel request queue. All queued requests
120 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
121 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
122
123 // ** Cquery Results Retrieval Functions
124 // The below functions pertain to retrieving cquery results from a prior
125 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400126
127 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400128 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500129
Chris Parsons944e7d02021-03-11 11:08:46 -0500130 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400131 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400132
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000133 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400134 // TODO(b/232976601): Remove.
135 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000136
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700137 // Returns the results of the GetApexInfo query (including output files)
138 GetApexInfo(label string, cfgkey configKey) (cquery.ApexCqueryInfo, error)
139
Chris Parsonsf874e462022-05-10 13:50:12 -0400140 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400141
142 // Issues commands to Bazel to receive results for all cquery requests
143 // queued in the BazelContext.
Yu Liu8d82ac52022-05-17 15:13:28 -0700144 InvokeBazel(config Config) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400145
Chris Parsonsad876012022-08-20 14:48:32 -0400146 // Returns true if Bazel handling is enabled for the module with the given name.
147 // Note that this only implies "bazel mixed build" allowlisting. The caller
148 // should independently verify the module is eligible for Bazel handling
149 // (for example, that it is MixedBuildBuildable).
150 BazelAllowlisted(moduleName string) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500151
152 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
153 OutputBase() string
154
155 // Returns build statements which should get registered to reflect Bazel's outputs.
156 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400157
158 // Returns the depsets defined in Bazel's aquery response.
159 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400160}
161
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400162type bazelRunner interface {
163 issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) (string, string, error)
164}
165
166type bazelPaths struct {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400167 homeDir string
168 bazelPath string
169 outputBase string
170 workspaceDir string
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200171 soongOutDir string
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000172 metricsDir string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400173}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400174
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400175// A context object which tracks queued requests that need to be made to Bazel,
176// and their results after the requests have been made.
177type bazelContext struct {
178 bazelRunner
179 paths *bazelPaths
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400180 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
181 requestMutex sync.Mutex // requests can be written in parallel
182
183 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500184
185 // Build statements which should get registered to reflect Bazel's outputs.
186 buildStatements []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400187
188 // Depsets which should be used for Bazel's build statements.
189 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400190
191 // Per-module allowlist/denylist functionality to control whether analysis of
192 // modules are handled by Bazel. For modules which do not have a Bazel definition
193 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
194 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
195 // Per-module denylist to opt modules out of bazel handling.
196 bazelDisabledModules map[string]bool
197 // Per-module allowlist to opt modules in to bazel handling.
198 bazelEnabledModules map[string]bool
199 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
200 modulesDefaultToBazel bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400201}
202
203var _ BazelContext = &bazelContext{}
204
205// A bazel context to use when Bazel is disabled.
206type noopBazelContext struct{}
207
208var _ BazelContext = noopBazelContext{}
209
210// A bazel context to use for tests.
211type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400212 OutputBaseDir string
213
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000214 LabelToOutputFiles map[string][]string
215 LabelToCcInfo map[string]cquery.CcInfo
216 LabelToPythonBinary map[string]string
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700217 LabelToApexInfo map[string]cquery.ApexCqueryInfo
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400218}
219
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700220func (m MockBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400221 panic("unimplemented")
Chris Parsons8d6e4332021-02-22 16:13:50 -0500222}
223
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700224func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400225 result, _ := m.LabelToOutputFiles[label]
226 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400227}
228
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700229func (m MockBazelContext) GetCcInfo(label string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400230 result, _ := m.LabelToCcInfo[label]
231 return result, nil
232}
233
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700234func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400235 result, _ := m.LabelToPythonBinary[label]
236 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000237}
238
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700239func (n MockBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexCqueryInfo, error) {
240 panic("unimplemented")
241}
242
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700243func (m MockBazelContext) InvokeBazel(_ Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400244 panic("unimplemented")
245}
246
Chris Parsonsad876012022-08-20 14:48:32 -0400247func (m MockBazelContext) BazelAllowlisted(moduleName string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400248 return true
249}
250
Liz Kammera92e8442021-04-07 20:25:21 -0400251func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500252
253func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
254 return []bazel.BuildStatement{}
255}
256
Chris Parsons1a7aca02022-04-25 22:35:15 -0400257func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
258 return []bazel.AqueryDepset{}
259}
260
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400261var _ BazelContext = MockBazelContext{}
262
Chris Parsonsf874e462022-05-10 13:50:12 -0400263func (bazelCtx *bazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
264 key := cqueryKey{label, requestType, cfgKey}
265 bazelCtx.requestMutex.Lock()
266 defer bazelCtx.requestMutex.Unlock()
267 bazelCtx.requests[key] = true
268}
269
270func (bazelCtx *bazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
271 key := cqueryKey{label, cquery.GetOutputFiles, cfgKey}
272 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500273 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400274 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400275 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400276 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400277}
278
Chris Parsonsf874e462022-05-10 13:50:12 -0400279func (bazelCtx *bazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
280 key := cqueryKey{label, cquery.GetCcInfo, cfgKey}
281 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000282 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400283 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000284 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400285 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 +0000286}
287
Chris Parsonsf874e462022-05-10 13:50:12 -0400288func (bazelCtx *bazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
289 key := cqueryKey{label, cquery.GetPythonBinary, cfgKey}
290 if rawString, ok := bazelCtx.results[key]; ok {
291 bazelOutput := strings.TrimSpace(rawString)
292 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
293 }
294 return "", fmt.Errorf("no bazel response found for %v", key)
295}
296
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700297func (bazelCtx *bazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexCqueryInfo, error) {
298 key := cqueryKey{label, cquery.GetApexInfo, cfgKey}
299 if rawString, ok := bazelCtx.results[key]; ok {
300 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString)), nil
301 }
302 return cquery.ApexCqueryInfo{}, fmt.Errorf("no bazel response found for %v", key)
303}
304
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700305func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500306 panic("unimplemented")
307}
308
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700309func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500310 panic("unimplemented")
311}
312
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700313func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400314 panic("unimplemented")
315}
316
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700317func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000318 panic("unimplemented")
319}
320
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700321func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexCqueryInfo, error) {
322 panic("unimplemented")
323}
324
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700325func (n noopBazelContext) InvokeBazel(_ Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400326 panic("unimplemented")
327}
328
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500329func (m noopBazelContext) OutputBase() string {
330 return ""
331}
332
Chris Parsonsad876012022-08-20 14:48:32 -0400333func (n noopBazelContext) BazelAllowlisted(moduleName string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400334 return false
335}
336
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500337func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
338 return []bazel.BuildStatement{}
339}
340
Chris Parsons1a7aca02022-04-25 22:35:15 -0400341func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
342 return []bazel.AqueryDepset{}
343}
344
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400345func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400346 var modulesDefaultToBazel bool
347 disabledModules := map[string]bool{}
348 enabledModules := map[string]bool{}
349
350 switch c.BuildMode {
351 case BazelProdMode:
352 modulesDefaultToBazel = false
353
354 for _, enabledProdModule := range allowlists.ProdMixedBuildsEnabledList {
355 enabledModules[enabledProdModule] = true
356 }
357 case BazelDevMode:
358 modulesDefaultToBazel = true
359
360 // Don't use partially-converted cc_library targets in mixed builds,
361 // since mixed builds would generally rely on both static and shared
362 // variants of a cc_library.
363 for staticOnlyModule, _ := range GetBp2BuildAllowList().ccLibraryStaticOnly {
364 disabledModules[staticOnlyModule] = true
365 }
366 for _, disabledDevModule := range allowlists.MixedBuildsDisabledList {
367 disabledModules[disabledDevModule] = true
368 }
369 default:
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400370 return noopBazelContext{}, nil
371 }
372
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400373 p, err := bazelPathsFromConfig(c)
374 if err != nil {
375 return nil, err
376 }
Chris Parsonsad876012022-08-20 14:48:32 -0400377
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400378 return &bazelContext{
Chris Parsonsad876012022-08-20 14:48:32 -0400379 bazelRunner: &builtinBazelRunner{},
380 paths: p,
381 requests: make(map[cqueryKey]bool),
Chris Parsonsef615e52022-08-18 22:04:11 -0400382 modulesDefaultToBazel: modulesDefaultToBazel,
383 bazelEnabledModules: enabledModules,
Chris Parsonsad876012022-08-20 14:48:32 -0400384 bazelDisabledModules: disabledModules,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400385 }, nil
386}
387
388func bazelPathsFromConfig(c *config) (*bazelPaths, error) {
389 p := bazelPaths{
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200390 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400391 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700392 var missingEnvVars []string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400393 if len(c.Getenv("BAZEL_HOME")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400394 p.homeDir = c.Getenv("BAZEL_HOME")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400395 } else {
396 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
397 }
398 if len(c.Getenv("BAZEL_PATH")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400399 p.bazelPath = c.Getenv("BAZEL_PATH")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400400 } else {
401 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
402 }
403 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400404 p.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400405 } else {
406 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
407 }
408 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400409 p.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400410 } else {
411 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
412 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000413 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400414 p.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000415 } else {
416 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
417 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400418 if len(missingEnvVars) > 0 {
419 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
420 } else {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400421 return &p, nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400422 }
423}
424
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400425func (p *bazelPaths) BazelMetricsDir() string {
426 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000427}
428
Chris Parsonsad876012022-08-20 14:48:32 -0400429func (context *bazelContext) BazelAllowlisted(moduleName string) bool {
430 if context.bazelDisabledModules[moduleName] {
431 return false
432 }
433 if context.bazelEnabledModules[moduleName] {
434 return true
435 }
436 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400437}
438
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400439func pwdPrefix() string {
440 // Darwin doesn't have /proc
441 if runtime.GOOS != "darwin" {
442 return "PWD=/proc/self/cwd"
443 }
444 return ""
445}
446
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400447type bazelCommand struct {
448 command string
449 // query or label
450 expression string
451}
452
453type mockBazelRunner struct {
454 bazelCommandResults map[bazelCommand]string
455 commands []bazelCommand
Yu Liu8d82ac52022-05-17 15:13:28 -0700456 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400457}
458
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700459func (r *mockBazelRunner) issueBazelCommand(_ *bazelPaths, _ bazel.RunName,
460 command bazelCommand, extraFlags ...string) (string, string, error) {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400461 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700462 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400463 if ret, ok := r.bazelCommandResults[command]; ok {
464 return ret, "", nil
465 }
466 return "", "", nil
467}
468
469type builtinBazelRunner struct{}
470
Chris Parsons808d84c2021-03-09 20:43:32 -0500471// Issues the given bazel command with given build label and additional flags.
472// Returns (stdout, stderr, error). The first and second return values are strings
473// containing the stdout and stderr of the run command, and an error is returned if
474// the invocation returned an error code.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400475func (r *builtinBazelRunner) issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Chris Parsons808d84c2021-03-09 20:43:32 -0500476 extraFlags ...string) (string, string, error) {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000477 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000478 "--output_base=" + absolutePath(paths.outputBase),
479 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700480 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700481 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700482 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400483
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700484 // Set default platforms to canonicalized values for mixed builds requests.
485 // If these are set in the bazelrc, they will have values that are
486 // non-canonicalized to @sourceroot labels, and thus be invalid when
487 // referenced from the buildroot.
488 //
489 // The actual platform values here may be overridden by configuration
490 // transitions from the buildroot.
491 fmt.Sprintf("--platforms=%s", "//build/bazel/platforms:android_target"),
492 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Jingwen Chen91220d72021-03-24 02:18:33 -0400493
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700494 // This should be parameterized on the host OS, but let's restrict to linux
495 // to keep things simple for now.
496 fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"),
497
498 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
499 "--experimental_repository_disable_download",
500
501 // Suppress noise
502 "--ui_event_filters=-INFO",
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700503 "--noshow_progress"}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400504 cmdFlags = append(cmdFlags, extraFlags...)
505
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400506 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200507 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700508 extraEnv := []string{
509 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200510 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700511 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Jingwen Chen8c523582021-06-01 11:19:53 +0000512 // Make OUT_DIR absolute here so tools/bazel.sh uses the correct
513 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700514 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500515 // Disables local host detection of gcc; toolchain information is defined
516 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700517 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
518 }
519 bazelCmd.Env = append(os.Environ(), extraEnv...)
Colin Crossff0278b2020-10-09 19:24:15 -0700520 stderr := &bytes.Buffer{}
521 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400522
523 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500524 return "", string(stderr.Bytes()),
525 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400526 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500527 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400528 }
529}
530
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400531func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500532 // TODO(cparsons): Define configuration transitions programmatically based
533 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400534 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500535#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400536# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500537#####################################################
538
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400539def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500540 return {
Chris Parsons787fb362021-10-14 18:43:51 -0400541 "//command_line_option:platforms": "@//build/bazel/platforms:%s_%s" % (attr.os, attr.arch),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500542 }
543
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400544_config_node_transition = transition(
545 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500546 inputs = [],
547 outputs = [
548 "//command_line_option:platforms",
549 ],
550)
551
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400552def _passthrough_rule_impl(ctx):
553 return [DefaultInfo(files = depset(ctx.files.deps))]
554
555config_node = rule(
556 implementation = _passthrough_rule_impl,
557 attrs = {
558 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400559 "os" : attr.string(mandatory = True),
560 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400561 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
562 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500563)
564
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400565
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500566# Rule representing the root of the build, to depend on all Bazel targets that
567# are required for the build. Building this target will build the entire Bazel
568# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400569mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400570 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500571 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400572 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500573 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400574)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500575
576def _phony_root_impl(ctx):
577 return []
578
579# Rule to depend on other targets but build nothing.
580# This is useful as follows: building a target of this rule will generate
581# symlink forests for all dependencies of the target, without executing any
582# actions of the build.
583phony_root = rule(
584 implementation = _phony_root_impl,
585 attrs = {"deps" : attr.label_list()},
586)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400587`
588 return []byte(contents)
589}
590
591func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500592 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
593 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400594 formatString := `
595# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400596load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
597
598%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400599
600mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400601 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400602)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500603
604phony_root(name = "phonyroot",
605 deps = [":buildroot"],
606)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400607`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400608 configNodeFormatString := `
609config_node(name = "%s",
610 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400611 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400612 deps = [%s],
613)
614`
615
616 configNodesSection := ""
617
Chris Parsons787fb362021-10-14 18:43:51 -0400618 labelsByConfig := map[string][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400619 for val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200620 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400621 configString := getConfigString(val)
622 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400623 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400624
Jingwen Chen1e347862021-09-02 12:11:49 +0000625 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400626 for configString, labels := range labelsByConfig {
627 configTokens := strings.Split(configString, "|")
628 if len(configTokens) != 2 {
629 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000630 }
Chris Parsons787fb362021-10-14 18:43:51 -0400631 archString := configTokens[0]
632 osString := configTokens[1]
633 targetString := fmt.Sprintf("%s_%s", osString, archString)
634 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
635 labelsString := strings.Join(labels, ",\n ")
636 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400637 }
638
Jingwen Chen1e347862021-09-02 12:11:49 +0000639 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400640}
641
Chris Parsons944e7d02021-03-11 11:08:46 -0500642func indent(original string) string {
643 result := ""
644 for _, line := range strings.Split(original, "\n") {
645 result += " " + line + "\n"
646 }
647 return result
648}
649
Chris Parsons808d84c2021-03-09 20:43:32 -0500650// Returns the file contents of the buildroot.cquery file that should be used for the cquery
651// expression in order to obtain information about buildroot and its dependencies.
652// The contents of this file depend on the bazelContext's requests; requests are enumerated
653// and grouped by their request type. The data retrieved for each label depends on its
654// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400655func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400656 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400657 for val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500658 cqueryId := getCqueryId(val)
659 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
660 requestTypeToCqueryIdEntries[val.requestType] =
661 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
662 }
663 labelRegistrationMapSection := ""
664 functionDefSection := ""
665 mainSwitchSection := ""
666
667 mapDeclarationFormatString := `
668%s = {
669 %s
670}
671`
672 functionDefFormatString := `
673def %s(target):
674%s
675`
676 mainSwitchSectionFormatString := `
677 if id_string in %s:
678 return id_string + ">>" + %s(target)
679`
680
Usta Shrestha0b52d832022-02-04 21:37:39 -0500681 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500682 labelMapName := requestType.Name() + "_Labels"
683 functionName := requestType.Name() + "_Fn"
684 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
685 labelMapName,
686 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
687 functionDefSection += fmt.Sprintf(functionDefFormatString,
688 functionName,
689 indent(requestType.StarlarkFunctionBody()))
690 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
691 labelMapName, functionName)
692 }
693
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400694 formatString := `
695# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400696
Chris Parsons944e7d02021-03-11 11:08:46 -0500697# Label Map Section
698%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500699
Chris Parsons944e7d02021-03-11 11:08:46 -0500700# Function Def Section
701%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500702
703def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400704 # TODO(b/199363072): filegroups and file targets aren't associated with any
705 # specific platform architecture in mixed builds. This is consistent with how
706 # Soong treats filegroups, but it may not be the case with manually-written
707 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500708 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000709 if buildoptions == None:
710 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400711 # any specific platform architecture in mixed builds, so use the host.
712 return "x86_64|linux"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500713 platforms = build_options(target)["//command_line_option:platforms"]
714 if len(platforms) != 1:
715 # An individual configured target should have only one platform architecture.
716 # Note that it's fine for there to be multiple architectures for the same label,
717 # but each is its own configured target.
718 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
719 platform_name = build_options(target)["//command_line_option:platforms"][0].name
720 if platform_name == "host":
721 return "HOST"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400722 elif platform_name.startswith("android_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400723 return platform_name[len("android_"):] + "|" + platform_name[:len("android_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400724 elif platform_name.startswith("linux_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400725 return platform_name[len("linux_"):] + "|" + platform_name[:len("linux_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400726 else:
727 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500728 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500729
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700730def json_for_file(key, file):
731 return '"' + key + '":"' + file.path + '"'
732
733def json_for_files(key, files):
734 return '"' + key + '":[' + ",".join(['"' + f.path + '"' for f in files]) + ']'
735
736def json_for_labels(key, ll):
737 return '"' + key + '":[' + ",".join(['"' + str(x) + '"' for x in ll]) + ']'
738
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400739def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500740 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500741
742 # Main switch section
743 %s
744 # This target was not requested via cquery, and thus must be a dependency
745 # of a requested target.
746 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400747`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400748
Chris Parsons944e7d02021-03-11 11:08:46 -0500749 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
750 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400751}
752
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200753// Returns a path containing build-related metadata required for interfacing
754// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400755func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200756 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500757}
758
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200759// Returns the path where the contents of the @soong_injection repository live.
760// It is used by Soong to tell Bazel things it cannot over the command line.
761func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200762 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200763}
764
765// Returns the path of the synthetic Bazel workspace that contains a symlink
766// forest composed the whole source tree and BUILD files generated by bp2build.
767func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200768 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200769}
770
Jingwen Chen8c523582021-06-01 11:19:53 +0000771// Returns the path to the top level out dir ($OUT_DIR).
772func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200773 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000774}
775
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400776// Issues commands to Bazel to receive results for all cquery requests
777// queued in the BazelContext.
Yu Liu8d82ac52022-05-17 15:13:28 -0700778func (context *bazelContext) InvokeBazel(config Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400779 context.results = make(map[cqueryKey]string)
780
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400781 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500782
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200783 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200784 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
785 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
786 err = os.MkdirAll(mixedBuildsPath, 0777)
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500787 }
Chris Parsons8ccdb632020-11-17 15:41:01 -0500788 if err != nil {
789 return err
790 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500791 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
792 err = os.MkdirAll(metricsDir, 0777)
793 if err != nil {
794 return err
795 }
796 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700797 if err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200798 return err
799 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700800 if err = ioutil.WriteFile(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400801 return err
802 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700803 if err = ioutil.WriteFile(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400804 return err
805 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200806 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700807 if err = ioutil.WriteFile(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400808 return err
809 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000810
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700811 const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
812 cqueryCmd := bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
813 cqueryOutput, cqueryErr, err := context.issueBazelCommand(context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
814 "--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500815 if err != nil {
Chris Parsons429f5402022-08-11 17:02:41 -0400816 return err
Chris Parsons8d6e4332021-02-22 16:13:50 -0500817 }
Chris Parsons429f5402022-08-11 17:02:41 -0400818 if err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400819 return err
820 }
821
822 cqueryResults := map[string]string{}
823 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
824 if strings.Contains(outputLine, ">>") {
825 splitLine := strings.SplitN(outputLine, ">>", 2)
826 cqueryResults[splitLine[0]] = splitLine[1]
827 }
828 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500829 for val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500830 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -0500831 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400832 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500833 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
834 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400835 }
836 }
837
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500838 // Issue an aquery command to retrieve action information about the bazel build tree.
839 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700840 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
841 // proto sources, which would add a number of unnecessary dependencies.
842 extraFlags := []string{"--output=jsonproto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -0700843 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700844 extraFlags = append(extraFlags, "--collect_code_coverage")
845 paths := make([]string, 0, 2)
846 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
847 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
848 }
849 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
850 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
851 }
852 if len(paths) > 0 {
853 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -0700854 }
855 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700856 aqueryCmd := bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
857 if aqueryOutput, _, err := context.issueBazelCommand(context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
858 extraFlags...); err == nil {
859 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400860 }
Chris Parsons4f069892021-01-15 12:22:41 -0500861 if err != nil {
862 return err
863 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500864
865 // Issue a build command of the phony root to generate symlink forests for dependencies of the
866 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
867 // but some of symlinks may be required to resolve source dependencies of the build.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700868 buildCmd := bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
869 if _, _, err = context.issueBazelCommand(context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd); err != nil {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500870 return err
871 }
872
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400873 // Clear requests.
874 context.requests = map[cqueryKey]bool{}
875 return nil
876}
Chris Parsonsa798d962020-10-12 23:44:08 -0400877
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500878func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
879 return context.buildStatements
880}
881
Chris Parsons1a7aca02022-04-25 22:35:15 -0400882func (context *bazelContext) AqueryDepsets() []bazel.AqueryDepset {
883 return context.depsets
884}
885
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500886func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400887 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500888}
889
Chris Parsonsa798d962020-10-12 23:44:08 -0400890// Singleton used for registering BUILD file ninja dependencies (needed
891// for correctness of builds which use Bazel.
892func BazelSingleton() Singleton {
893 return &bazelSingleton{}
894}
895
896type bazelSingleton struct{}
897
898func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500899 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -0400900 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500901 return
902 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400903
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500904 // Add ninja file dependencies for files which all bazel invocations require.
905 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200906 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500907 ctx.AddNinjaFileDeps(bazelBuildList)
908
909 data, err := ioutil.ReadFile(bazelBuildList)
910 if err != nil {
911 ctx.Errorf(err.Error())
912 }
913 files := strings.Split(strings.TrimSpace(string(data)), "\n")
914 for _, file := range files {
915 ctx.AddNinjaFileDeps(file)
916 }
917
Chris Parsons1a7aca02022-04-25 22:35:15 -0400918 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
919 var outputs []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400920 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
921 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400922 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
923 }
924 for _, artifactPath := range depset.DirectArtifacts {
925 outputs = append(outputs, PathForBazelOut(ctx, artifactPath))
926 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400927 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400928 ctx.Build(pctx, BuildParams{
929 Rule: blueprint.Phony,
930 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
931 Implicits: outputs,
932 })
933 }
934
Usta Shresthaacd5a0c2022-06-22 11:20:50 -0400935 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
936 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500937 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -0700938 if len(buildStatement.Command) > 0 {
939 rule := NewRuleBuilder(pctx, ctx)
940 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
941 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
942 rule.Build(fmt.Sprintf("bazel %d", index), desc)
943 continue
944 }
945 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
946 // and thus require special treatment. If BuildStatement were an interface implementing
947 // buildRule(ctx) function, the code here would just call it.
948 // Unfortunately, the BuildStatement is defined in
949 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
950 // because this would cause circular dependency. So, until we move aquery processing
951 // to the 'android' package, we need to handle special cases here.
952 if buildStatement.Mnemonic == "FileWrite" || buildStatement.Mnemonic == "SourceSymlinkManifest" {
953 // Pass file contents as the value of the rule's "content" argument.
954 // Escape newlines and $ in the contents (the action "writeBazelFile" restores "\\n"
955 // back to the newline, and Ninja reads $$ as $.
956 escaped := strings.ReplaceAll(strings.ReplaceAll(buildStatement.FileContents, "\n", "\\n"),
957 "$", "$$")
958 ctx.Build(pctx, BuildParams{
959 Rule: writeBazelFile,
960 Output: PathForBazelOut(ctx, buildStatement.OutputPaths[0]),
961 Description: fmt.Sprintf("%s %s", buildStatement.Mnemonic, buildStatement.OutputPaths[0]),
962 Args: map[string]string{
963 "content": escaped,
964 },
965 })
Sasha Smundakc180dbd2022-07-03 14:55:58 -0700966 } else if buildStatement.Mnemonic == "SymlinkTree" {
967 // build-runfiles arguments are the manifest file and the target directory
968 // where it creates the symlink tree according to this manifest (and then
969 // writes the MANIFEST file to it).
970 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
971 outManifestPath := outManifest.String()
972 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
973 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
974 }
975 outDir := filepath.Dir(outManifestPath)
976 ctx.Build(pctx, BuildParams{
977 Rule: buildRunfilesRule,
978 Output: outManifest,
979 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
980 Description: "symlink tree for " + outDir,
981 Args: map[string]string{
982 "outDir": outDir,
983 },
984 })
Sasha Smundak1da064c2022-06-08 16:36:16 -0700985 } else {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000986 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500987 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400988 }
989}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500990
Usta Shresthaacd5a0c2022-06-22 11:20:50 -0400991// Register bazel-owned build statements (obtained from the aquery invocation).
992func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx PathContext) {
993 // executionRoot is the action cwd.
994 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
995
996 // Remove old outputs, as some actions might not rerun if the outputs are detected.
997 if len(buildStatement.OutputPaths) > 0 {
998 cmd.Text("rm -f")
999 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001000 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001001 }
1002 cmd.Text("&&")
1003 }
1004
1005 for _, pair := range buildStatement.Env {
1006 // Set per-action env variables, if any.
1007 cmd.Flag(pair.Key + "=" + pair.Value)
1008 }
1009
1010 // The actual Bazel action.
1011 cmd.Text(buildStatement.Command)
1012
1013 for _, outputPath := range buildStatement.OutputPaths {
1014 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1015 }
1016 for _, inputPath := range buildStatement.InputPaths {
1017 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1018 }
1019 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1020 otherDepsetName := bazelDepsetName(inputDepsetHash)
1021 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1022 }
1023
1024 if depfile := buildStatement.Depfile; depfile != nil {
1025 // The paths in depfile are relative to `executionRoot`.
1026 // Hence, they need to be corrected by replacing "bazel-out"
1027 // with the full `bazelOutDir`.
1028 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1029 // would be deemed missing.
1030 // (Note: The regexp uses a capture group because the version of sed
1031 // does not support a look-behind pattern.)
1032 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1033 bazelOutDir, *depfile)
1034 cmd.Text(replacement)
1035 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1036 }
1037
1038 for _, symlinkPath := range buildStatement.SymlinkPaths {
1039 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1040 }
1041}
1042
Chris Parsons8d6e4332021-02-22 16:13:50 -05001043func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001044 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001045}
1046
Chris Parsons787fb362021-10-14 18:43:51 -04001047func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001048 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001049 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001050 if key.configKey.osType.Class == Device {
1051 // For the generic Android, the expected result is "target|android", which
1052 // corresponds to the product_variable_config named "android_target" in
1053 // build/bazel/platforms/BUILD.bazel.
1054 arch = "target"
1055 } else {
1056 // Use host platform, which is currently hardcoded to be x86_64.
1057 arch = "x86_64"
1058 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001059 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001060 osName := key.configKey.osType.Name
1061 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" {
Chris Parsons787fb362021-10-14 18:43:51 -04001062 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001063 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001064 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001065 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -04001066}
1067
Chris Parsonsf874e462022-05-10 13:50:12 -04001068func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001069 return configKey{
1070 // use string because Arch is not a valid key in go
1071 arch: ctx.Arch().String(),
1072 osType: ctx.Os(),
1073 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001074}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001075
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001076func bazelDepsetName(contentHash string) string {
1077 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001078}