blob: eff03176d2ca15480cfdd8ab8d7983074437d749 [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")
43)
44
Chris Parsonsf874e462022-05-10 13:50:12 -040045func init() {
46 RegisterMixedBuildsMutator(InitRegistrationContext)
47}
48
49func RegisterMixedBuildsMutator(ctx RegistrationContext) {
50 ctx.PostDepsMutators(func(ctx RegisterMutatorsContext) {
51 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
52 })
53}
54
55func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
56 if m := ctx.Module(); m.Enabled() {
57 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
58 if mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx) {
59 mixedBuildMod.QueueBazelCall(ctx)
60 }
61 }
62 }
63}
64
Liz Kammerf29df7c2021-04-02 13:37:39 -040065type cqueryRequest interface {
66 // Name returns a string name for this request type. Such request type names must be unique,
67 // and must only consist of alphanumeric characters.
68 Name() string
69
70 // StarlarkFunctionBody returns a starlark function body to process this request type.
71 // The returned string is the body of a Starlark function which obtains
72 // all request-relevant information about a target and returns a string containing
73 // this information.
74 // The function should have the following properties:
75 // - `target` is the only parameter to this function (a configured target).
76 // - The return value must be a string.
77 // - The function body should not be indented outside of its own scope.
78 StarlarkFunctionBody() string
79}
80
Chris Parsons787fb362021-10-14 18:43:51 -040081// Portion of cquery map key to describe target configuration.
82type configKey struct {
Liz Kammer0940b892022-03-18 15:55:04 -040083 arch string
84 osType OsType
Chris Parsons787fb362021-10-14 18:43:51 -040085}
86
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040087// Map key to describe bazel cquery requests.
88type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040089 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -040090 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -040091 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040092}
93
Chris Parsonsf874e462022-05-10 13:50:12 -040094// BazelContext is a context object useful for interacting with Bazel during
95// the course of a build. Use of Bazel to evaluate part of the build graph
96// is referred to as a "mixed build". (Some modules are managed by Soong,
97// some are managed by Bazel). To facilitate interop between these build
98// subgraphs, Soong may make requests to Bazel and evaluate their responses
99// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400100type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400101 // Add a cquery request to the bazel request queue. All queued requests
102 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
103 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
104
105 // ** Cquery Results Retrieval Functions
106 // The below functions pertain to retrieving cquery results from a prior
107 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400108
109 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400110 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500111
Chris Parsons944e7d02021-03-11 11:08:46 -0500112 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400113 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400114
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000115 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400116 // TODO(b/232976601): Remove.
117 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000118
Chris Parsonsf874e462022-05-10 13:50:12 -0400119 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400120
121 // Issues commands to Bazel to receive results for all cquery requests
122 // queued in the BazelContext.
Yu Liu8d82ac52022-05-17 15:13:28 -0700123 InvokeBazel(config Config) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400124
125 // Returns true if bazel is enabled for the given configuration.
126 BazelEnabled() bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500127
128 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
129 OutputBase() string
130
131 // Returns build statements which should get registered to reflect Bazel's outputs.
132 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400133
134 // Returns the depsets defined in Bazel's aquery response.
135 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400136}
137
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400138type bazelRunner interface {
139 issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) (string, string, error)
140}
141
142type bazelPaths struct {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400143 homeDir string
144 bazelPath string
145 outputBase string
146 workspaceDir string
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200147 soongOutDir string
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000148 metricsDir string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400149}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400150
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400151// A context object which tracks queued requests that need to be made to Bazel,
152// and their results after the requests have been made.
153type bazelContext struct {
154 bazelRunner
155 paths *bazelPaths
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400156 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
157 requestMutex sync.Mutex // requests can be written in parallel
158
159 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500160
161 // Build statements which should get registered to reflect Bazel's outputs.
162 buildStatements []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400163
164 // Depsets which should be used for Bazel's build statements.
165 depsets []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400166}
167
168var _ BazelContext = &bazelContext{}
169
170// A bazel context to use when Bazel is disabled.
171type noopBazelContext struct{}
172
173var _ BazelContext = noopBazelContext{}
174
175// A bazel context to use for tests.
176type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400177 OutputBaseDir string
178
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000179 LabelToOutputFiles map[string][]string
180 LabelToCcInfo map[string]cquery.CcInfo
181 LabelToPythonBinary map[string]string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400182}
183
Chris Parsonsf874e462022-05-10 13:50:12 -0400184func (m MockBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
185 panic("unimplemented")
Chris Parsons8d6e4332021-02-22 16:13:50 -0500186}
187
Chris Parsonsf874e462022-05-10 13:50:12 -0400188func (m MockBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
189 result, _ := m.LabelToOutputFiles[label]
190 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400191}
192
Chris Parsonsf874e462022-05-10 13:50:12 -0400193func (m MockBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
194 result, _ := m.LabelToCcInfo[label]
195 return result, nil
196}
197
198func (m MockBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
199 result, _ := m.LabelToPythonBinary[label]
200 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000201}
202
Yu Liu8d82ac52022-05-17 15:13:28 -0700203func (m MockBazelContext) InvokeBazel(config Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400204 panic("unimplemented")
205}
206
207func (m MockBazelContext) BazelEnabled() bool {
208 return true
209}
210
Liz Kammera92e8442021-04-07 20:25:21 -0400211func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500212
213func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
214 return []bazel.BuildStatement{}
215}
216
Chris Parsons1a7aca02022-04-25 22:35:15 -0400217func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
218 return []bazel.AqueryDepset{}
219}
220
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400221var _ BazelContext = MockBazelContext{}
222
Chris Parsonsf874e462022-05-10 13:50:12 -0400223func (bazelCtx *bazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
224 key := cqueryKey{label, requestType, cfgKey}
225 bazelCtx.requestMutex.Lock()
226 defer bazelCtx.requestMutex.Unlock()
227 bazelCtx.requests[key] = true
228}
229
230func (bazelCtx *bazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
231 key := cqueryKey{label, cquery.GetOutputFiles, cfgKey}
232 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500233 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400234 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400235 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400236 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400237}
238
Chris Parsonsf874e462022-05-10 13:50:12 -0400239func (bazelCtx *bazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
240 key := cqueryKey{label, cquery.GetCcInfo, cfgKey}
241 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000242 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400243 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000244 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400245 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 +0000246}
247
Chris Parsonsf874e462022-05-10 13:50:12 -0400248func (bazelCtx *bazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
249 key := cqueryKey{label, cquery.GetPythonBinary, cfgKey}
250 if rawString, ok := bazelCtx.results[key]; ok {
251 bazelOutput := strings.TrimSpace(rawString)
252 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
253 }
254 return "", fmt.Errorf("no bazel response found for %v", key)
255}
256
257func (n noopBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500258 panic("unimplemented")
259}
260
Chris Parsonsf874e462022-05-10 13:50:12 -0400261func (n noopBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500262 panic("unimplemented")
263}
264
Chris Parsonsf874e462022-05-10 13:50:12 -0400265func (n noopBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
266 panic("unimplemented")
267}
268
269func (n noopBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000270 panic("unimplemented")
271}
272
Yu Liu8d82ac52022-05-17 15:13:28 -0700273func (n noopBazelContext) InvokeBazel(config Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400274 panic("unimplemented")
275}
276
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500277func (m noopBazelContext) OutputBase() string {
278 return ""
279}
280
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400281func (n noopBazelContext) BazelEnabled() bool {
282 return false
283}
284
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500285func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
286 return []bazel.BuildStatement{}
287}
288
Chris Parsons1a7aca02022-04-25 22:35:15 -0400289func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
290 return []bazel.AqueryDepset{}
291}
292
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400293func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons8b77a002020-10-27 18:59:25 -0400294 // TODO(cparsons): Assess USE_BAZEL=1 instead once "mixed Soong/Bazel builds"
295 // are production ready.
Jingwen Chen442b1a42021-06-17 07:02:15 +0000296 if !c.IsEnvTrue("USE_BAZEL_ANALYSIS") {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400297 return noopBazelContext{}, nil
298 }
299
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400300 p, err := bazelPathsFromConfig(c)
301 if err != nil {
302 return nil, err
303 }
304 return &bazelContext{
305 bazelRunner: &builtinBazelRunner{},
306 paths: p,
307 requests: make(map[cqueryKey]bool),
308 }, nil
309}
310
311func bazelPathsFromConfig(c *config) (*bazelPaths, error) {
312 p := bazelPaths{
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200313 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400314 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400315 missingEnvVars := []string{}
316 if len(c.Getenv("BAZEL_HOME")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400317 p.homeDir = c.Getenv("BAZEL_HOME")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400318 } else {
319 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
320 }
321 if len(c.Getenv("BAZEL_PATH")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400322 p.bazelPath = c.Getenv("BAZEL_PATH")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400323 } else {
324 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
325 }
326 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400327 p.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400328 } else {
329 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
330 }
331 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400332 p.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400333 } else {
334 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
335 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000336 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400337 p.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000338 } else {
339 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
340 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400341 if len(missingEnvVars) > 0 {
342 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
343 } else {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400344 return &p, nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400345 }
346}
347
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400348func (p *bazelPaths) BazelMetricsDir() string {
349 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000350}
351
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400352func (context *bazelContext) BazelEnabled() bool {
353 return true
354}
355
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400356func pwdPrefix() string {
357 // Darwin doesn't have /proc
358 if runtime.GOOS != "darwin" {
359 return "PWD=/proc/self/cwd"
360 }
361 return ""
362}
363
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400364type bazelCommand struct {
365 command string
366 // query or label
367 expression string
368}
369
370type mockBazelRunner struct {
371 bazelCommandResults map[bazelCommand]string
372 commands []bazelCommand
Yu Liu8d82ac52022-05-17 15:13:28 -0700373 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400374}
375
376func (r *mockBazelRunner) issueBazelCommand(paths *bazelPaths,
377 runName bazel.RunName,
378 command bazelCommand,
379 extraFlags ...string) (string, string, error) {
380 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700381 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400382 if ret, ok := r.bazelCommandResults[command]; ok {
383 return ret, "", nil
384 }
385 return "", "", nil
386}
387
388type builtinBazelRunner struct{}
389
Chris Parsons808d84c2021-03-09 20:43:32 -0500390// Issues the given bazel command with given build label and additional flags.
391// Returns (stdout, stderr, error). The first and second return values are strings
392// containing the stdout and stderr of the run command, and an error is returned if
393// the invocation returned an error code.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400394func (r *builtinBazelRunner) issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Chris Parsons808d84c2021-03-09 20:43:32 -0500395 extraFlags ...string) (string, string, error) {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000396 cmdFlags := []string{
397 // --noautodetect_server_javabase has the practical consequence of preventing Bazel from
398 // attempting to download rules_java, which is incompatible with
399 // --experimental_repository_disable_download set further below.
400 // rules_java is also not needed until mixed builds start building java targets.
401 // TODO(b/197958133): Once rules_java is pulled into AOSP, remove this flag.
402 "--noautodetect_server_javabase",
403 "--output_base=" + absolutePath(paths.outputBase),
404 command.command,
405 }
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400406 cmdFlags = append(cmdFlags, command.expression)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400407 cmdFlags = append(cmdFlags, "--profile="+shared.BazelMetricsFilename(paths, runName))
Jingwen Chen91220d72021-03-24 02:18:33 -0400408
409 // Set default platforms to canonicalized values for mixed builds requests.
410 // If these are set in the bazelrc, they will have values that are
411 // non-canonicalized to @sourceroot labels, and thus be invalid when
412 // referenced from the buildroot.
413 //
414 // The actual platform values here may be overridden by configuration
415 // transitions from the buildroot.
Chris Parsonsee423b02021-02-08 23:04:59 -0500416 cmdFlags = append(cmdFlags,
Liz Kammerc0c66092021-07-26 17:38:47 -0400417 fmt.Sprintf("--platforms=%s", "//build/bazel/platforms:android_target"))
Chris Parsonsee423b02021-02-08 23:04:59 -0500418 cmdFlags = append(cmdFlags,
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200419 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"))
Jingwen Chen91220d72021-03-24 02:18:33 -0400420 // This should be parameterized on the host OS, but let's restrict to linux
421 // to keep things simple for now.
422 cmdFlags = append(cmdFlags,
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200423 fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"))
Jingwen Chen91220d72021-03-24 02:18:33 -0400424
Chris Parsons8d6e4332021-02-22 16:13:50 -0500425 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
426 cmdFlags = append(cmdFlags, "--experimental_repository_disable_download")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400427 cmdFlags = append(cmdFlags, extraFlags...)
428
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400429 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200430 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200431 bazelCmd.Env = append(os.Environ(),
432 "HOME="+paths.homeDir,
433 pwdPrefix(),
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200434 "BUILD_DIR="+absolutePath(paths.soongOutDir),
Jingwen Chen8c523582021-06-01 11:19:53 +0000435 // Make OUT_DIR absolute here so tools/bazel.sh uses the correct
436 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
437 "OUT_DIR="+absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500438 // Disables local host detection of gcc; toolchain information is defined
439 // explicitly in BUILD files.
440 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
Colin Crossff0278b2020-10-09 19:24:15 -0700441 stderr := &bytes.Buffer{}
442 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400443
444 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500445 return "", string(stderr.Bytes()),
446 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400447 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500448 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400449 }
450}
451
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400452func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500453 // TODO(cparsons): Define configuration transitions programmatically based
454 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400455 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500456#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400457# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500458#####################################################
459
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400460def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500461 return {
Chris Parsons787fb362021-10-14 18:43:51 -0400462 "//command_line_option:platforms": "@//build/bazel/platforms:%s_%s" % (attr.os, attr.arch),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500463 }
464
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400465_config_node_transition = transition(
466 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500467 inputs = [],
468 outputs = [
469 "//command_line_option:platforms",
470 ],
471)
472
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400473def _passthrough_rule_impl(ctx):
474 return [DefaultInfo(files = depset(ctx.files.deps))]
475
476config_node = rule(
477 implementation = _passthrough_rule_impl,
478 attrs = {
479 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400480 "os" : attr.string(mandatory = True),
481 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400482 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
483 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500484)
485
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400486
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500487# Rule representing the root of the build, to depend on all Bazel targets that
488# are required for the build. Building this target will build the entire Bazel
489# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400490mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400491 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500492 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400493 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500494 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400495)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500496
497def _phony_root_impl(ctx):
498 return []
499
500# Rule to depend on other targets but build nothing.
501# This is useful as follows: building a target of this rule will generate
502# symlink forests for all dependencies of the target, without executing any
503# actions of the build.
504phony_root = rule(
505 implementation = _phony_root_impl,
506 attrs = {"deps" : attr.label_list()},
507)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400508`
509 return []byte(contents)
510}
511
512func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500513 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
514 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400515 formatString := `
516# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400517load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
518
519%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400520
521mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400522 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400523)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500524
525phony_root(name = "phonyroot",
526 deps = [":buildroot"],
527)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400528`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400529 configNodeFormatString := `
530config_node(name = "%s",
531 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400532 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400533 deps = [%s],
534)
535`
536
537 configNodesSection := ""
538
Chris Parsons787fb362021-10-14 18:43:51 -0400539 labelsByConfig := map[string][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400540 for val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200541 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400542 configString := getConfigString(val)
543 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400544 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400545
Jingwen Chen1e347862021-09-02 12:11:49 +0000546 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400547 for configString, labels := range labelsByConfig {
548 configTokens := strings.Split(configString, "|")
549 if len(configTokens) != 2 {
550 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000551 }
Chris Parsons787fb362021-10-14 18:43:51 -0400552 archString := configTokens[0]
553 osString := configTokens[1]
554 targetString := fmt.Sprintf("%s_%s", osString, archString)
555 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
556 labelsString := strings.Join(labels, ",\n ")
557 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400558 }
559
Jingwen Chen1e347862021-09-02 12:11:49 +0000560 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400561}
562
Chris Parsons944e7d02021-03-11 11:08:46 -0500563func indent(original string) string {
564 result := ""
565 for _, line := range strings.Split(original, "\n") {
566 result += " " + line + "\n"
567 }
568 return result
569}
570
Chris Parsons808d84c2021-03-09 20:43:32 -0500571// Returns the file contents of the buildroot.cquery file that should be used for the cquery
572// expression in order to obtain information about buildroot and its dependencies.
573// The contents of this file depend on the bazelContext's requests; requests are enumerated
574// and grouped by their request type. The data retrieved for each label depends on its
575// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400576func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400577 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400578 for val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500579 cqueryId := getCqueryId(val)
580 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
581 requestTypeToCqueryIdEntries[val.requestType] =
582 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
583 }
584 labelRegistrationMapSection := ""
585 functionDefSection := ""
586 mainSwitchSection := ""
587
588 mapDeclarationFormatString := `
589%s = {
590 %s
591}
592`
593 functionDefFormatString := `
594def %s(target):
595%s
596`
597 mainSwitchSectionFormatString := `
598 if id_string in %s:
599 return id_string + ">>" + %s(target)
600`
601
Usta Shrestha0b52d832022-02-04 21:37:39 -0500602 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500603 labelMapName := requestType.Name() + "_Labels"
604 functionName := requestType.Name() + "_Fn"
605 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
606 labelMapName,
607 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
608 functionDefSection += fmt.Sprintf(functionDefFormatString,
609 functionName,
610 indent(requestType.StarlarkFunctionBody()))
611 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
612 labelMapName, functionName)
613 }
614
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400615 formatString := `
616# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400617
Chris Parsons944e7d02021-03-11 11:08:46 -0500618# Label Map Section
619%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500620
Chris Parsons944e7d02021-03-11 11:08:46 -0500621# Function Def Section
622%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500623
624def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400625 # TODO(b/199363072): filegroups and file targets aren't associated with any
626 # specific platform architecture in mixed builds. This is consistent with how
627 # Soong treats filegroups, but it may not be the case with manually-written
628 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500629 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000630 if buildoptions == None:
631 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400632 # any specific platform architecture in mixed builds, so use the host.
633 return "x86_64|linux"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500634 platforms = build_options(target)["//command_line_option:platforms"]
635 if len(platforms) != 1:
636 # An individual configured target should have only one platform architecture.
637 # Note that it's fine for there to be multiple architectures for the same label,
638 # but each is its own configured target.
639 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
640 platform_name = build_options(target)["//command_line_option:platforms"][0].name
641 if platform_name == "host":
642 return "HOST"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400643 elif platform_name.startswith("android_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400644 return platform_name[len("android_"):] + "|" + platform_name[:len("android_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400645 elif platform_name.startswith("linux_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400646 return platform_name[len("linux_"):] + "|" + platform_name[:len("linux_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400647 else:
648 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500649 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500650
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400651def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500652 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500653
654 # Main switch section
655 %s
656 # This target was not requested via cquery, and thus must be a dependency
657 # of a requested target.
658 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400659`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400660
Chris Parsons944e7d02021-03-11 11:08:46 -0500661 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
662 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400663}
664
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200665// Returns a path containing build-related metadata required for interfacing
666// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400667func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200668 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500669}
670
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200671// Returns the path where the contents of the @soong_injection repository live.
672// It is used by Soong to tell Bazel things it cannot over the command line.
673func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200674 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200675}
676
677// Returns the path of the synthetic Bazel workspace that contains a symlink
678// forest composed the whole source tree and BUILD files generated by bp2build.
679func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200680 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200681}
682
Jingwen Chen8c523582021-06-01 11:19:53 +0000683// Returns the path to the top level out dir ($OUT_DIR).
684func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200685 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000686}
687
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400688// Issues commands to Bazel to receive results for all cquery requests
689// queued in the BazelContext.
Yu Liu8d82ac52022-05-17 15:13:28 -0700690func (context *bazelContext) InvokeBazel(config Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400691 context.results = make(map[cqueryKey]string)
692
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400693 var cqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500694 var cqueryErr string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400695 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500696
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200697 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200698 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
699 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
700 err = os.MkdirAll(mixedBuildsPath, 0777)
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500701 }
Chris Parsons8ccdb632020-11-17 15:41:01 -0500702 if err != nil {
703 return err
704 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500705 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
706 err = os.MkdirAll(metricsDir, 0777)
707 if err != nil {
708 return err
709 }
710 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200711 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666)
712 if err != nil {
713 return err
714 }
715
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400716 err = ioutil.WriteFile(
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200717 filepath.Join(mixedBuildsPath, "main.bzl"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400718 context.mainBzlFileContents(), 0666)
719 if err != nil {
720 return err
721 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200722
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400723 err = ioutil.WriteFile(
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200724 filepath.Join(mixedBuildsPath, "BUILD.bazel"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400725 context.mainBuildFileContents(), 0666)
726 if err != nil {
727 return err
728 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200729 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400730 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800731 absolutePath(cqueryFileRelpath),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400732 context.cqueryStarlarkFileContents(), 0666)
733 if err != nil {
734 return err
735 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000736
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200737 buildrootLabel := "@soong_injection//mixed_builds:buildroot"
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400738 cqueryOutput, cqueryErr, err = context.issueBazelCommand(
739 context.paths,
740 bazel.CqueryBuildRootRunName,
Liz Kammerc19d5cd2021-10-06 18:16:58 -0400741 bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)},
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400742 "--output=starlark",
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200743 "--starlark:file="+absolutePath(cqueryFileRelpath))
744 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500745 []byte(cqueryOutput), 0666)
746 if err != nil {
747 return err
748 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400749
750 if err != nil {
751 return err
752 }
753
754 cqueryResults := map[string]string{}
755 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
756 if strings.Contains(outputLine, ">>") {
757 splitLine := strings.SplitN(outputLine, ">>", 2)
758 cqueryResults[splitLine[0]] = splitLine[1]
759 }
760 }
761
Usta Shrestha902fd172022-03-02 15:27:49 -0500762 for val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500763 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -0500764 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400765 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500766 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
767 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400768 }
769 }
770
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500771 // Issue an aquery command to retrieve action information about the bazel build tree.
772 //
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500773 var aqueryOutput string
Yu Liu8d82ac52022-05-17 15:13:28 -0700774 var coverageFlags []string
775 if Bool(config.productVariables.ClangCoverage) {
776 coverageFlags = append(coverageFlags, "--collect_code_coverage")
777 if len(config.productVariables.NativeCoveragePaths) > 0 ||
778 len(config.productVariables.NativeCoverageExcludePaths) > 0 {
779 includePaths := JoinWithPrefixAndSeparator(config.productVariables.NativeCoveragePaths, "+", ",")
780 excludePaths := JoinWithPrefixAndSeparator(config.productVariables.NativeCoverageExcludePaths, "-", ",")
781 if len(includePaths) > 0 && len(excludePaths) > 0 {
782 includePaths += ","
783 }
784 coverageFlags = append(coverageFlags, fmt.Sprintf(`--instrumentation_filter=%s`,
785 includePaths+excludePaths))
786 }
787 }
788
Sasha Smundak1da064c2022-06-08 16:36:16 -0700789 extraFlags := append([]string{"--output=jsonproto", "--include_file_write_contents"}, coverageFlags...)
Yu Liu8d82ac52022-05-17 15:13:28 -0700790
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400791 aqueryOutput, _, err = context.issueBazelCommand(
792 context.paths,
793 bazel.AqueryBuildRootRunName,
794 bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)},
795 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
796 // proto sources, which would add a number of unnecessary dependencies.
Yu Liu8d82ac52022-05-17 15:13:28 -0700797 extraFlags...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400798
799 if err != nil {
800 return err
801 }
802
Chris Parsons1a7aca02022-04-25 22:35:15 -0400803 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
Chris Parsons4f069892021-01-15 12:22:41 -0500804 if err != nil {
805 return err
806 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500807
808 // Issue a build command of the phony root to generate symlink forests for dependencies of the
809 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
810 // but some of symlinks may be required to resolve source dependencies of the build.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400811 _, _, err = context.issueBazelCommand(
812 context.paths,
813 bazel.BazelBuildPhonyRootRunName,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200814 bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"})
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500815
816 if err != nil {
817 return err
818 }
819
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400820 // Clear requests.
821 context.requests = map[cqueryKey]bool{}
822 return nil
823}
Chris Parsonsa798d962020-10-12 23:44:08 -0400824
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500825func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
826 return context.buildStatements
827}
828
Chris Parsons1a7aca02022-04-25 22:35:15 -0400829func (context *bazelContext) AqueryDepsets() []bazel.AqueryDepset {
830 return context.depsets
831}
832
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500833func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400834 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500835}
836
Chris Parsonsa798d962020-10-12 23:44:08 -0400837// Singleton used for registering BUILD file ninja dependencies (needed
838// for correctness of builds which use Bazel.
839func BazelSingleton() Singleton {
840 return &bazelSingleton{}
841}
842
843type bazelSingleton struct{}
844
845func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500846 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
847 if !ctx.Config().BazelContext.BazelEnabled() {
848 return
849 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400850
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500851 // Add ninja file dependencies for files which all bazel invocations require.
852 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200853 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500854 ctx.AddNinjaFileDeps(bazelBuildList)
855
856 data, err := ioutil.ReadFile(bazelBuildList)
857 if err != nil {
858 ctx.Errorf(err.Error())
859 }
860 files := strings.Split(strings.TrimSpace(string(data)), "\n")
861 for _, file := range files {
862 ctx.AddNinjaFileDeps(file)
863 }
864
Chris Parsons1a7aca02022-04-25 22:35:15 -0400865 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
866 var outputs []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400867 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
868 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400869 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
870 }
871 for _, artifactPath := range depset.DirectArtifacts {
872 outputs = append(outputs, PathForBazelOut(ctx, artifactPath))
873 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400874 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400875 ctx.Build(pctx, BuildParams{
876 Rule: blueprint.Phony,
877 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
878 Implicits: outputs,
879 })
880 }
881
Usta Shresthaacd5a0c2022-06-22 11:20:50 -0400882 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
883 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500884 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -0700885 if len(buildStatement.Command) > 0 {
886 rule := NewRuleBuilder(pctx, ctx)
887 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
888 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
889 rule.Build(fmt.Sprintf("bazel %d", index), desc)
890 continue
891 }
892 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
893 // and thus require special treatment. If BuildStatement were an interface implementing
894 // buildRule(ctx) function, the code here would just call it.
895 // Unfortunately, the BuildStatement is defined in
896 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
897 // because this would cause circular dependency. So, until we move aquery processing
898 // to the 'android' package, we need to handle special cases here.
899 if buildStatement.Mnemonic == "FileWrite" || buildStatement.Mnemonic == "SourceSymlinkManifest" {
900 // Pass file contents as the value of the rule's "content" argument.
901 // Escape newlines and $ in the contents (the action "writeBazelFile" restores "\\n"
902 // back to the newline, and Ninja reads $$ as $.
903 escaped := strings.ReplaceAll(strings.ReplaceAll(buildStatement.FileContents, "\n", "\\n"),
904 "$", "$$")
905 ctx.Build(pctx, BuildParams{
906 Rule: writeBazelFile,
907 Output: PathForBazelOut(ctx, buildStatement.OutputPaths[0]),
908 Description: fmt.Sprintf("%s %s", buildStatement.Mnemonic, buildStatement.OutputPaths[0]),
909 Args: map[string]string{
910 "content": escaped,
911 },
912 })
913 } else {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000914 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500915 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400916 }
917}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500918
Usta Shresthaacd5a0c2022-06-22 11:20:50 -0400919// Register bazel-owned build statements (obtained from the aquery invocation).
920func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx PathContext) {
921 // executionRoot is the action cwd.
922 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
923
924 // Remove old outputs, as some actions might not rerun if the outputs are detected.
925 if len(buildStatement.OutputPaths) > 0 {
926 cmd.Text("rm -f")
927 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -0400928 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -0400929 }
930 cmd.Text("&&")
931 }
932
933 for _, pair := range buildStatement.Env {
934 // Set per-action env variables, if any.
935 cmd.Flag(pair.Key + "=" + pair.Value)
936 }
937
938 // The actual Bazel action.
939 cmd.Text(buildStatement.Command)
940
941 for _, outputPath := range buildStatement.OutputPaths {
942 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
943 }
944 for _, inputPath := range buildStatement.InputPaths {
945 cmd.Implicit(PathForBazelOut(ctx, inputPath))
946 }
947 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
948 otherDepsetName := bazelDepsetName(inputDepsetHash)
949 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
950 }
951
952 if depfile := buildStatement.Depfile; depfile != nil {
953 // The paths in depfile are relative to `executionRoot`.
954 // Hence, they need to be corrected by replacing "bazel-out"
955 // with the full `bazelOutDir`.
956 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
957 // would be deemed missing.
958 // (Note: The regexp uses a capture group because the version of sed
959 // does not support a look-behind pattern.)
960 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
961 bazelOutDir, *depfile)
962 cmd.Text(replacement)
963 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
964 }
965
966 for _, symlinkPath := range buildStatement.SymlinkPaths {
967 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
968 }
969}
970
Chris Parsons8d6e4332021-02-22 16:13:50 -0500971func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -0400972 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500973}
974
Chris Parsons787fb362021-10-14 18:43:51 -0400975func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -0400976 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -0400977 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -0700978 if key.configKey.osType.Class == Device {
979 // For the generic Android, the expected result is "target|android", which
980 // corresponds to the product_variable_config named "android_target" in
981 // build/bazel/platforms/BUILD.bazel.
982 arch = "target"
983 } else {
984 // Use host platform, which is currently hardcoded to be x86_64.
985 arch = "x86_64"
986 }
Chris Parsons8d6e4332021-02-22 16:13:50 -0500987 }
Usta Shrestha16ac1352022-06-22 11:01:55 -0400988 osName := key.configKey.osType.Name
989 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" {
Chris Parsons787fb362021-10-14 18:43:51 -0400990 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -0400991 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -0400992 }
Usta Shrestha16ac1352022-06-22 11:01:55 -0400993 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -0400994}
995
Chris Parsonsf874e462022-05-10 13:50:12 -0400996func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -0400997 return configKey{
998 // use string because Arch is not a valid key in go
999 arch: ctx.Arch().String(),
1000 osType: ctx.Os(),
1001 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001002}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001003
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001004func bazelDepsetName(contentHash string) string {
1005 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001006}