blob: 64092927b56cf83f8398800072b168ac781b4c21 [file] [log] [blame]
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001// Copyright 2020 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package android
16
17import (
18 "bytes"
19 "errors"
20 "fmt"
Chris Parsonsa798d962020-10-12 23:44:08 -040021 "io/ioutil"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040022 "os"
23 "os/exec"
Usta Shresthaacd5a0c2022-06-22 11:20:50 -040024 "path"
Chris Parsonsa798d962020-10-12 23:44:08 -040025 "path/filepath"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040026 "runtime"
27 "strings"
28 "sync"
Chris Parsonsa798d962020-10-12 23:44:08 -040029
Chris Parsonsad876012022-08-20 14:48:32 -040030 "android/soong/android/allowlists"
Chris Parsons944e7d02021-03-11 11:08:46 -050031 "android/soong/bazel/cquery"
Jingwen Chen1e347862021-09-02 12:11:49 +000032 "android/soong/shared"
Liz Kammer337e9032022-08-03 15:49:43 -040033
Chris Parsons1a7aca02022-04-25 22:35:15 -040034 "github.com/google/blueprint"
Liz Kammer8206d4f2021-03-03 16:40:52 -050035
Patrice Arruda05ab2d02020-12-12 06:24:26 +000036 "android/soong/bazel"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040037)
38
Sasha Smundak1da064c2022-06-08 16:36:16 -070039var (
40 writeBazelFile = pctx.AndroidStaticRule("bazelWriteFileRule", blueprint.RuleParams{
41 Command: `sed "s/\\\\n/\n/g" ${out}.rsp >${out}`,
42 Rspfile: "${out}.rsp",
43 RspfileContent: "${content}",
44 }, "content")
Sasha Smundakc180dbd2022-07-03 14:55:58 -070045 _ = pctx.HostBinToolVariable("bazelBuildRunfilesTool", "build-runfiles")
46 buildRunfilesRule = pctx.AndroidStaticRule("bazelBuildRunfiles", blueprint.RuleParams{
47 Command: "${bazelBuildRunfilesTool} ${in} ${outDir}",
48 Depfile: "",
49 Description: "",
50 CommandDeps: []string{"${bazelBuildRunfilesTool}"},
51 }, "outDir")
Sasha Smundak1da064c2022-06-08 16:36:16 -070052)
53
Chris Parsonsf874e462022-05-10 13:50:12 -040054func init() {
55 RegisterMixedBuildsMutator(InitRegistrationContext)
56}
57
58func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammer337e9032022-08-03 15:49:43 -040059 ctx.FinalDepsMutators(func(ctx RegisterMutatorsContext) {
Chris Parsonsf874e462022-05-10 13:50:12 -040060 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
61 })
62}
63
64func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
65 if m := ctx.Module(); m.Enabled() {
66 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
67 if mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx) {
68 mixedBuildMod.QueueBazelCall(ctx)
69 }
70 }
71 }
72}
73
Liz Kammerf29df7c2021-04-02 13:37:39 -040074type cqueryRequest interface {
75 // Name returns a string name for this request type. Such request type names must be unique,
76 // and must only consist of alphanumeric characters.
77 Name() string
78
79 // StarlarkFunctionBody returns a starlark function body to process this request type.
80 // The returned string is the body of a Starlark function which obtains
81 // all request-relevant information about a target and returns a string containing
82 // this information.
83 // The function should have the following properties:
84 // - `target` is the only parameter to this function (a configured target).
85 // - The return value must be a string.
86 // - The function body should not be indented outside of its own scope.
87 StarlarkFunctionBody() string
88}
89
Chris Parsons787fb362021-10-14 18:43:51 -040090// Portion of cquery map key to describe target configuration.
91type configKey struct {
Liz Kammer0940b892022-03-18 15:55:04 -040092 arch string
93 osType OsType
Chris Parsons787fb362021-10-14 18:43:51 -040094}
95
Sasha Smundakfe9a5b82022-07-27 14:51:45 -070096func (c configKey) String() string {
97 return fmt.Sprintf("%s::%s", c.arch, c.osType)
98}
99
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400100// Map key to describe bazel cquery requests.
101type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400102 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400103 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400104 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400105}
106
Chris Parsons86dc2c22022-09-28 14:58:41 -0400107func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
108 if strings.HasPrefix(label, "//") {
109 // Normalize Bazel labels to specify main repository explicitly.
110 label = "@" + label
111 }
112 return cqueryKey{label, cqueryRequest, cfgKey}
113}
114
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700115func (c cqueryKey) String() string {
116 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700117}
118
Chris Parsonsf874e462022-05-10 13:50:12 -0400119// BazelContext is a context object useful for interacting with Bazel during
120// the course of a build. Use of Bazel to evaluate part of the build graph
121// is referred to as a "mixed build". (Some modules are managed by Soong,
122// some are managed by Bazel). To facilitate interop between these build
123// subgraphs, Soong may make requests to Bazel and evaluate their responses
124// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400125type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400126 // Add a cquery request to the bazel request queue. All queued requests
127 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
128 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
129
130 // ** Cquery Results Retrieval Functions
131 // The below functions pertain to retrieving cquery results from a prior
132 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400133
134 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400135 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500136
Chris Parsons944e7d02021-03-11 11:08:46 -0500137 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400138 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400139
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000140 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400141 // TODO(b/232976601): Remove.
142 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000143
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700144 // Returns the results of the GetApexInfo query (including output files)
145 GetApexInfo(label string, cfgkey configKey) (cquery.ApexCqueryInfo, error)
146
Chris Parsonsf874e462022-05-10 13:50:12 -0400147 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400148
149 // Issues commands to Bazel to receive results for all cquery requests
150 // queued in the BazelContext.
Yu Liu8d82ac52022-05-17 15:13:28 -0700151 InvokeBazel(config Config) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400152
Chris Parsonsad876012022-08-20 14:48:32 -0400153 // Returns true if Bazel handling is enabled for the module with the given name.
154 // Note that this only implies "bazel mixed build" allowlisting. The caller
155 // should independently verify the module is eligible for Bazel handling
156 // (for example, that it is MixedBuildBuildable).
157 BazelAllowlisted(moduleName string) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500158
159 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
160 OutputBase() string
161
162 // Returns build statements which should get registered to reflect Bazel's outputs.
163 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400164
165 // Returns the depsets defined in Bazel's aquery response.
166 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400167}
168
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400169type bazelRunner interface {
170 issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) (string, string, error)
171}
172
173type bazelPaths struct {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400174 homeDir string
175 bazelPath string
176 outputBase string
177 workspaceDir string
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200178 soongOutDir string
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000179 metricsDir string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400180}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400181
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400182// A context object which tracks queued requests that need to be made to Bazel,
183// and their results after the requests have been made.
184type bazelContext struct {
185 bazelRunner
186 paths *bazelPaths
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400187 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
188 requestMutex sync.Mutex // requests can be written in parallel
189
190 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500191
192 // Build statements which should get registered to reflect Bazel's outputs.
193 buildStatements []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400194
195 // Depsets which should be used for Bazel's build statements.
196 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400197
198 // Per-module allowlist/denylist functionality to control whether analysis of
199 // modules are handled by Bazel. For modules which do not have a Bazel definition
200 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
201 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
202 // Per-module denylist to opt modules out of bazel handling.
203 bazelDisabledModules map[string]bool
204 // Per-module allowlist to opt modules in to bazel handling.
205 bazelEnabledModules map[string]bool
206 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
207 modulesDefaultToBazel bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400208}
209
210var _ BazelContext = &bazelContext{}
211
212// A bazel context to use when Bazel is disabled.
213type noopBazelContext struct{}
214
215var _ BazelContext = noopBazelContext{}
216
217// A bazel context to use for tests.
218type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400219 OutputBaseDir string
220
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000221 LabelToOutputFiles map[string][]string
222 LabelToCcInfo map[string]cquery.CcInfo
223 LabelToPythonBinary map[string]string
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700224 LabelToApexInfo map[string]cquery.ApexCqueryInfo
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400225}
226
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700227func (m MockBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400228 panic("unimplemented")
Chris Parsons8d6e4332021-02-22 16:13:50 -0500229}
230
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700231func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400232 result, _ := m.LabelToOutputFiles[label]
233 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400234}
235
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700236func (m MockBazelContext) GetCcInfo(label string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400237 result, _ := m.LabelToCcInfo[label]
238 return result, nil
239}
240
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700241func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400242 result, _ := m.LabelToPythonBinary[label]
243 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000244}
245
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700246func (n MockBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexCqueryInfo, error) {
247 panic("unimplemented")
248}
249
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700250func (m MockBazelContext) InvokeBazel(_ Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400251 panic("unimplemented")
252}
253
Chris Parsonsad876012022-08-20 14:48:32 -0400254func (m MockBazelContext) BazelAllowlisted(moduleName string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400255 return true
256}
257
Liz Kammera92e8442021-04-07 20:25:21 -0400258func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500259
260func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
261 return []bazel.BuildStatement{}
262}
263
Chris Parsons1a7aca02022-04-25 22:35:15 -0400264func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
265 return []bazel.AqueryDepset{}
266}
267
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400268var _ BazelContext = MockBazelContext{}
269
Chris Parsonsf874e462022-05-10 13:50:12 -0400270func (bazelCtx *bazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400271 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400272 bazelCtx.requestMutex.Lock()
273 defer bazelCtx.requestMutex.Unlock()
274 bazelCtx.requests[key] = true
275}
276
277func (bazelCtx *bazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400278 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400279 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500280 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400281
Chris Parsonsf874e462022-05-10 13:50:12 -0400282 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400283 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400284 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400285}
286
Chris Parsonsf874e462022-05-10 13:50:12 -0400287func (bazelCtx *bazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400288 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400289 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000290 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400291 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000292 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400293 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 +0000294}
295
Chris Parsonsf874e462022-05-10 13:50:12 -0400296func (bazelCtx *bazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400297 key := makeCqueryKey(label, cquery.GetPythonBinary, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400298 if rawString, ok := bazelCtx.results[key]; ok {
299 bazelOutput := strings.TrimSpace(rawString)
300 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
301 }
302 return "", fmt.Errorf("no bazel response found for %v", key)
303}
304
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700305func (bazelCtx *bazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexCqueryInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400306 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700307 if rawString, ok := bazelCtx.results[key]; ok {
308 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString)), nil
309 }
310 return cquery.ApexCqueryInfo{}, fmt.Errorf("no bazel response found for %v", key)
311}
312
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700313func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500314 panic("unimplemented")
315}
316
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700317func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500318 panic("unimplemented")
319}
320
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700321func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400322 panic("unimplemented")
323}
324
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700325func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000326 panic("unimplemented")
327}
328
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700329func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexCqueryInfo, error) {
330 panic("unimplemented")
331}
332
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700333func (n noopBazelContext) InvokeBazel(_ Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400334 panic("unimplemented")
335}
336
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500337func (m noopBazelContext) OutputBase() string {
338 return ""
339}
340
Chris Parsonsad876012022-08-20 14:48:32 -0400341func (n noopBazelContext) BazelAllowlisted(moduleName string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400342 return false
343}
344
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500345func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
346 return []bazel.BuildStatement{}
347}
348
Chris Parsons1a7aca02022-04-25 22:35:15 -0400349func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
350 return []bazel.AqueryDepset{}
351}
352
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400353func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400354 var modulesDefaultToBazel bool
355 disabledModules := map[string]bool{}
356 enabledModules := map[string]bool{}
357
358 switch c.BuildMode {
359 case BazelProdMode:
360 modulesDefaultToBazel = false
361
362 for _, enabledProdModule := range allowlists.ProdMixedBuildsEnabledList {
363 enabledModules[enabledProdModule] = true
364 }
365 case BazelDevMode:
366 modulesDefaultToBazel = true
367
368 // Don't use partially-converted cc_library targets in mixed builds,
369 // since mixed builds would generally rely on both static and shared
370 // variants of a cc_library.
371 for staticOnlyModule, _ := range GetBp2BuildAllowList().ccLibraryStaticOnly {
372 disabledModules[staticOnlyModule] = true
373 }
374 for _, disabledDevModule := range allowlists.MixedBuildsDisabledList {
375 disabledModules[disabledDevModule] = true
376 }
377 default:
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400378 return noopBazelContext{}, nil
379 }
380
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400381 p, err := bazelPathsFromConfig(c)
382 if err != nil {
383 return nil, err
384 }
Chris Parsonsad876012022-08-20 14:48:32 -0400385
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400386 return &bazelContext{
Chris Parsonsad876012022-08-20 14:48:32 -0400387 bazelRunner: &builtinBazelRunner{},
388 paths: p,
389 requests: make(map[cqueryKey]bool),
Chris Parsonsef615e52022-08-18 22:04:11 -0400390 modulesDefaultToBazel: modulesDefaultToBazel,
391 bazelEnabledModules: enabledModules,
Chris Parsonsad876012022-08-20 14:48:32 -0400392 bazelDisabledModules: disabledModules,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400393 }, nil
394}
395
396func bazelPathsFromConfig(c *config) (*bazelPaths, error) {
397 p := bazelPaths{
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200398 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400399 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700400 var missingEnvVars []string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400401 if len(c.Getenv("BAZEL_HOME")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400402 p.homeDir = c.Getenv("BAZEL_HOME")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400403 } else {
404 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
405 }
406 if len(c.Getenv("BAZEL_PATH")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400407 p.bazelPath = c.Getenv("BAZEL_PATH")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400408 } else {
409 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
410 }
411 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400412 p.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400413 } else {
414 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
415 }
416 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400417 p.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400418 } else {
419 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
420 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000421 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400422 p.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000423 } else {
424 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
425 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400426 if len(missingEnvVars) > 0 {
427 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
428 } else {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400429 return &p, nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400430 }
431}
432
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400433func (p *bazelPaths) BazelMetricsDir() string {
434 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000435}
436
Chris Parsonsad876012022-08-20 14:48:32 -0400437func (context *bazelContext) BazelAllowlisted(moduleName string) bool {
438 if context.bazelDisabledModules[moduleName] {
439 return false
440 }
441 if context.bazelEnabledModules[moduleName] {
442 return true
443 }
444 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400445}
446
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400447func pwdPrefix() string {
448 // Darwin doesn't have /proc
449 if runtime.GOOS != "darwin" {
450 return "PWD=/proc/self/cwd"
451 }
452 return ""
453}
454
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400455type bazelCommand struct {
456 command string
457 // query or label
458 expression string
459}
460
461type mockBazelRunner struct {
462 bazelCommandResults map[bazelCommand]string
463 commands []bazelCommand
Yu Liu8d82ac52022-05-17 15:13:28 -0700464 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400465}
466
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700467func (r *mockBazelRunner) issueBazelCommand(_ *bazelPaths, _ bazel.RunName,
468 command bazelCommand, extraFlags ...string) (string, string, error) {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400469 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700470 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400471 if ret, ok := r.bazelCommandResults[command]; ok {
472 return ret, "", nil
473 }
474 return "", "", nil
475}
476
477type builtinBazelRunner struct{}
478
Chris Parsons808d84c2021-03-09 20:43:32 -0500479// Issues the given bazel command with given build label and additional flags.
480// Returns (stdout, stderr, error). The first and second return values are strings
481// containing the stdout and stderr of the run command, and an error is returned if
482// the invocation returned an error code.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400483func (r *builtinBazelRunner) issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Chris Parsons808d84c2021-03-09 20:43:32 -0500484 extraFlags ...string) (string, string, error) {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000485 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000486 "--output_base=" + absolutePath(paths.outputBase),
487 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700488 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700489 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700490 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400491
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700492 // Set default platforms to canonicalized values for mixed builds requests.
493 // If these are set in the bazelrc, they will have values that are
494 // non-canonicalized to @sourceroot labels, and thus be invalid when
495 // referenced from the buildroot.
496 //
497 // The actual platform values here may be overridden by configuration
498 // transitions from the buildroot.
499 fmt.Sprintf("--platforms=%s", "//build/bazel/platforms:android_target"),
500 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Jingwen Chen91220d72021-03-24 02:18:33 -0400501
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700502 // This should be parameterized on the host OS, but let's restrict to linux
503 // to keep things simple for now.
504 fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"),
505
506 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
507 "--experimental_repository_disable_download",
508
509 // Suppress noise
510 "--ui_event_filters=-INFO",
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700511 "--noshow_progress"}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400512 cmdFlags = append(cmdFlags, extraFlags...)
513
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400514 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200515 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700516 extraEnv := []string{
517 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200518 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700519 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Jingwen Chen8c523582021-06-01 11:19:53 +0000520 // Make OUT_DIR absolute here so tools/bazel.sh uses the correct
521 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700522 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500523 // Disables local host detection of gcc; toolchain information is defined
524 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700525 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
526 }
527 bazelCmd.Env = append(os.Environ(), extraEnv...)
Colin Crossff0278b2020-10-09 19:24:15 -0700528 stderr := &bytes.Buffer{}
529 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400530
531 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500532 return "", string(stderr.Bytes()),
533 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400534 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500535 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400536 }
537}
538
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400539func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500540 // TODO(cparsons): Define configuration transitions programmatically based
541 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400542 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500543#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400544# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500545#####################################################
546
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400547def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500548 return {
Chris Parsons787fb362021-10-14 18:43:51 -0400549 "//command_line_option:platforms": "@//build/bazel/platforms:%s_%s" % (attr.os, attr.arch),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500550 }
551
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400552_config_node_transition = transition(
553 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500554 inputs = [],
555 outputs = [
556 "//command_line_option:platforms",
557 ],
558)
559
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400560def _passthrough_rule_impl(ctx):
561 return [DefaultInfo(files = depset(ctx.files.deps))]
562
563config_node = rule(
564 implementation = _passthrough_rule_impl,
565 attrs = {
566 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400567 "os" : attr.string(mandatory = True),
568 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400569 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
570 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500571)
572
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400573
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500574# Rule representing the root of the build, to depend on all Bazel targets that
575# are required for the build. Building this target will build the entire Bazel
576# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400577mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400578 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500579 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400580 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500581 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400582)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500583
584def _phony_root_impl(ctx):
585 return []
586
587# Rule to depend on other targets but build nothing.
588# This is useful as follows: building a target of this rule will generate
589# symlink forests for all dependencies of the target, without executing any
590# actions of the build.
591phony_root = rule(
592 implementation = _phony_root_impl,
593 attrs = {"deps" : attr.label_list()},
594)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400595`
596 return []byte(contents)
597}
598
599func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500600 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
601 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400602 formatString := `
603# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400604load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
605
606%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400607
608mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400609 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400610)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500611
612phony_root(name = "phonyroot",
613 deps = [":buildroot"],
614)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400615`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400616 configNodeFormatString := `
617config_node(name = "%s",
618 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400619 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400620 deps = [%s],
621)
622`
623
624 configNodesSection := ""
625
Chris Parsons787fb362021-10-14 18:43:51 -0400626 labelsByConfig := map[string][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400627 for val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200628 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400629 configString := getConfigString(val)
630 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400631 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400632
Jingwen Chen1e347862021-09-02 12:11:49 +0000633 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400634 for configString, labels := range labelsByConfig {
635 configTokens := strings.Split(configString, "|")
636 if len(configTokens) != 2 {
637 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000638 }
Chris Parsons787fb362021-10-14 18:43:51 -0400639 archString := configTokens[0]
640 osString := configTokens[1]
641 targetString := fmt.Sprintf("%s_%s", osString, archString)
642 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
643 labelsString := strings.Join(labels, ",\n ")
644 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400645 }
646
Jingwen Chen1e347862021-09-02 12:11:49 +0000647 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400648}
649
Chris Parsons944e7d02021-03-11 11:08:46 -0500650func indent(original string) string {
651 result := ""
652 for _, line := range strings.Split(original, "\n") {
653 result += " " + line + "\n"
654 }
655 return result
656}
657
Chris Parsons808d84c2021-03-09 20:43:32 -0500658// Returns the file contents of the buildroot.cquery file that should be used for the cquery
659// expression in order to obtain information about buildroot and its dependencies.
660// The contents of this file depend on the bazelContext's requests; requests are enumerated
661// and grouped by their request type. The data retrieved for each label depends on its
662// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400663func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400664 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400665 for val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500666 cqueryId := getCqueryId(val)
667 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
668 requestTypeToCqueryIdEntries[val.requestType] =
669 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
670 }
671 labelRegistrationMapSection := ""
672 functionDefSection := ""
673 mainSwitchSection := ""
674
675 mapDeclarationFormatString := `
676%s = {
677 %s
678}
679`
680 functionDefFormatString := `
681def %s(target):
682%s
683`
684 mainSwitchSectionFormatString := `
685 if id_string in %s:
686 return id_string + ">>" + %s(target)
687`
688
Usta Shrestha0b52d832022-02-04 21:37:39 -0500689 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500690 labelMapName := requestType.Name() + "_Labels"
691 functionName := requestType.Name() + "_Fn"
692 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
693 labelMapName,
694 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
695 functionDefSection += fmt.Sprintf(functionDefFormatString,
696 functionName,
697 indent(requestType.StarlarkFunctionBody()))
698 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
699 labelMapName, functionName)
700 }
701
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400702 formatString := `
703# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400704
Usta Shrestha79fccef2022-09-02 18:37:40 -0400705# a drop-in replacement for json.encode(), not available in cquery environment
706# TODO(cparsons): bring json module in and remove this function
707def json_encode(input):
708 # Avoiding recursion by limiting
709 # - a dict to contain anything except a dict
710 # - a list to contain only primitives
711 def encode_primitive(p):
712 t = type(p)
713 if t == "string" or t == "int":
714 return repr(p)
715 fail("unsupported value '%%s' of type '%%s'" %% (p, type(p)))
716
717 def encode_list(list):
718 return "[%%s]" %% ", ".join([encode_primitive(item) for item in list])
719
720 def encode_list_or_primitive(v):
721 return encode_list(v) if type(v) == "list" else encode_primitive(v)
722
723 if type(input) == "dict":
724 # TODO(juu): the result is read line by line so can't use '\n' yet
725 kv_pairs = [("%%s: %%s" %% (encode_primitive(k), encode_list_or_primitive(v))) for (k, v) in input.items()]
726 return "{ %%s }" %% ", ".join(kv_pairs)
727 else:
728 return encode_list_or_primitive(input)
729
Chris Parsons944e7d02021-03-11 11:08:46 -0500730# Label Map Section
731%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500732
Chris Parsons944e7d02021-03-11 11:08:46 -0500733# Function Def Section
734%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500735
736def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400737 # TODO(b/199363072): filegroups and file targets aren't associated with any
738 # specific platform architecture in mixed builds. This is consistent with how
739 # Soong treats filegroups, but it may not be the case with manually-written
740 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500741 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000742 if buildoptions == None:
743 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400744 # any specific platform architecture in mixed builds, so use the host.
745 return "x86_64|linux"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500746 platforms = build_options(target)["//command_line_option:platforms"]
747 if len(platforms) != 1:
748 # An individual configured target should have only one platform architecture.
749 # Note that it's fine for there to be multiple architectures for the same label,
750 # but each is its own configured target.
751 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
752 platform_name = build_options(target)["//command_line_option:platforms"][0].name
753 if platform_name == "host":
754 return "HOST"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400755 elif platform_name.startswith("android_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400756 return platform_name[len("android_"):] + "|" + platform_name[:len("android_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400757 elif platform_name.startswith("linux_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400758 return platform_name[len("linux_"):] + "|" + platform_name[:len("linux_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400759 else:
760 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500761 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500762
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400763def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500764 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500765
Chris Parsons86dc2c22022-09-28 14:58:41 -0400766 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
767 if id_string.startswith("//"):
768 id_string = "@" + id_string
769
Chris Parsons944e7d02021-03-11 11:08:46 -0500770 # Main switch section
771 %s
772 # This target was not requested via cquery, and thus must be a dependency
773 # of a requested target.
774 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400775`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400776
Chris Parsons944e7d02021-03-11 11:08:46 -0500777 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
778 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400779}
780
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200781// Returns a path containing build-related metadata required for interfacing
782// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400783func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200784 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500785}
786
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200787// Returns the path where the contents of the @soong_injection repository live.
788// It is used by Soong to tell Bazel things it cannot over the command line.
789func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200790 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200791}
792
793// Returns the path of the synthetic Bazel workspace that contains a symlink
794// forest composed the whole source tree and BUILD files generated by bp2build.
795func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200796 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200797}
798
Jingwen Chen8c523582021-06-01 11:19:53 +0000799// Returns the path to the top level out dir ($OUT_DIR).
800func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200801 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000802}
803
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400804// Issues commands to Bazel to receive results for all cquery requests
805// queued in the BazelContext.
Yu Liu8d82ac52022-05-17 15:13:28 -0700806func (context *bazelContext) InvokeBazel(config Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400807 context.results = make(map[cqueryKey]string)
808
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400809 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500810
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200811 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200812 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
813 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
814 err = os.MkdirAll(mixedBuildsPath, 0777)
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500815 }
Chris Parsons8ccdb632020-11-17 15:41:01 -0500816 if err != nil {
817 return err
818 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500819 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
820 err = os.MkdirAll(metricsDir, 0777)
821 if err != nil {
822 return err
823 }
824 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700825 if err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200826 return err
827 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700828 if err = ioutil.WriteFile(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400829 return err
830 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700831 if err = ioutil.WriteFile(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400832 return err
833 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200834 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700835 if err = ioutil.WriteFile(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400836 return err
837 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000838
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700839 const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
840 cqueryCmd := bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
841 cqueryOutput, cqueryErr, err := context.issueBazelCommand(context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
842 "--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500843 if err != nil {
Chris Parsons429f5402022-08-11 17:02:41 -0400844 return err
Chris Parsons8d6e4332021-02-22 16:13:50 -0500845 }
Chris Parsons429f5402022-08-11 17:02:41 -0400846 if err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400847 return err
848 }
849
850 cqueryResults := map[string]string{}
851 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
852 if strings.Contains(outputLine, ">>") {
853 splitLine := strings.SplitN(outputLine, ">>", 2)
854 cqueryResults[splitLine[0]] = splitLine[1]
855 }
856 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500857 for val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500858 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -0500859 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400860 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500861 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
862 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400863 }
864 }
865
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500866 // Issue an aquery command to retrieve action information about the bazel build tree.
867 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700868 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
869 // proto sources, which would add a number of unnecessary dependencies.
870 extraFlags := []string{"--output=jsonproto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -0700871 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700872 extraFlags = append(extraFlags, "--collect_code_coverage")
873 paths := make([]string, 0, 2)
874 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
875 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
876 }
877 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
878 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
879 }
880 if len(paths) > 0 {
881 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -0700882 }
883 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700884 aqueryCmd := bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
885 if aqueryOutput, _, err := context.issueBazelCommand(context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
886 extraFlags...); err == nil {
887 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400888 }
Chris Parsons4f069892021-01-15 12:22:41 -0500889 if err != nil {
890 return err
891 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500892
893 // Issue a build command of the phony root to generate symlink forests for dependencies of the
894 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
895 // but some of symlinks may be required to resolve source dependencies of the build.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700896 buildCmd := bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
897 if _, _, err = context.issueBazelCommand(context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd); err != nil {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500898 return err
899 }
900
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400901 // Clear requests.
902 context.requests = map[cqueryKey]bool{}
903 return nil
904}
Chris Parsonsa798d962020-10-12 23:44:08 -0400905
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500906func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
907 return context.buildStatements
908}
909
Chris Parsons1a7aca02022-04-25 22:35:15 -0400910func (context *bazelContext) AqueryDepsets() []bazel.AqueryDepset {
911 return context.depsets
912}
913
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500914func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400915 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500916}
917
Chris Parsonsa798d962020-10-12 23:44:08 -0400918// Singleton used for registering BUILD file ninja dependencies (needed
919// for correctness of builds which use Bazel.
920func BazelSingleton() Singleton {
921 return &bazelSingleton{}
922}
923
924type bazelSingleton struct{}
925
926func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500927 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -0400928 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500929 return
930 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400931
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500932 // Add ninja file dependencies for files which all bazel invocations require.
933 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200934 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500935 ctx.AddNinjaFileDeps(bazelBuildList)
936
937 data, err := ioutil.ReadFile(bazelBuildList)
938 if err != nil {
939 ctx.Errorf(err.Error())
940 }
941 files := strings.Split(strings.TrimSpace(string(data)), "\n")
942 for _, file := range files {
943 ctx.AddNinjaFileDeps(file)
944 }
945
Chris Parsons1a7aca02022-04-25 22:35:15 -0400946 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
947 var outputs []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400948 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
949 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400950 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
951 }
952 for _, artifactPath := range depset.DirectArtifacts {
953 outputs = append(outputs, PathForBazelOut(ctx, artifactPath))
954 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400955 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400956 ctx.Build(pctx, BuildParams{
957 Rule: blueprint.Phony,
958 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
959 Implicits: outputs,
960 })
961 }
962
Usta Shresthaacd5a0c2022-06-22 11:20:50 -0400963 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
964 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500965 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -0700966 if len(buildStatement.Command) > 0 {
967 rule := NewRuleBuilder(pctx, ctx)
968 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
969 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
970 rule.Build(fmt.Sprintf("bazel %d", index), desc)
971 continue
972 }
973 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
974 // and thus require special treatment. If BuildStatement were an interface implementing
975 // buildRule(ctx) function, the code here would just call it.
976 // Unfortunately, the BuildStatement is defined in
977 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
978 // because this would cause circular dependency. So, until we move aquery processing
979 // to the 'android' package, we need to handle special cases here.
980 if buildStatement.Mnemonic == "FileWrite" || buildStatement.Mnemonic == "SourceSymlinkManifest" {
981 // Pass file contents as the value of the rule's "content" argument.
982 // Escape newlines and $ in the contents (the action "writeBazelFile" restores "\\n"
983 // back to the newline, and Ninja reads $$ as $.
984 escaped := strings.ReplaceAll(strings.ReplaceAll(buildStatement.FileContents, "\n", "\\n"),
985 "$", "$$")
986 ctx.Build(pctx, BuildParams{
987 Rule: writeBazelFile,
988 Output: PathForBazelOut(ctx, buildStatement.OutputPaths[0]),
989 Description: fmt.Sprintf("%s %s", buildStatement.Mnemonic, buildStatement.OutputPaths[0]),
990 Args: map[string]string{
991 "content": escaped,
992 },
993 })
Sasha Smundakc180dbd2022-07-03 14:55:58 -0700994 } else if buildStatement.Mnemonic == "SymlinkTree" {
995 // build-runfiles arguments are the manifest file and the target directory
996 // where it creates the symlink tree according to this manifest (and then
997 // writes the MANIFEST file to it).
998 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
999 outManifestPath := outManifest.String()
1000 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1001 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1002 }
1003 outDir := filepath.Dir(outManifestPath)
1004 ctx.Build(pctx, BuildParams{
1005 Rule: buildRunfilesRule,
1006 Output: outManifest,
1007 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1008 Description: "symlink tree for " + outDir,
1009 Args: map[string]string{
1010 "outDir": outDir,
1011 },
1012 })
Sasha Smundak1da064c2022-06-08 16:36:16 -07001013 } else {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001014 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001015 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001016 }
1017}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001018
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001019// Register bazel-owned build statements (obtained from the aquery invocation).
1020func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx PathContext) {
1021 // executionRoot is the action cwd.
1022 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1023
1024 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1025 if len(buildStatement.OutputPaths) > 0 {
1026 cmd.Text("rm -f")
1027 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001028 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001029 }
1030 cmd.Text("&&")
1031 }
1032
1033 for _, pair := range buildStatement.Env {
1034 // Set per-action env variables, if any.
1035 cmd.Flag(pair.Key + "=" + pair.Value)
1036 }
1037
1038 // The actual Bazel action.
1039 cmd.Text(buildStatement.Command)
1040
1041 for _, outputPath := range buildStatement.OutputPaths {
1042 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1043 }
1044 for _, inputPath := range buildStatement.InputPaths {
1045 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1046 }
1047 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1048 otherDepsetName := bazelDepsetName(inputDepsetHash)
1049 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1050 }
1051
1052 if depfile := buildStatement.Depfile; depfile != nil {
1053 // The paths in depfile are relative to `executionRoot`.
1054 // Hence, they need to be corrected by replacing "bazel-out"
1055 // with the full `bazelOutDir`.
1056 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1057 // would be deemed missing.
1058 // (Note: The regexp uses a capture group because the version of sed
1059 // does not support a look-behind pattern.)
1060 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1061 bazelOutDir, *depfile)
1062 cmd.Text(replacement)
1063 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1064 }
1065
1066 for _, symlinkPath := range buildStatement.SymlinkPaths {
1067 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1068 }
1069}
1070
Chris Parsons8d6e4332021-02-22 16:13:50 -05001071func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001072 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001073}
1074
Chris Parsons787fb362021-10-14 18:43:51 -04001075func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001076 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001077 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001078 if key.configKey.osType.Class == Device {
1079 // For the generic Android, the expected result is "target|android", which
1080 // corresponds to the product_variable_config named "android_target" in
1081 // build/bazel/platforms/BUILD.bazel.
1082 arch = "target"
1083 } else {
1084 // Use host platform, which is currently hardcoded to be x86_64.
1085 arch = "x86_64"
1086 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001087 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001088 osName := key.configKey.osType.Name
1089 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" {
Chris Parsons787fb362021-10-14 18:43:51 -04001090 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001091 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001092 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001093 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -04001094}
1095
Chris Parsonsf874e462022-05-10 13:50:12 -04001096func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001097 return configKey{
1098 // use string because Arch is not a valid key in go
1099 arch: ctx.Arch().String(),
1100 osType: ctx.Os(),
1101 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001102}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001103
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001104func bazelDepsetName(contentHash string) string {
1105 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001106}