blob: 3be9805be7332f3dee108d1a7934d33149bcb2e1 [file] [log] [blame]
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001// Copyright 2020 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package android
16
17import (
18 "bytes"
19 "errors"
20 "fmt"
Chris Parsonsa798d962020-10-12 23:44:08 -040021 "io/ioutil"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040022 "os"
23 "os/exec"
Usta Shresthaacd5a0c2022-06-22 11:20:50 -040024 "path"
Chris Parsonsa798d962020-10-12 23:44:08 -040025 "path/filepath"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040026 "runtime"
27 "strings"
28 "sync"
Chris Parsonsa798d962020-10-12 23:44:08 -040029
Chris Parsons944e7d02021-03-11 11:08:46 -050030 "android/soong/bazel/cquery"
Jingwen Chen1e347862021-09-02 12:11:49 +000031 "android/soong/shared"
Chris Parsons1a7aca02022-04-25 22:35:15 -040032 "github.com/google/blueprint"
Liz Kammer8206d4f2021-03-03 16:40:52 -050033
Patrice Arruda05ab2d02020-12-12 06:24:26 +000034 "android/soong/bazel"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040035)
36
Sasha Smundak1da064c2022-06-08 16:36:16 -070037var (
38 writeBazelFile = pctx.AndroidStaticRule("bazelWriteFileRule", blueprint.RuleParams{
39 Command: `sed "s/\\\\n/\n/g" ${out}.rsp >${out}`,
40 Rspfile: "${out}.rsp",
41 RspfileContent: "${content}",
42 }, "content")
Sasha Smundakc180dbd2022-07-03 14:55:58 -070043 _ = pctx.HostBinToolVariable("bazelBuildRunfilesTool", "build-runfiles")
44 buildRunfilesRule = pctx.AndroidStaticRule("bazelBuildRunfiles", blueprint.RuleParams{
45 Command: "${bazelBuildRunfilesTool} ${in} ${outDir}",
46 Depfile: "",
47 Description: "",
48 CommandDeps: []string{"${bazelBuildRunfilesTool}"},
49 }, "outDir")
Sasha Smundak1da064c2022-06-08 16:36:16 -070050)
51
Chris Parsonsf874e462022-05-10 13:50:12 -040052func init() {
53 RegisterMixedBuildsMutator(InitRegistrationContext)
54}
55
56func RegisterMixedBuildsMutator(ctx RegistrationContext) {
57 ctx.PostDepsMutators(func(ctx RegisterMutatorsContext) {
58 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
59 })
60}
61
62func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
63 if m := ctx.Module(); m.Enabled() {
64 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
65 if mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx) {
66 mixedBuildMod.QueueBazelCall(ctx)
67 }
68 }
69 }
70}
71
Liz Kammerf29df7c2021-04-02 13:37:39 -040072type cqueryRequest interface {
73 // Name returns a string name for this request type. Such request type names must be unique,
74 // and must only consist of alphanumeric characters.
75 Name() string
76
77 // StarlarkFunctionBody returns a starlark function body to process this request type.
78 // The returned string is the body of a Starlark function which obtains
79 // all request-relevant information about a target and returns a string containing
80 // this information.
81 // The function should have the following properties:
82 // - `target` is the only parameter to this function (a configured target).
83 // - The return value must be a string.
84 // - The function body should not be indented outside of its own scope.
85 StarlarkFunctionBody() string
86}
87
Chris Parsons787fb362021-10-14 18:43:51 -040088// Portion of cquery map key to describe target configuration.
89type configKey struct {
Liz Kammer0940b892022-03-18 15:55:04 -040090 arch string
91 osType OsType
Chris Parsons787fb362021-10-14 18:43:51 -040092}
93
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040094// Map key to describe bazel cquery requests.
95type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040096 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -040097 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -040098 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040099}
100
Chris Parsonsf874e462022-05-10 13:50:12 -0400101// BazelContext is a context object useful for interacting with Bazel during
102// the course of a build. Use of Bazel to evaluate part of the build graph
103// is referred to as a "mixed build". (Some modules are managed by Soong,
104// some are managed by Bazel). To facilitate interop between these build
105// subgraphs, Soong may make requests to Bazel and evaluate their responses
106// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400107type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400108 // Add a cquery request to the bazel request queue. All queued requests
109 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
110 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
111
112 // ** Cquery Results Retrieval Functions
113 // The below functions pertain to retrieving cquery results from a prior
114 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400115
116 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400117 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500118
Chris Parsons944e7d02021-03-11 11:08:46 -0500119 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400120 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400121
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000122 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400123 // TODO(b/232976601): Remove.
124 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000125
Chris Parsonsf874e462022-05-10 13:50:12 -0400126 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400127
128 // Issues commands to Bazel to receive results for all cquery requests
129 // queued in the BazelContext.
Yu Liu8d82ac52022-05-17 15:13:28 -0700130 InvokeBazel(config Config) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400131
132 // Returns true if bazel is enabled for the given configuration.
133 BazelEnabled() bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500134
135 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
136 OutputBase() string
137
138 // Returns build statements which should get registered to reflect Bazel's outputs.
139 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400140
141 // Returns the depsets defined in Bazel's aquery response.
142 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400143}
144
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400145type bazelRunner interface {
146 issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) (string, string, error)
147}
148
149type bazelPaths struct {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400150 homeDir string
151 bazelPath string
152 outputBase string
153 workspaceDir string
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200154 soongOutDir string
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000155 metricsDir string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400156}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400157
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400158// A context object which tracks queued requests that need to be made to Bazel,
159// and their results after the requests have been made.
160type bazelContext struct {
161 bazelRunner
162 paths *bazelPaths
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400163 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
164 requestMutex sync.Mutex // requests can be written in parallel
165
166 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500167
168 // Build statements which should get registered to reflect Bazel's outputs.
169 buildStatements []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400170
171 // Depsets which should be used for Bazel's build statements.
172 depsets []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400173}
174
175var _ BazelContext = &bazelContext{}
176
177// A bazel context to use when Bazel is disabled.
178type noopBazelContext struct{}
179
180var _ BazelContext = noopBazelContext{}
181
182// A bazel context to use for tests.
183type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400184 OutputBaseDir string
185
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000186 LabelToOutputFiles map[string][]string
187 LabelToCcInfo map[string]cquery.CcInfo
188 LabelToPythonBinary map[string]string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400189}
190
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700191func (m MockBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400192 panic("unimplemented")
Chris Parsons8d6e4332021-02-22 16:13:50 -0500193}
194
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700195func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400196 result, _ := m.LabelToOutputFiles[label]
197 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400198}
199
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700200func (m MockBazelContext) GetCcInfo(label string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400201 result, _ := m.LabelToCcInfo[label]
202 return result, nil
203}
204
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700205func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400206 result, _ := m.LabelToPythonBinary[label]
207 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000208}
209
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700210func (m MockBazelContext) InvokeBazel(_ Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400211 panic("unimplemented")
212}
213
214func (m MockBazelContext) BazelEnabled() bool {
215 return true
216}
217
Liz Kammera92e8442021-04-07 20:25:21 -0400218func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500219
220func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
221 return []bazel.BuildStatement{}
222}
223
Chris Parsons1a7aca02022-04-25 22:35:15 -0400224func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
225 return []bazel.AqueryDepset{}
226}
227
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400228var _ BazelContext = MockBazelContext{}
229
Chris Parsonsf874e462022-05-10 13:50:12 -0400230func (bazelCtx *bazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
231 key := cqueryKey{label, requestType, cfgKey}
232 bazelCtx.requestMutex.Lock()
233 defer bazelCtx.requestMutex.Unlock()
234 bazelCtx.requests[key] = true
235}
236
237func (bazelCtx *bazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
238 key := cqueryKey{label, cquery.GetOutputFiles, cfgKey}
239 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500240 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400241 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400242 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400243 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400244}
245
Chris Parsonsf874e462022-05-10 13:50:12 -0400246func (bazelCtx *bazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
247 key := cqueryKey{label, cquery.GetCcInfo, cfgKey}
248 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000249 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400250 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000251 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400252 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 +0000253}
254
Chris Parsonsf874e462022-05-10 13:50:12 -0400255func (bazelCtx *bazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
256 key := cqueryKey{label, cquery.GetPythonBinary, cfgKey}
257 if rawString, ok := bazelCtx.results[key]; ok {
258 bazelOutput := strings.TrimSpace(rawString)
259 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
260 }
261 return "", fmt.Errorf("no bazel response found for %v", key)
262}
263
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700264func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500265 panic("unimplemented")
266}
267
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700268func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500269 panic("unimplemented")
270}
271
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700272func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400273 panic("unimplemented")
274}
275
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700276func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000277 panic("unimplemented")
278}
279
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700280func (n noopBazelContext) InvokeBazel(_ Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400281 panic("unimplemented")
282}
283
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500284func (m noopBazelContext) OutputBase() string {
285 return ""
286}
287
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400288func (n noopBazelContext) BazelEnabled() bool {
289 return false
290}
291
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500292func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
293 return []bazel.BuildStatement{}
294}
295
Chris Parsons1a7aca02022-04-25 22:35:15 -0400296func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
297 return []bazel.AqueryDepset{}
298}
299
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400300func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons8b77a002020-10-27 18:59:25 -0400301 // TODO(cparsons): Assess USE_BAZEL=1 instead once "mixed Soong/Bazel builds"
302 // are production ready.
Jingwen Chen442b1a42021-06-17 07:02:15 +0000303 if !c.IsEnvTrue("USE_BAZEL_ANALYSIS") {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400304 return noopBazelContext{}, nil
305 }
306
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400307 p, err := bazelPathsFromConfig(c)
308 if err != nil {
309 return nil, err
310 }
311 return &bazelContext{
312 bazelRunner: &builtinBazelRunner{},
313 paths: p,
314 requests: make(map[cqueryKey]bool),
315 }, nil
316}
317
318func bazelPathsFromConfig(c *config) (*bazelPaths, error) {
319 p := bazelPaths{
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200320 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400321 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700322 var missingEnvVars []string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400323 if len(c.Getenv("BAZEL_HOME")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400324 p.homeDir = c.Getenv("BAZEL_HOME")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400325 } else {
326 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
327 }
328 if len(c.Getenv("BAZEL_PATH")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400329 p.bazelPath = c.Getenv("BAZEL_PATH")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400330 } else {
331 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
332 }
333 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400334 p.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400335 } else {
336 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
337 }
338 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400339 p.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400340 } else {
341 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
342 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000343 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400344 p.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000345 } else {
346 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
347 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400348 if len(missingEnvVars) > 0 {
349 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
350 } else {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400351 return &p, nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400352 }
353}
354
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400355func (p *bazelPaths) BazelMetricsDir() string {
356 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000357}
358
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400359func (context *bazelContext) BazelEnabled() bool {
360 return true
361}
362
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400363func pwdPrefix() string {
364 // Darwin doesn't have /proc
365 if runtime.GOOS != "darwin" {
366 return "PWD=/proc/self/cwd"
367 }
368 return ""
369}
370
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400371type bazelCommand struct {
372 command string
373 // query or label
374 expression string
375}
376
377type mockBazelRunner struct {
378 bazelCommandResults map[bazelCommand]string
379 commands []bazelCommand
Yu Liu8d82ac52022-05-17 15:13:28 -0700380 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400381}
382
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700383func (r *mockBazelRunner) issueBazelCommand(_ *bazelPaths, _ bazel.RunName,
384 command bazelCommand, extraFlags ...string) (string, string, error) {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400385 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700386 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400387 if ret, ok := r.bazelCommandResults[command]; ok {
388 return ret, "", nil
389 }
390 return "", "", nil
391}
392
393type builtinBazelRunner struct{}
394
Chris Parsons808d84c2021-03-09 20:43:32 -0500395// Issues the given bazel command with given build label and additional flags.
396// Returns (stdout, stderr, error). The first and second return values are strings
397// containing the stdout and stderr of the run command, and an error is returned if
398// the invocation returned an error code.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400399func (r *builtinBazelRunner) issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Chris Parsons808d84c2021-03-09 20:43:32 -0500400 extraFlags ...string) (string, string, error) {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000401 cmdFlags := []string{
402 // --noautodetect_server_javabase has the practical consequence of preventing Bazel from
403 // attempting to download rules_java, which is incompatible with
404 // --experimental_repository_disable_download set further below.
405 // rules_java is also not needed until mixed builds start building java targets.
406 // TODO(b/197958133): Once rules_java is pulled into AOSP, remove this flag.
407 "--noautodetect_server_javabase",
408 "--output_base=" + absolutePath(paths.outputBase),
409 command.command,
410 }
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400411 cmdFlags = append(cmdFlags, command.expression)
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700412 cmdFlags = append(cmdFlags,
413 // TODO(asmundak): is it needed in every build?
414 "--profile="+shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400415
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700416 // Set default platforms to canonicalized values for mixed builds requests.
417 // If these are set in the bazelrc, they will have values that are
418 // non-canonicalized to @sourceroot labels, and thus be invalid when
419 // referenced from the buildroot.
420 //
421 // The actual platform values here may be overridden by configuration
422 // transitions from the buildroot.
423 fmt.Sprintf("--platforms=%s", "//build/bazel/platforms:android_target"),
424 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Jingwen Chen91220d72021-03-24 02:18:33 -0400425
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700426 // This should be parameterized on the host OS, but let's restrict to linux
427 // to keep things simple for now.
428 fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"),
429
430 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
431 "--experimental_repository_disable_download",
432
433 // Suppress noise
434 "--ui_event_filters=-INFO",
435 "--noshow_progress")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400436 cmdFlags = append(cmdFlags, extraFlags...)
437
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400438 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200439 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200440 bazelCmd.Env = append(os.Environ(),
441 "HOME="+paths.homeDir,
442 pwdPrefix(),
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200443 "BUILD_DIR="+absolutePath(paths.soongOutDir),
Jingwen Chen8c523582021-06-01 11:19:53 +0000444 // Make OUT_DIR absolute here so tools/bazel.sh uses the correct
445 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
446 "OUT_DIR="+absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500447 // Disables local host detection of gcc; toolchain information is defined
448 // explicitly in BUILD files.
449 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
Colin Crossff0278b2020-10-09 19:24:15 -0700450 stderr := &bytes.Buffer{}
451 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400452
453 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500454 return "", string(stderr.Bytes()),
455 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400456 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500457 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400458 }
459}
460
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400461func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500462 // TODO(cparsons): Define configuration transitions programmatically based
463 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400464 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500465#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400466# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500467#####################################################
468
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400469def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500470 return {
Chris Parsons787fb362021-10-14 18:43:51 -0400471 "//command_line_option:platforms": "@//build/bazel/platforms:%s_%s" % (attr.os, attr.arch),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500472 }
473
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400474_config_node_transition = transition(
475 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500476 inputs = [],
477 outputs = [
478 "//command_line_option:platforms",
479 ],
480)
481
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400482def _passthrough_rule_impl(ctx):
483 return [DefaultInfo(files = depset(ctx.files.deps))]
484
485config_node = rule(
486 implementation = _passthrough_rule_impl,
487 attrs = {
488 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400489 "os" : attr.string(mandatory = True),
490 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400491 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
492 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500493)
494
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400495
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500496# Rule representing the root of the build, to depend on all Bazel targets that
497# are required for the build. Building this target will build the entire Bazel
498# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400499mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400500 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500501 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400502 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500503 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400504)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500505
506def _phony_root_impl(ctx):
507 return []
508
509# Rule to depend on other targets but build nothing.
510# This is useful as follows: building a target of this rule will generate
511# symlink forests for all dependencies of the target, without executing any
512# actions of the build.
513phony_root = rule(
514 implementation = _phony_root_impl,
515 attrs = {"deps" : attr.label_list()},
516)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400517`
518 return []byte(contents)
519}
520
521func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500522 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
523 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400524 formatString := `
525# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400526load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
527
528%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400529
530mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400531 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400532)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500533
534phony_root(name = "phonyroot",
535 deps = [":buildroot"],
536)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400537`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400538 configNodeFormatString := `
539config_node(name = "%s",
540 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400541 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400542 deps = [%s],
543)
544`
545
546 configNodesSection := ""
547
Chris Parsons787fb362021-10-14 18:43:51 -0400548 labelsByConfig := map[string][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400549 for val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200550 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400551 configString := getConfigString(val)
552 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400553 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400554
Jingwen Chen1e347862021-09-02 12:11:49 +0000555 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400556 for configString, labels := range labelsByConfig {
557 configTokens := strings.Split(configString, "|")
558 if len(configTokens) != 2 {
559 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000560 }
Chris Parsons787fb362021-10-14 18:43:51 -0400561 archString := configTokens[0]
562 osString := configTokens[1]
563 targetString := fmt.Sprintf("%s_%s", osString, archString)
564 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
565 labelsString := strings.Join(labels, ",\n ")
566 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400567 }
568
Jingwen Chen1e347862021-09-02 12:11:49 +0000569 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400570}
571
Chris Parsons944e7d02021-03-11 11:08:46 -0500572func indent(original string) string {
573 result := ""
574 for _, line := range strings.Split(original, "\n") {
575 result += " " + line + "\n"
576 }
577 return result
578}
579
Chris Parsons808d84c2021-03-09 20:43:32 -0500580// Returns the file contents of the buildroot.cquery file that should be used for the cquery
581// expression in order to obtain information about buildroot and its dependencies.
582// The contents of this file depend on the bazelContext's requests; requests are enumerated
583// and grouped by their request type. The data retrieved for each label depends on its
584// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400585func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400586 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400587 for val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500588 cqueryId := getCqueryId(val)
589 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
590 requestTypeToCqueryIdEntries[val.requestType] =
591 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
592 }
593 labelRegistrationMapSection := ""
594 functionDefSection := ""
595 mainSwitchSection := ""
596
597 mapDeclarationFormatString := `
598%s = {
599 %s
600}
601`
602 functionDefFormatString := `
603def %s(target):
604%s
605`
606 mainSwitchSectionFormatString := `
607 if id_string in %s:
608 return id_string + ">>" + %s(target)
609`
610
Usta Shrestha0b52d832022-02-04 21:37:39 -0500611 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500612 labelMapName := requestType.Name() + "_Labels"
613 functionName := requestType.Name() + "_Fn"
614 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
615 labelMapName,
616 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
617 functionDefSection += fmt.Sprintf(functionDefFormatString,
618 functionName,
619 indent(requestType.StarlarkFunctionBody()))
620 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
621 labelMapName, functionName)
622 }
623
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400624 formatString := `
625# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400626
Chris Parsons944e7d02021-03-11 11:08:46 -0500627# Label Map Section
628%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500629
Chris Parsons944e7d02021-03-11 11:08:46 -0500630# Function Def Section
631%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500632
633def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400634 # TODO(b/199363072): filegroups and file targets aren't associated with any
635 # specific platform architecture in mixed builds. This is consistent with how
636 # Soong treats filegroups, but it may not be the case with manually-written
637 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500638 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000639 if buildoptions == None:
640 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400641 # any specific platform architecture in mixed builds, so use the host.
642 return "x86_64|linux"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500643 platforms = build_options(target)["//command_line_option:platforms"]
644 if len(platforms) != 1:
645 # An individual configured target should have only one platform architecture.
646 # Note that it's fine for there to be multiple architectures for the same label,
647 # but each is its own configured target.
648 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
649 platform_name = build_options(target)["//command_line_option:platforms"][0].name
650 if platform_name == "host":
651 return "HOST"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400652 elif platform_name.startswith("android_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400653 return platform_name[len("android_"):] + "|" + platform_name[:len("android_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400654 elif platform_name.startswith("linux_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400655 return platform_name[len("linux_"):] + "|" + platform_name[:len("linux_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400656 else:
657 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500658 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500659
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400660def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500661 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500662
663 # Main switch section
664 %s
665 # This target was not requested via cquery, and thus must be a dependency
666 # of a requested target.
667 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400668`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400669
Chris Parsons944e7d02021-03-11 11:08:46 -0500670 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
671 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400672}
673
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200674// Returns a path containing build-related metadata required for interfacing
675// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400676func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200677 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500678}
679
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200680// Returns the path where the contents of the @soong_injection repository live.
681// It is used by Soong to tell Bazel things it cannot over the command line.
682func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200683 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200684}
685
686// Returns the path of the synthetic Bazel workspace that contains a symlink
687// forest composed the whole source tree and BUILD files generated by bp2build.
688func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200689 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200690}
691
Jingwen Chen8c523582021-06-01 11:19:53 +0000692// Returns the path to the top level out dir ($OUT_DIR).
693func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200694 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000695}
696
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400697// Issues commands to Bazel to receive results for all cquery requests
698// queued in the BazelContext.
Yu Liu8d82ac52022-05-17 15:13:28 -0700699func (context *bazelContext) InvokeBazel(config Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400700 context.results = make(map[cqueryKey]string)
701
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400702 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500703
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200704 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200705 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
706 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
707 err = os.MkdirAll(mixedBuildsPath, 0777)
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500708 }
Chris Parsons8ccdb632020-11-17 15:41:01 -0500709 if err != nil {
710 return err
711 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500712 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
713 err = os.MkdirAll(metricsDir, 0777)
714 if err != nil {
715 return err
716 }
717 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700718 if err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200719 return err
720 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700721 if err = ioutil.WriteFile(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400722 return err
723 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700724 if err = ioutil.WriteFile(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400725 return err
726 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200727 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700728 if err = ioutil.WriteFile(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400729 return err
730 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000731
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700732 const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
733 cqueryCmd := bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
734 cqueryOutput, cqueryErr, err := context.issueBazelCommand(context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
735 "--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500736 if err != nil {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700737 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryOutput), 0666)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500738 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400739 if err != nil {
740 return err
741 }
742
743 cqueryResults := map[string]string{}
744 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
745 if strings.Contains(outputLine, ">>") {
746 splitLine := strings.SplitN(outputLine, ">>", 2)
747 cqueryResults[splitLine[0]] = splitLine[1]
748 }
749 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500750 for val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500751 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -0500752 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400753 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500754 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
755 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400756 }
757 }
758
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500759 // Issue an aquery command to retrieve action information about the bazel build tree.
760 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700761 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
762 // proto sources, which would add a number of unnecessary dependencies.
763 extraFlags := []string{"--output=jsonproto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -0700764 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700765 extraFlags = append(extraFlags, "--collect_code_coverage")
766 paths := make([]string, 0, 2)
767 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
768 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
769 }
770 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
771 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
772 }
773 if len(paths) > 0 {
774 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -0700775 }
776 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700777 aqueryCmd := bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
778 if aqueryOutput, _, err := context.issueBazelCommand(context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
779 extraFlags...); err == nil {
780 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400781 }
Chris Parsons4f069892021-01-15 12:22:41 -0500782 if err != nil {
783 return err
784 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500785
786 // Issue a build command of the phony root to generate symlink forests for dependencies of the
787 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
788 // but some of symlinks may be required to resolve source dependencies of the build.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700789 buildCmd := bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
790 if _, _, err = context.issueBazelCommand(context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd); err != nil {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500791 return err
792 }
793
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400794 // Clear requests.
795 context.requests = map[cqueryKey]bool{}
796 return nil
797}
Chris Parsonsa798d962020-10-12 23:44:08 -0400798
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500799func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
800 return context.buildStatements
801}
802
Chris Parsons1a7aca02022-04-25 22:35:15 -0400803func (context *bazelContext) AqueryDepsets() []bazel.AqueryDepset {
804 return context.depsets
805}
806
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500807func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400808 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500809}
810
Chris Parsonsa798d962020-10-12 23:44:08 -0400811// Singleton used for registering BUILD file ninja dependencies (needed
812// for correctness of builds which use Bazel.
813func BazelSingleton() Singleton {
814 return &bazelSingleton{}
815}
816
817type bazelSingleton struct{}
818
819func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500820 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
821 if !ctx.Config().BazelContext.BazelEnabled() {
822 return
823 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400824
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500825 // Add ninja file dependencies for files which all bazel invocations require.
826 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200827 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500828 ctx.AddNinjaFileDeps(bazelBuildList)
829
830 data, err := ioutil.ReadFile(bazelBuildList)
831 if err != nil {
832 ctx.Errorf(err.Error())
833 }
834 files := strings.Split(strings.TrimSpace(string(data)), "\n")
835 for _, file := range files {
836 ctx.AddNinjaFileDeps(file)
837 }
838
Chris Parsons1a7aca02022-04-25 22:35:15 -0400839 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
840 var outputs []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400841 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
842 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400843 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
844 }
845 for _, artifactPath := range depset.DirectArtifacts {
846 outputs = append(outputs, PathForBazelOut(ctx, artifactPath))
847 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400848 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400849 ctx.Build(pctx, BuildParams{
850 Rule: blueprint.Phony,
851 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
852 Implicits: outputs,
853 })
854 }
855
Usta Shresthaacd5a0c2022-06-22 11:20:50 -0400856 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
857 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500858 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -0700859 if len(buildStatement.Command) > 0 {
860 rule := NewRuleBuilder(pctx, ctx)
861 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
862 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
863 rule.Build(fmt.Sprintf("bazel %d", index), desc)
864 continue
865 }
866 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
867 // and thus require special treatment. If BuildStatement were an interface implementing
868 // buildRule(ctx) function, the code here would just call it.
869 // Unfortunately, the BuildStatement is defined in
870 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
871 // because this would cause circular dependency. So, until we move aquery processing
872 // to the 'android' package, we need to handle special cases here.
873 if buildStatement.Mnemonic == "FileWrite" || buildStatement.Mnemonic == "SourceSymlinkManifest" {
874 // Pass file contents as the value of the rule's "content" argument.
875 // Escape newlines and $ in the contents (the action "writeBazelFile" restores "\\n"
876 // back to the newline, and Ninja reads $$ as $.
877 escaped := strings.ReplaceAll(strings.ReplaceAll(buildStatement.FileContents, "\n", "\\n"),
878 "$", "$$")
879 ctx.Build(pctx, BuildParams{
880 Rule: writeBazelFile,
881 Output: PathForBazelOut(ctx, buildStatement.OutputPaths[0]),
882 Description: fmt.Sprintf("%s %s", buildStatement.Mnemonic, buildStatement.OutputPaths[0]),
883 Args: map[string]string{
884 "content": escaped,
885 },
886 })
Sasha Smundakc180dbd2022-07-03 14:55:58 -0700887 } else if buildStatement.Mnemonic == "SymlinkTree" {
888 // build-runfiles arguments are the manifest file and the target directory
889 // where it creates the symlink tree according to this manifest (and then
890 // writes the MANIFEST file to it).
891 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
892 outManifestPath := outManifest.String()
893 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
894 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
895 }
896 outDir := filepath.Dir(outManifestPath)
897 ctx.Build(pctx, BuildParams{
898 Rule: buildRunfilesRule,
899 Output: outManifest,
900 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
901 Description: "symlink tree for " + outDir,
902 Args: map[string]string{
903 "outDir": outDir,
904 },
905 })
Sasha Smundak1da064c2022-06-08 16:36:16 -0700906 } else {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000907 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500908 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400909 }
910}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500911
Usta Shresthaacd5a0c2022-06-22 11:20:50 -0400912// Register bazel-owned build statements (obtained from the aquery invocation).
913func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx PathContext) {
914 // executionRoot is the action cwd.
915 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
916
917 // Remove old outputs, as some actions might not rerun if the outputs are detected.
918 if len(buildStatement.OutputPaths) > 0 {
919 cmd.Text("rm -f")
920 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -0400921 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -0400922 }
923 cmd.Text("&&")
924 }
925
926 for _, pair := range buildStatement.Env {
927 // Set per-action env variables, if any.
928 cmd.Flag(pair.Key + "=" + pair.Value)
929 }
930
931 // The actual Bazel action.
932 cmd.Text(buildStatement.Command)
933
934 for _, outputPath := range buildStatement.OutputPaths {
935 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
936 }
937 for _, inputPath := range buildStatement.InputPaths {
938 cmd.Implicit(PathForBazelOut(ctx, inputPath))
939 }
940 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
941 otherDepsetName := bazelDepsetName(inputDepsetHash)
942 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
943 }
944
945 if depfile := buildStatement.Depfile; depfile != nil {
946 // The paths in depfile are relative to `executionRoot`.
947 // Hence, they need to be corrected by replacing "bazel-out"
948 // with the full `bazelOutDir`.
949 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
950 // would be deemed missing.
951 // (Note: The regexp uses a capture group because the version of sed
952 // does not support a look-behind pattern.)
953 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
954 bazelOutDir, *depfile)
955 cmd.Text(replacement)
956 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
957 }
958
959 for _, symlinkPath := range buildStatement.SymlinkPaths {
960 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
961 }
962}
963
Chris Parsons8d6e4332021-02-22 16:13:50 -0500964func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -0400965 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500966}
967
Chris Parsons787fb362021-10-14 18:43:51 -0400968func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -0400969 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -0400970 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -0700971 if key.configKey.osType.Class == Device {
972 // For the generic Android, the expected result is "target|android", which
973 // corresponds to the product_variable_config named "android_target" in
974 // build/bazel/platforms/BUILD.bazel.
975 arch = "target"
976 } else {
977 // Use host platform, which is currently hardcoded to be x86_64.
978 arch = "x86_64"
979 }
Chris Parsons8d6e4332021-02-22 16:13:50 -0500980 }
Usta Shrestha16ac1352022-06-22 11:01:55 -0400981 osName := key.configKey.osType.Name
982 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" {
Chris Parsons787fb362021-10-14 18:43:51 -0400983 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -0400984 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -0400985 }
Usta Shrestha16ac1352022-06-22 11:01:55 -0400986 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -0400987}
988
Chris Parsonsf874e462022-05-10 13:50:12 -0400989func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -0400990 return configKey{
991 // use string because Arch is not a valid key in go
992 arch: ctx.Arch().String(),
993 osType: ctx.Os(),
994 }
Chris Parsons8d6e4332021-02-22 16:13:50 -0500995}
Chris Parsons1a7aca02022-04-25 22:35:15 -0400996
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400997func bazelDepsetName(contentHash string) string {
998 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400999}