blob: d87f988691536c9c376c150bc715efcc26963f73 [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 Parsonsad876012022-08-20 14:48:32 -0400346 if !c.IsMixedBuildsEnabled() {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400347 return noopBazelContext{}, nil
348 }
349
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400350 p, err := bazelPathsFromConfig(c)
351 if err != nil {
352 return nil, err
353 }
Chris Parsonsad876012022-08-20 14:48:32 -0400354
355 // TODO(cparsons): Use a different allowlist depending on prod vs. dev
356 // bazel mode.
357 disabledModules := map[string]bool{}
358 // Don't use partially-converted cc_library targets in mixed builds,
359 // since mixed builds would generally rely on both static and shared
360 // variants of a cc_library.
361 for staticOnlyModule, _ := range GetBp2BuildAllowList().ccLibraryStaticOnly {
362 disabledModules[staticOnlyModule] = true
363 }
364 for _, disabledDevModule := range allowlists.MixedBuildsDisabledList {
365 disabledModules[disabledDevModule] = true
366 }
367
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400368 return &bazelContext{
Chris Parsonsad876012022-08-20 14:48:32 -0400369 bazelRunner: &builtinBazelRunner{},
370 paths: p,
371 requests: make(map[cqueryKey]bool),
372 modulesDefaultToBazel: true,
373 bazelDisabledModules: disabledModules,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400374 }, nil
375}
376
377func bazelPathsFromConfig(c *config) (*bazelPaths, error) {
378 p := bazelPaths{
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200379 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400380 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700381 var missingEnvVars []string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400382 if len(c.Getenv("BAZEL_HOME")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400383 p.homeDir = c.Getenv("BAZEL_HOME")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400384 } else {
385 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
386 }
387 if len(c.Getenv("BAZEL_PATH")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400388 p.bazelPath = c.Getenv("BAZEL_PATH")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400389 } else {
390 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
391 }
392 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400393 p.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400394 } else {
395 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
396 }
397 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400398 p.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400399 } else {
400 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
401 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000402 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400403 p.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000404 } else {
405 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
406 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400407 if len(missingEnvVars) > 0 {
408 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
409 } else {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400410 return &p, nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400411 }
412}
413
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400414func (p *bazelPaths) BazelMetricsDir() string {
415 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000416}
417
Chris Parsonsad876012022-08-20 14:48:32 -0400418func (context *bazelContext) BazelAllowlisted(moduleName string) bool {
419 if context.bazelDisabledModules[moduleName] {
420 return false
421 }
422 if context.bazelEnabledModules[moduleName] {
423 return true
424 }
425 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400426}
427
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400428func pwdPrefix() string {
429 // Darwin doesn't have /proc
430 if runtime.GOOS != "darwin" {
431 return "PWD=/proc/self/cwd"
432 }
433 return ""
434}
435
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400436type bazelCommand struct {
437 command string
438 // query or label
439 expression string
440}
441
442type mockBazelRunner struct {
443 bazelCommandResults map[bazelCommand]string
444 commands []bazelCommand
Yu Liu8d82ac52022-05-17 15:13:28 -0700445 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400446}
447
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700448func (r *mockBazelRunner) issueBazelCommand(_ *bazelPaths, _ bazel.RunName,
449 command bazelCommand, extraFlags ...string) (string, string, error) {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400450 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700451 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400452 if ret, ok := r.bazelCommandResults[command]; ok {
453 return ret, "", nil
454 }
455 return "", "", nil
456}
457
458type builtinBazelRunner struct{}
459
Chris Parsons808d84c2021-03-09 20:43:32 -0500460// Issues the given bazel command with given build label and additional flags.
461// Returns (stdout, stderr, error). The first and second return values are strings
462// containing the stdout and stderr of the run command, and an error is returned if
463// the invocation returned an error code.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400464func (r *builtinBazelRunner) issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Chris Parsons808d84c2021-03-09 20:43:32 -0500465 extraFlags ...string) (string, string, error) {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000466 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000467 "--output_base=" + absolutePath(paths.outputBase),
468 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700469 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700470 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700471 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400472
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700473 // Set default platforms to canonicalized values for mixed builds requests.
474 // If these are set in the bazelrc, they will have values that are
475 // non-canonicalized to @sourceroot labels, and thus be invalid when
476 // referenced from the buildroot.
477 //
478 // The actual platform values here may be overridden by configuration
479 // transitions from the buildroot.
480 fmt.Sprintf("--platforms=%s", "//build/bazel/platforms:android_target"),
481 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Jingwen Chen91220d72021-03-24 02:18:33 -0400482
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700483 // This should be parameterized on the host OS, but let's restrict to linux
484 // to keep things simple for now.
485 fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"),
486
487 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
488 "--experimental_repository_disable_download",
489
490 // Suppress noise
491 "--ui_event_filters=-INFO",
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700492 "--noshow_progress"}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400493 cmdFlags = append(cmdFlags, extraFlags...)
494
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400495 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200496 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700497 extraEnv := []string{
498 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200499 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700500 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Jingwen Chen8c523582021-06-01 11:19:53 +0000501 // Make OUT_DIR absolute here so tools/bazel.sh uses the correct
502 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700503 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500504 // Disables local host detection of gcc; toolchain information is defined
505 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700506 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
507 }
508 bazelCmd.Env = append(os.Environ(), extraEnv...)
Colin Crossff0278b2020-10-09 19:24:15 -0700509 stderr := &bytes.Buffer{}
510 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400511
512 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500513 return "", string(stderr.Bytes()),
514 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400515 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500516 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400517 }
518}
519
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400520func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500521 // TODO(cparsons): Define configuration transitions programmatically based
522 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400523 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500524#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400525# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500526#####################################################
527
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400528def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500529 return {
Chris Parsons787fb362021-10-14 18:43:51 -0400530 "//command_line_option:platforms": "@//build/bazel/platforms:%s_%s" % (attr.os, attr.arch),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500531 }
532
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400533_config_node_transition = transition(
534 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500535 inputs = [],
536 outputs = [
537 "//command_line_option:platforms",
538 ],
539)
540
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400541def _passthrough_rule_impl(ctx):
542 return [DefaultInfo(files = depset(ctx.files.deps))]
543
544config_node = rule(
545 implementation = _passthrough_rule_impl,
546 attrs = {
547 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400548 "os" : attr.string(mandatory = True),
549 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400550 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
551 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500552)
553
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400554
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500555# Rule representing the root of the build, to depend on all Bazel targets that
556# are required for the build. Building this target will build the entire Bazel
557# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400558mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400559 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500560 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400561 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500562 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400563)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500564
565def _phony_root_impl(ctx):
566 return []
567
568# Rule to depend on other targets but build nothing.
569# This is useful as follows: building a target of this rule will generate
570# symlink forests for all dependencies of the target, without executing any
571# actions of the build.
572phony_root = rule(
573 implementation = _phony_root_impl,
574 attrs = {"deps" : attr.label_list()},
575)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400576`
577 return []byte(contents)
578}
579
580func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500581 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
582 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400583 formatString := `
584# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400585load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
586
587%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400588
589mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400590 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400591)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500592
593phony_root(name = "phonyroot",
594 deps = [":buildroot"],
595)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400596`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400597 configNodeFormatString := `
598config_node(name = "%s",
599 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400600 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400601 deps = [%s],
602)
603`
604
605 configNodesSection := ""
606
Chris Parsons787fb362021-10-14 18:43:51 -0400607 labelsByConfig := map[string][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400608 for val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200609 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400610 configString := getConfigString(val)
611 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400612 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400613
Jingwen Chen1e347862021-09-02 12:11:49 +0000614 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400615 for configString, labels := range labelsByConfig {
616 configTokens := strings.Split(configString, "|")
617 if len(configTokens) != 2 {
618 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000619 }
Chris Parsons787fb362021-10-14 18:43:51 -0400620 archString := configTokens[0]
621 osString := configTokens[1]
622 targetString := fmt.Sprintf("%s_%s", osString, archString)
623 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
624 labelsString := strings.Join(labels, ",\n ")
625 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400626 }
627
Jingwen Chen1e347862021-09-02 12:11:49 +0000628 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400629}
630
Chris Parsons944e7d02021-03-11 11:08:46 -0500631func indent(original string) string {
632 result := ""
633 for _, line := range strings.Split(original, "\n") {
634 result += " " + line + "\n"
635 }
636 return result
637}
638
Chris Parsons808d84c2021-03-09 20:43:32 -0500639// Returns the file contents of the buildroot.cquery file that should be used for the cquery
640// expression in order to obtain information about buildroot and its dependencies.
641// The contents of this file depend on the bazelContext's requests; requests are enumerated
642// and grouped by their request type. The data retrieved for each label depends on its
643// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400644func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400645 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400646 for val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500647 cqueryId := getCqueryId(val)
648 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
649 requestTypeToCqueryIdEntries[val.requestType] =
650 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
651 }
652 labelRegistrationMapSection := ""
653 functionDefSection := ""
654 mainSwitchSection := ""
655
656 mapDeclarationFormatString := `
657%s = {
658 %s
659}
660`
661 functionDefFormatString := `
662def %s(target):
663%s
664`
665 mainSwitchSectionFormatString := `
666 if id_string in %s:
667 return id_string + ">>" + %s(target)
668`
669
Usta Shrestha0b52d832022-02-04 21:37:39 -0500670 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500671 labelMapName := requestType.Name() + "_Labels"
672 functionName := requestType.Name() + "_Fn"
673 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
674 labelMapName,
675 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
676 functionDefSection += fmt.Sprintf(functionDefFormatString,
677 functionName,
678 indent(requestType.StarlarkFunctionBody()))
679 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
680 labelMapName, functionName)
681 }
682
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400683 formatString := `
684# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400685
Chris Parsons944e7d02021-03-11 11:08:46 -0500686# Label Map Section
687%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500688
Chris Parsons944e7d02021-03-11 11:08:46 -0500689# Function Def Section
690%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500691
692def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400693 # TODO(b/199363072): filegroups and file targets aren't associated with any
694 # specific platform architecture in mixed builds. This is consistent with how
695 # Soong treats filegroups, but it may not be the case with manually-written
696 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500697 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000698 if buildoptions == None:
699 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400700 # any specific platform architecture in mixed builds, so use the host.
701 return "x86_64|linux"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500702 platforms = build_options(target)["//command_line_option:platforms"]
703 if len(platforms) != 1:
704 # An individual configured target should have only one platform architecture.
705 # Note that it's fine for there to be multiple architectures for the same label,
706 # but each is its own configured target.
707 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
708 platform_name = build_options(target)["//command_line_option:platforms"][0].name
709 if platform_name == "host":
710 return "HOST"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400711 elif platform_name.startswith("android_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400712 return platform_name[len("android_"):] + "|" + platform_name[:len("android_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400713 elif platform_name.startswith("linux_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400714 return platform_name[len("linux_"):] + "|" + platform_name[:len("linux_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400715 else:
716 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500717 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500718
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700719def json_for_file(key, file):
720 return '"' + key + '":"' + file.path + '"'
721
722def json_for_files(key, files):
723 return '"' + key + '":[' + ",".join(['"' + f.path + '"' for f in files]) + ']'
724
725def json_for_labels(key, ll):
726 return '"' + key + '":[' + ",".join(['"' + str(x) + '"' for x in ll]) + ']'
727
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400728def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500729 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500730
731 # Main switch section
732 %s
733 # This target was not requested via cquery, and thus must be a dependency
734 # of a requested target.
735 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400736`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400737
Chris Parsons944e7d02021-03-11 11:08:46 -0500738 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
739 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400740}
741
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200742// Returns a path containing build-related metadata required for interfacing
743// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400744func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200745 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500746}
747
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200748// Returns the path where the contents of the @soong_injection repository live.
749// It is used by Soong to tell Bazel things it cannot over the command line.
750func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200751 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200752}
753
754// Returns the path of the synthetic Bazel workspace that contains a symlink
755// forest composed the whole source tree and BUILD files generated by bp2build.
756func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200757 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200758}
759
Jingwen Chen8c523582021-06-01 11:19:53 +0000760// Returns the path to the top level out dir ($OUT_DIR).
761func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200762 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000763}
764
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400765// Issues commands to Bazel to receive results for all cquery requests
766// queued in the BazelContext.
Yu Liu8d82ac52022-05-17 15:13:28 -0700767func (context *bazelContext) InvokeBazel(config Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400768 context.results = make(map[cqueryKey]string)
769
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400770 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500771
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200772 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200773 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
774 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
775 err = os.MkdirAll(mixedBuildsPath, 0777)
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500776 }
Chris Parsons8ccdb632020-11-17 15:41:01 -0500777 if err != nil {
778 return err
779 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500780 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
781 err = os.MkdirAll(metricsDir, 0777)
782 if err != nil {
783 return err
784 }
785 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700786 if err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200787 return err
788 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700789 if err = ioutil.WriteFile(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400790 return err
791 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700792 if err = ioutil.WriteFile(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400793 return err
794 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200795 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700796 if err = ioutil.WriteFile(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400797 return err
798 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000799
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700800 const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
801 cqueryCmd := bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
802 cqueryOutput, cqueryErr, err := context.issueBazelCommand(context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
803 "--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500804 if err != nil {
Chris Parsons429f5402022-08-11 17:02:41 -0400805 return err
Chris Parsons8d6e4332021-02-22 16:13:50 -0500806 }
Chris Parsons429f5402022-08-11 17:02:41 -0400807 if err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400808 return err
809 }
810
811 cqueryResults := map[string]string{}
812 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
813 if strings.Contains(outputLine, ">>") {
814 splitLine := strings.SplitN(outputLine, ">>", 2)
815 cqueryResults[splitLine[0]] = splitLine[1]
816 }
817 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500818 for val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500819 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -0500820 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400821 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500822 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
823 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400824 }
825 }
826
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500827 // Issue an aquery command to retrieve action information about the bazel build tree.
828 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700829 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
830 // proto sources, which would add a number of unnecessary dependencies.
831 extraFlags := []string{"--output=jsonproto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -0700832 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700833 extraFlags = append(extraFlags, "--collect_code_coverage")
834 paths := make([]string, 0, 2)
835 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
836 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
837 }
838 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
839 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
840 }
841 if len(paths) > 0 {
842 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -0700843 }
844 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700845 aqueryCmd := bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
846 if aqueryOutput, _, err := context.issueBazelCommand(context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
847 extraFlags...); err == nil {
848 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400849 }
Chris Parsons4f069892021-01-15 12:22:41 -0500850 if err != nil {
851 return err
852 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500853
854 // Issue a build command of the phony root to generate symlink forests for dependencies of the
855 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
856 // but some of symlinks may be required to resolve source dependencies of the build.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700857 buildCmd := bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
858 if _, _, err = context.issueBazelCommand(context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd); err != nil {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500859 return err
860 }
861
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400862 // Clear requests.
863 context.requests = map[cqueryKey]bool{}
864 return nil
865}
Chris Parsonsa798d962020-10-12 23:44:08 -0400866
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500867func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
868 return context.buildStatements
869}
870
Chris Parsons1a7aca02022-04-25 22:35:15 -0400871func (context *bazelContext) AqueryDepsets() []bazel.AqueryDepset {
872 return context.depsets
873}
874
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500875func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400876 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500877}
878
Chris Parsonsa798d962020-10-12 23:44:08 -0400879// Singleton used for registering BUILD file ninja dependencies (needed
880// for correctness of builds which use Bazel.
881func BazelSingleton() Singleton {
882 return &bazelSingleton{}
883}
884
885type bazelSingleton struct{}
886
887func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500888 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -0400889 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500890 return
891 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400892
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500893 // Add ninja file dependencies for files which all bazel invocations require.
894 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200895 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500896 ctx.AddNinjaFileDeps(bazelBuildList)
897
898 data, err := ioutil.ReadFile(bazelBuildList)
899 if err != nil {
900 ctx.Errorf(err.Error())
901 }
902 files := strings.Split(strings.TrimSpace(string(data)), "\n")
903 for _, file := range files {
904 ctx.AddNinjaFileDeps(file)
905 }
906
Chris Parsons1a7aca02022-04-25 22:35:15 -0400907 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
908 var outputs []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400909 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
910 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400911 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
912 }
913 for _, artifactPath := range depset.DirectArtifacts {
914 outputs = append(outputs, PathForBazelOut(ctx, artifactPath))
915 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400916 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400917 ctx.Build(pctx, BuildParams{
918 Rule: blueprint.Phony,
919 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
920 Implicits: outputs,
921 })
922 }
923
Usta Shresthaacd5a0c2022-06-22 11:20:50 -0400924 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
925 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500926 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -0700927 if len(buildStatement.Command) > 0 {
928 rule := NewRuleBuilder(pctx, ctx)
929 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
930 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
931 rule.Build(fmt.Sprintf("bazel %d", index), desc)
932 continue
933 }
934 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
935 // and thus require special treatment. If BuildStatement were an interface implementing
936 // buildRule(ctx) function, the code here would just call it.
937 // Unfortunately, the BuildStatement is defined in
938 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
939 // because this would cause circular dependency. So, until we move aquery processing
940 // to the 'android' package, we need to handle special cases here.
941 if buildStatement.Mnemonic == "FileWrite" || buildStatement.Mnemonic == "SourceSymlinkManifest" {
942 // Pass file contents as the value of the rule's "content" argument.
943 // Escape newlines and $ in the contents (the action "writeBazelFile" restores "\\n"
944 // back to the newline, and Ninja reads $$ as $.
945 escaped := strings.ReplaceAll(strings.ReplaceAll(buildStatement.FileContents, "\n", "\\n"),
946 "$", "$$")
947 ctx.Build(pctx, BuildParams{
948 Rule: writeBazelFile,
949 Output: PathForBazelOut(ctx, buildStatement.OutputPaths[0]),
950 Description: fmt.Sprintf("%s %s", buildStatement.Mnemonic, buildStatement.OutputPaths[0]),
951 Args: map[string]string{
952 "content": escaped,
953 },
954 })
Sasha Smundakc180dbd2022-07-03 14:55:58 -0700955 } else if buildStatement.Mnemonic == "SymlinkTree" {
956 // build-runfiles arguments are the manifest file and the target directory
957 // where it creates the symlink tree according to this manifest (and then
958 // writes the MANIFEST file to it).
959 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
960 outManifestPath := outManifest.String()
961 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
962 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
963 }
964 outDir := filepath.Dir(outManifestPath)
965 ctx.Build(pctx, BuildParams{
966 Rule: buildRunfilesRule,
967 Output: outManifest,
968 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
969 Description: "symlink tree for " + outDir,
970 Args: map[string]string{
971 "outDir": outDir,
972 },
973 })
Sasha Smundak1da064c2022-06-08 16:36:16 -0700974 } else {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000975 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500976 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400977 }
978}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500979
Usta Shresthaacd5a0c2022-06-22 11:20:50 -0400980// Register bazel-owned build statements (obtained from the aquery invocation).
981func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx PathContext) {
982 // executionRoot is the action cwd.
983 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
984
985 // Remove old outputs, as some actions might not rerun if the outputs are detected.
986 if len(buildStatement.OutputPaths) > 0 {
987 cmd.Text("rm -f")
988 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -0400989 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -0400990 }
991 cmd.Text("&&")
992 }
993
994 for _, pair := range buildStatement.Env {
995 // Set per-action env variables, if any.
996 cmd.Flag(pair.Key + "=" + pair.Value)
997 }
998
999 // The actual Bazel action.
1000 cmd.Text(buildStatement.Command)
1001
1002 for _, outputPath := range buildStatement.OutputPaths {
1003 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1004 }
1005 for _, inputPath := range buildStatement.InputPaths {
1006 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1007 }
1008 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1009 otherDepsetName := bazelDepsetName(inputDepsetHash)
1010 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1011 }
1012
1013 if depfile := buildStatement.Depfile; depfile != nil {
1014 // The paths in depfile are relative to `executionRoot`.
1015 // Hence, they need to be corrected by replacing "bazel-out"
1016 // with the full `bazelOutDir`.
1017 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1018 // would be deemed missing.
1019 // (Note: The regexp uses a capture group because the version of sed
1020 // does not support a look-behind pattern.)
1021 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1022 bazelOutDir, *depfile)
1023 cmd.Text(replacement)
1024 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1025 }
1026
1027 for _, symlinkPath := range buildStatement.SymlinkPaths {
1028 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1029 }
1030}
1031
Chris Parsons8d6e4332021-02-22 16:13:50 -05001032func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001033 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001034}
1035
Chris Parsons787fb362021-10-14 18:43:51 -04001036func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001037 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001038 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001039 if key.configKey.osType.Class == Device {
1040 // For the generic Android, the expected result is "target|android", which
1041 // corresponds to the product_variable_config named "android_target" in
1042 // build/bazel/platforms/BUILD.bazel.
1043 arch = "target"
1044 } else {
1045 // Use host platform, which is currently hardcoded to be x86_64.
1046 arch = "x86_64"
1047 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001048 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001049 osName := key.configKey.osType.Name
1050 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" {
Chris Parsons787fb362021-10-14 18:43:51 -04001051 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001052 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001053 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001054 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -04001055}
1056
Chris Parsonsf874e462022-05-10 13:50:12 -04001057func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001058 return configKey{
1059 // use string because Arch is not a valid key in go
1060 arch: ctx.Arch().String(),
1061 osType: ctx.Os(),
1062 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001063}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001064
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001065func bazelDepsetName(contentHash string) string {
1066 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001067}