blob: 33b67aba8b35050855491f23e5762a8b9670c5ec [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"
Chris Parsonsa798d962020-10-12 23:44:08 -040024 "path/filepath"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040025 "runtime"
26 "strings"
27 "sync"
Chris Parsonsa798d962020-10-12 23:44:08 -040028
Chris Parsons944e7d02021-03-11 11:08:46 -050029 "android/soong/bazel/cquery"
Jingwen Chen1e347862021-09-02 12:11:49 +000030 "android/soong/shared"
Chris Parsons1a7aca02022-04-25 22:35:15 -040031 "github.com/google/blueprint"
Liz Kammer8206d4f2021-03-03 16:40:52 -050032
Patrice Arruda05ab2d02020-12-12 06:24:26 +000033 "android/soong/bazel"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040034)
35
Chris Parsonsf874e462022-05-10 13:50:12 -040036func init() {
37 RegisterMixedBuildsMutator(InitRegistrationContext)
38}
39
40func RegisterMixedBuildsMutator(ctx RegistrationContext) {
41 ctx.PostDepsMutators(func(ctx RegisterMutatorsContext) {
42 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
43 })
44}
45
46func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
47 if m := ctx.Module(); m.Enabled() {
48 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
49 if mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx) {
50 mixedBuildMod.QueueBazelCall(ctx)
51 }
52 }
53 }
54}
55
Liz Kammerf29df7c2021-04-02 13:37:39 -040056type cqueryRequest interface {
57 // Name returns a string name for this request type. Such request type names must be unique,
58 // and must only consist of alphanumeric characters.
59 Name() string
60
61 // StarlarkFunctionBody returns a starlark function body to process this request type.
62 // The returned string is the body of a Starlark function which obtains
63 // all request-relevant information about a target and returns a string containing
64 // this information.
65 // The function should have the following properties:
66 // - `target` is the only parameter to this function (a configured target).
67 // - The return value must be a string.
68 // - The function body should not be indented outside of its own scope.
69 StarlarkFunctionBody() string
70}
71
Chris Parsons787fb362021-10-14 18:43:51 -040072// Portion of cquery map key to describe target configuration.
73type configKey struct {
Liz Kammer0940b892022-03-18 15:55:04 -040074 arch string
75 osType OsType
Chris Parsons787fb362021-10-14 18:43:51 -040076}
77
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040078// Map key to describe bazel cquery requests.
79type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040080 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -040081 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -040082 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040083}
84
Chris Parsonsf874e462022-05-10 13:50:12 -040085// BazelContext is a context object useful for interacting with Bazel during
86// the course of a build. Use of Bazel to evaluate part of the build graph
87// is referred to as a "mixed build". (Some modules are managed by Soong,
88// some are managed by Bazel). To facilitate interop between these build
89// subgraphs, Soong may make requests to Bazel and evaluate their responses
90// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040091type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -040092 // Add a cquery request to the bazel request queue. All queued requests
93 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
94 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
95
96 // ** Cquery Results Retrieval Functions
97 // The below functions pertain to retrieving cquery results from a prior
98 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040099
100 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400101 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500102
Chris Parsons944e7d02021-03-11 11:08:46 -0500103 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400104 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400105
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000106 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400107 // TODO(b/232976601): Remove.
108 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000109
Chris Parsonsf874e462022-05-10 13:50:12 -0400110 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400111
112 // Issues commands to Bazel to receive results for all cquery requests
113 // queued in the BazelContext.
Yu Liu8d82ac52022-05-17 15:13:28 -0700114 InvokeBazel(config Config) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400115
116 // Returns true if bazel is enabled for the given configuration.
117 BazelEnabled() bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500118
119 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
120 OutputBase() string
121
122 // Returns build statements which should get registered to reflect Bazel's outputs.
123 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400124
125 // Returns the depsets defined in Bazel's aquery response.
126 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400127}
128
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400129type bazelRunner interface {
130 issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) (string, string, error)
131}
132
133type bazelPaths struct {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400134 homeDir string
135 bazelPath string
136 outputBase string
137 workspaceDir string
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200138 soongOutDir string
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000139 metricsDir string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400140}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400141
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400142// A context object which tracks queued requests that need to be made to Bazel,
143// and their results after the requests have been made.
144type bazelContext struct {
145 bazelRunner
146 paths *bazelPaths
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400147 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
148 requestMutex sync.Mutex // requests can be written in parallel
149
150 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500151
152 // Build statements which should get registered to reflect Bazel's outputs.
153 buildStatements []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400154
155 // Depsets which should be used for Bazel's build statements.
156 depsets []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400157}
158
159var _ BazelContext = &bazelContext{}
160
161// A bazel context to use when Bazel is disabled.
162type noopBazelContext struct{}
163
164var _ BazelContext = noopBazelContext{}
165
166// A bazel context to use for tests.
167type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400168 OutputBaseDir string
169
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000170 LabelToOutputFiles map[string][]string
171 LabelToCcInfo map[string]cquery.CcInfo
172 LabelToPythonBinary map[string]string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400173}
174
Chris Parsonsf874e462022-05-10 13:50:12 -0400175func (m MockBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
176 panic("unimplemented")
Chris Parsons8d6e4332021-02-22 16:13:50 -0500177}
178
Chris Parsonsf874e462022-05-10 13:50:12 -0400179func (m MockBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
180 result, _ := m.LabelToOutputFiles[label]
181 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400182}
183
Chris Parsonsf874e462022-05-10 13:50:12 -0400184func (m MockBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
185 result, _ := m.LabelToCcInfo[label]
186 return result, nil
187}
188
189func (m MockBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
190 result, _ := m.LabelToPythonBinary[label]
191 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000192}
193
Yu Liu8d82ac52022-05-17 15:13:28 -0700194func (m MockBazelContext) InvokeBazel(config Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400195 panic("unimplemented")
196}
197
198func (m MockBazelContext) BazelEnabled() bool {
199 return true
200}
201
Liz Kammera92e8442021-04-07 20:25:21 -0400202func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500203
204func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
205 return []bazel.BuildStatement{}
206}
207
Chris Parsons1a7aca02022-04-25 22:35:15 -0400208func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
209 return []bazel.AqueryDepset{}
210}
211
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400212var _ BazelContext = MockBazelContext{}
213
Chris Parsonsf874e462022-05-10 13:50:12 -0400214func (bazelCtx *bazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
215 key := cqueryKey{label, requestType, cfgKey}
216 bazelCtx.requestMutex.Lock()
217 defer bazelCtx.requestMutex.Unlock()
218 bazelCtx.requests[key] = true
219}
220
221func (bazelCtx *bazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
222 key := cqueryKey{label, cquery.GetOutputFiles, cfgKey}
223 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500224 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400225 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400226 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400227 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400228}
229
Chris Parsonsf874e462022-05-10 13:50:12 -0400230func (bazelCtx *bazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
231 key := cqueryKey{label, cquery.GetCcInfo, cfgKey}
232 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000233 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400234 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000235 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400236 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 +0000237}
238
Chris Parsonsf874e462022-05-10 13:50:12 -0400239func (bazelCtx *bazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
240 key := cqueryKey{label, cquery.GetPythonBinary, cfgKey}
241 if rawString, ok := bazelCtx.results[key]; ok {
242 bazelOutput := strings.TrimSpace(rawString)
243 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
244 }
245 return "", fmt.Errorf("no bazel response found for %v", key)
246}
247
248func (n noopBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500249 panic("unimplemented")
250}
251
Chris Parsonsf874e462022-05-10 13:50:12 -0400252func (n noopBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500253 panic("unimplemented")
254}
255
Chris Parsonsf874e462022-05-10 13:50:12 -0400256func (n noopBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
257 panic("unimplemented")
258}
259
260func (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 +0000261 panic("unimplemented")
262}
263
Yu Liu8d82ac52022-05-17 15:13:28 -0700264func (n noopBazelContext) InvokeBazel(config Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400265 panic("unimplemented")
266}
267
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500268func (m noopBazelContext) OutputBase() string {
269 return ""
270}
271
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400272func (n noopBazelContext) BazelEnabled() bool {
273 return false
274}
275
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500276func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
277 return []bazel.BuildStatement{}
278}
279
Chris Parsons1a7aca02022-04-25 22:35:15 -0400280func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
281 return []bazel.AqueryDepset{}
282}
283
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400284func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons8b77a002020-10-27 18:59:25 -0400285 // TODO(cparsons): Assess USE_BAZEL=1 instead once "mixed Soong/Bazel builds"
286 // are production ready.
Jingwen Chen442b1a42021-06-17 07:02:15 +0000287 if !c.IsEnvTrue("USE_BAZEL_ANALYSIS") {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400288 return noopBazelContext{}, nil
289 }
290
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400291 p, err := bazelPathsFromConfig(c)
292 if err != nil {
293 return nil, err
294 }
295 return &bazelContext{
296 bazelRunner: &builtinBazelRunner{},
297 paths: p,
298 requests: make(map[cqueryKey]bool),
299 }, nil
300}
301
302func bazelPathsFromConfig(c *config) (*bazelPaths, error) {
303 p := bazelPaths{
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200304 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400305 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400306 missingEnvVars := []string{}
307 if len(c.Getenv("BAZEL_HOME")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400308 p.homeDir = c.Getenv("BAZEL_HOME")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400309 } else {
310 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
311 }
312 if len(c.Getenv("BAZEL_PATH")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400313 p.bazelPath = c.Getenv("BAZEL_PATH")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400314 } else {
315 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
316 }
317 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400318 p.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400319 } else {
320 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
321 }
322 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400323 p.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400324 } else {
325 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
326 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000327 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400328 p.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000329 } else {
330 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
331 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400332 if len(missingEnvVars) > 0 {
333 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
334 } else {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400335 return &p, nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400336 }
337}
338
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400339func (p *bazelPaths) BazelMetricsDir() string {
340 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000341}
342
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400343func (context *bazelContext) BazelEnabled() bool {
344 return true
345}
346
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400347func pwdPrefix() string {
348 // Darwin doesn't have /proc
349 if runtime.GOOS != "darwin" {
350 return "PWD=/proc/self/cwd"
351 }
352 return ""
353}
354
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400355type bazelCommand struct {
356 command string
357 // query or label
358 expression string
359}
360
361type mockBazelRunner struct {
362 bazelCommandResults map[bazelCommand]string
363 commands []bazelCommand
Yu Liu8d82ac52022-05-17 15:13:28 -0700364 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400365}
366
367func (r *mockBazelRunner) issueBazelCommand(paths *bazelPaths,
368 runName bazel.RunName,
369 command bazelCommand,
370 extraFlags ...string) (string, string, error) {
371 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700372 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400373 if ret, ok := r.bazelCommandResults[command]; ok {
374 return ret, "", nil
375 }
376 return "", "", nil
377}
378
379type builtinBazelRunner struct{}
380
Chris Parsons808d84c2021-03-09 20:43:32 -0500381// Issues the given bazel command with given build label and additional flags.
382// Returns (stdout, stderr, error). The first and second return values are strings
383// containing the stdout and stderr of the run command, and an error is returned if
384// the invocation returned an error code.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400385func (r *builtinBazelRunner) issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Chris Parsons808d84c2021-03-09 20:43:32 -0500386 extraFlags ...string) (string, string, error) {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000387 cmdFlags := []string{
388 // --noautodetect_server_javabase has the practical consequence of preventing Bazel from
389 // attempting to download rules_java, which is incompatible with
390 // --experimental_repository_disable_download set further below.
391 // rules_java is also not needed until mixed builds start building java targets.
392 // TODO(b/197958133): Once rules_java is pulled into AOSP, remove this flag.
393 "--noautodetect_server_javabase",
394 "--output_base=" + absolutePath(paths.outputBase),
395 command.command,
396 }
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400397 cmdFlags = append(cmdFlags, command.expression)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400398 cmdFlags = append(cmdFlags, "--profile="+shared.BazelMetricsFilename(paths, runName))
Jingwen Chen91220d72021-03-24 02:18:33 -0400399
400 // Set default platforms to canonicalized values for mixed builds requests.
401 // If these are set in the bazelrc, they will have values that are
402 // non-canonicalized to @sourceroot labels, and thus be invalid when
403 // referenced from the buildroot.
404 //
405 // The actual platform values here may be overridden by configuration
406 // transitions from the buildroot.
Chris Parsonsee423b02021-02-08 23:04:59 -0500407 cmdFlags = append(cmdFlags,
Liz Kammerc0c66092021-07-26 17:38:47 -0400408 fmt.Sprintf("--platforms=%s", "//build/bazel/platforms:android_target"))
Chris Parsonsee423b02021-02-08 23:04:59 -0500409 cmdFlags = append(cmdFlags,
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200410 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"))
Jingwen Chen91220d72021-03-24 02:18:33 -0400411 // This should be parameterized on the host OS, but let's restrict to linux
412 // to keep things simple for now.
413 cmdFlags = append(cmdFlags,
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200414 fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"))
Jingwen Chen91220d72021-03-24 02:18:33 -0400415
Chris Parsons8d6e4332021-02-22 16:13:50 -0500416 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
417 cmdFlags = append(cmdFlags, "--experimental_repository_disable_download")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400418 cmdFlags = append(cmdFlags, extraFlags...)
419
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400420 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200421 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200422 bazelCmd.Env = append(os.Environ(),
423 "HOME="+paths.homeDir,
424 pwdPrefix(),
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200425 "BUILD_DIR="+absolutePath(paths.soongOutDir),
Jingwen Chen8c523582021-06-01 11:19:53 +0000426 // Make OUT_DIR absolute here so tools/bazel.sh uses the correct
427 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
428 "OUT_DIR="+absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500429 // Disables local host detection of gcc; toolchain information is defined
430 // explicitly in BUILD files.
431 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
Colin Crossff0278b2020-10-09 19:24:15 -0700432 stderr := &bytes.Buffer{}
433 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400434
435 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500436 return "", string(stderr.Bytes()),
437 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400438 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500439 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400440 }
441}
442
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400443func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500444 // TODO(cparsons): Define configuration transitions programmatically based
445 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400446 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500447#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400448# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500449#####################################################
450
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400451def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500452 return {
Chris Parsons787fb362021-10-14 18:43:51 -0400453 "//command_line_option:platforms": "@//build/bazel/platforms:%s_%s" % (attr.os, attr.arch),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500454 }
455
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400456_config_node_transition = transition(
457 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500458 inputs = [],
459 outputs = [
460 "//command_line_option:platforms",
461 ],
462)
463
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400464def _passthrough_rule_impl(ctx):
465 return [DefaultInfo(files = depset(ctx.files.deps))]
466
467config_node = rule(
468 implementation = _passthrough_rule_impl,
469 attrs = {
470 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400471 "os" : attr.string(mandatory = True),
472 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400473 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
474 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500475)
476
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400477
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500478# Rule representing the root of the build, to depend on all Bazel targets that
479# are required for the build. Building this target will build the entire Bazel
480# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400481mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400482 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500483 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400484 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500485 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400486)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500487
488def _phony_root_impl(ctx):
489 return []
490
491# Rule to depend on other targets but build nothing.
492# This is useful as follows: building a target of this rule will generate
493# symlink forests for all dependencies of the target, without executing any
494# actions of the build.
495phony_root = rule(
496 implementation = _phony_root_impl,
497 attrs = {"deps" : attr.label_list()},
498)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400499`
500 return []byte(contents)
501}
502
503func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500504 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
505 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400506 formatString := `
507# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400508load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
509
510%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400511
512mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400513 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400514)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500515
516phony_root(name = "phonyroot",
517 deps = [":buildroot"],
518)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400519`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400520 configNodeFormatString := `
521config_node(name = "%s",
522 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400523 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400524 deps = [%s],
525)
526`
527
528 configNodesSection := ""
529
Chris Parsons787fb362021-10-14 18:43:51 -0400530 labelsByConfig := map[string][]string{}
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400531 for val, _ := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200532 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400533 configString := getConfigString(val)
534 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400535 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400536
Jingwen Chen1e347862021-09-02 12:11:49 +0000537 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400538 for configString, labels := range labelsByConfig {
539 configTokens := strings.Split(configString, "|")
540 if len(configTokens) != 2 {
541 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000542 }
Chris Parsons787fb362021-10-14 18:43:51 -0400543 archString := configTokens[0]
544 osString := configTokens[1]
545 targetString := fmt.Sprintf("%s_%s", osString, archString)
546 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
547 labelsString := strings.Join(labels, ",\n ")
548 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400549 }
550
Jingwen Chen1e347862021-09-02 12:11:49 +0000551 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400552}
553
Chris Parsons944e7d02021-03-11 11:08:46 -0500554func indent(original string) string {
555 result := ""
556 for _, line := range strings.Split(original, "\n") {
557 result += " " + line + "\n"
558 }
559 return result
560}
561
Chris Parsons808d84c2021-03-09 20:43:32 -0500562// Returns the file contents of the buildroot.cquery file that should be used for the cquery
563// expression in order to obtain information about buildroot and its dependencies.
564// The contents of this file depend on the bazelContext's requests; requests are enumerated
565// and grouped by their request type. The data retrieved for each label depends on its
566// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400567func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400568 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons944e7d02021-03-11 11:08:46 -0500569 for val, _ := range context.requests {
570 cqueryId := getCqueryId(val)
571 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
572 requestTypeToCqueryIdEntries[val.requestType] =
573 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
574 }
575 labelRegistrationMapSection := ""
576 functionDefSection := ""
577 mainSwitchSection := ""
578
579 mapDeclarationFormatString := `
580%s = {
581 %s
582}
583`
584 functionDefFormatString := `
585def %s(target):
586%s
587`
588 mainSwitchSectionFormatString := `
589 if id_string in %s:
590 return id_string + ">>" + %s(target)
591`
592
Usta Shrestha0b52d832022-02-04 21:37:39 -0500593 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500594 labelMapName := requestType.Name() + "_Labels"
595 functionName := requestType.Name() + "_Fn"
596 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
597 labelMapName,
598 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
599 functionDefSection += fmt.Sprintf(functionDefFormatString,
600 functionName,
601 indent(requestType.StarlarkFunctionBody()))
602 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
603 labelMapName, functionName)
604 }
605
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400606 formatString := `
607# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400608
Chris Parsons944e7d02021-03-11 11:08:46 -0500609# Label Map Section
610%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500611
Chris Parsons944e7d02021-03-11 11:08:46 -0500612# Function Def Section
613%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500614
615def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400616 # TODO(b/199363072): filegroups and file targets aren't associated with any
617 # specific platform architecture in mixed builds. This is consistent with how
618 # Soong treats filegroups, but it may not be the case with manually-written
619 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500620 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000621 if buildoptions == None:
622 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400623 # any specific platform architecture in mixed builds, so use the host.
624 return "x86_64|linux"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500625 platforms = build_options(target)["//command_line_option:platforms"]
626 if len(platforms) != 1:
627 # An individual configured target should have only one platform architecture.
628 # Note that it's fine for there to be multiple architectures for the same label,
629 # but each is its own configured target.
630 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
631 platform_name = build_options(target)["//command_line_option:platforms"][0].name
632 if platform_name == "host":
633 return "HOST"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400634 elif platform_name.startswith("android_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400635 return platform_name[len("android_"):] + "|" + platform_name[:len("android_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400636 elif platform_name.startswith("linux_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400637 return platform_name[len("linux_"):] + "|" + platform_name[:len("linux_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400638 else:
639 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500640 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500641
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400642def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500643 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500644
645 # Main switch section
646 %s
647 # This target was not requested via cquery, and thus must be a dependency
648 # of a requested target.
649 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400650`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400651
Chris Parsons944e7d02021-03-11 11:08:46 -0500652 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
653 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400654}
655
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200656// Returns a path containing build-related metadata required for interfacing
657// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400658func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200659 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500660}
661
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200662// Returns the path where the contents of the @soong_injection repository live.
663// It is used by Soong to tell Bazel things it cannot over the command line.
664func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200665 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200666}
667
668// Returns the path of the synthetic Bazel workspace that contains a symlink
669// forest composed the whole source tree and BUILD files generated by bp2build.
670func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200671 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200672}
673
Jingwen Chen8c523582021-06-01 11:19:53 +0000674// Returns the path to the top level out dir ($OUT_DIR).
675func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200676 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000677}
678
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400679// Issues commands to Bazel to receive results for all cquery requests
680// queued in the BazelContext.
Yu Liu8d82ac52022-05-17 15:13:28 -0700681func (context *bazelContext) InvokeBazel(config Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400682 context.results = make(map[cqueryKey]string)
683
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400684 var cqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500685 var cqueryErr string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400686 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500687
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200688 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200689 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
690 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
691 err = os.MkdirAll(mixedBuildsPath, 0777)
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500692 }
Chris Parsons8ccdb632020-11-17 15:41:01 -0500693 if err != nil {
694 return err
695 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500696 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
697 err = os.MkdirAll(metricsDir, 0777)
698 if err != nil {
699 return err
700 }
701 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200702 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666)
703 if err != nil {
704 return err
705 }
706
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400707 err = ioutil.WriteFile(
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200708 filepath.Join(mixedBuildsPath, "main.bzl"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400709 context.mainBzlFileContents(), 0666)
710 if err != nil {
711 return err
712 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200713
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400714 err = ioutil.WriteFile(
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200715 filepath.Join(mixedBuildsPath, "BUILD.bazel"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400716 context.mainBuildFileContents(), 0666)
717 if err != nil {
718 return err
719 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200720 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400721 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800722 absolutePath(cqueryFileRelpath),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400723 context.cqueryStarlarkFileContents(), 0666)
724 if err != nil {
725 return err
726 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000727
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200728 buildrootLabel := "@soong_injection//mixed_builds:buildroot"
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400729 cqueryOutput, cqueryErr, err = context.issueBazelCommand(
730 context.paths,
731 bazel.CqueryBuildRootRunName,
Liz Kammerc19d5cd2021-10-06 18:16:58 -0400732 bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)},
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400733 "--output=starlark",
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200734 "--starlark:file="+absolutePath(cqueryFileRelpath))
735 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500736 []byte(cqueryOutput), 0666)
737 if err != nil {
738 return err
739 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400740
741 if err != nil {
742 return err
743 }
744
745 cqueryResults := map[string]string{}
746 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
747 if strings.Contains(outputLine, ">>") {
748 splitLine := strings.SplitN(outputLine, ">>", 2)
749 cqueryResults[splitLine[0]] = splitLine[1]
750 }
751 }
752
Usta Shrestha902fd172022-03-02 15:27:49 -0500753 for val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500754 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -0500755 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400756 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500757 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
758 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400759 }
760 }
761
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500762 // Issue an aquery command to retrieve action information about the bazel build tree.
763 //
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500764 var aqueryOutput string
Yu Liu8d82ac52022-05-17 15:13:28 -0700765 var coverageFlags []string
766 if Bool(config.productVariables.ClangCoverage) {
767 coverageFlags = append(coverageFlags, "--collect_code_coverage")
768 if len(config.productVariables.NativeCoveragePaths) > 0 ||
769 len(config.productVariables.NativeCoverageExcludePaths) > 0 {
770 includePaths := JoinWithPrefixAndSeparator(config.productVariables.NativeCoveragePaths, "+", ",")
771 excludePaths := JoinWithPrefixAndSeparator(config.productVariables.NativeCoverageExcludePaths, "-", ",")
772 if len(includePaths) > 0 && len(excludePaths) > 0 {
773 includePaths += ","
774 }
775 coverageFlags = append(coverageFlags, fmt.Sprintf(`--instrumentation_filter=%s`,
776 includePaths+excludePaths))
777 }
778 }
779
780 extraFlags := append([]string{"--output=jsonproto"}, coverageFlags...)
781
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400782 aqueryOutput, _, err = context.issueBazelCommand(
783 context.paths,
784 bazel.AqueryBuildRootRunName,
785 bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)},
786 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
787 // proto sources, which would add a number of unnecessary dependencies.
Yu Liu8d82ac52022-05-17 15:13:28 -0700788 extraFlags...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400789
790 if err != nil {
791 return err
792 }
793
Chris Parsons1a7aca02022-04-25 22:35:15 -0400794 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
Chris Parsons4f069892021-01-15 12:22:41 -0500795 if err != nil {
796 return err
797 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500798
799 // Issue a build command of the phony root to generate symlink forests for dependencies of the
800 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
801 // but some of symlinks may be required to resolve source dependencies of the build.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400802 _, _, err = context.issueBazelCommand(
803 context.paths,
804 bazel.BazelBuildPhonyRootRunName,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200805 bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"})
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500806
807 if err != nil {
808 return err
809 }
810
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400811 // Clear requests.
812 context.requests = map[cqueryKey]bool{}
813 return nil
814}
Chris Parsonsa798d962020-10-12 23:44:08 -0400815
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500816func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
817 return context.buildStatements
818}
819
Chris Parsons1a7aca02022-04-25 22:35:15 -0400820func (context *bazelContext) AqueryDepsets() []bazel.AqueryDepset {
821 return context.depsets
822}
823
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500824func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400825 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500826}
827
Chris Parsonsa798d962020-10-12 23:44:08 -0400828// Singleton used for registering BUILD file ninja dependencies (needed
829// for correctness of builds which use Bazel.
830func BazelSingleton() Singleton {
831 return &bazelSingleton{}
832}
833
834type bazelSingleton struct{}
835
836func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500837 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
838 if !ctx.Config().BazelContext.BazelEnabled() {
839 return
840 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400841
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500842 // Add ninja file dependencies for files which all bazel invocations require.
843 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200844 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500845 ctx.AddNinjaFileDeps(bazelBuildList)
846
847 data, err := ioutil.ReadFile(bazelBuildList)
848 if err != nil {
849 ctx.Errorf(err.Error())
850 }
851 files := strings.Split(strings.TrimSpace(string(data)), "\n")
852 for _, file := range files {
853 ctx.AddNinjaFileDeps(file)
854 }
855
Chris Parsons1a7aca02022-04-25 22:35:15 -0400856 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
857 var outputs []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400858 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
859 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400860 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
861 }
862 for _, artifactPath := range depset.DirectArtifacts {
863 outputs = append(outputs, PathForBazelOut(ctx, artifactPath))
864 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400865 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400866 ctx.Build(pctx, BuildParams{
867 Rule: blueprint.Phony,
868 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
869 Implicits: outputs,
870 })
871 }
872
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500873 // Register bazel-owned build statements (obtained from the aquery invocation).
874 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500875 if len(buildStatement.Command) < 1 {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000876 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500877 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500878 rule := NewRuleBuilder(pctx, ctx)
879 cmd := rule.Command()
Chris Parsons94a0bba2021-06-04 15:03:47 -0400880
881 // cd into Bazel's execution root, which is the action cwd.
Chris Parsonse37a4de2021-09-23 17:10:50 -0400882 cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ &&", ctx.Config().BazelContext.OutputBase()))
883
884 // Remove old outputs, as some actions might not rerun if the outputs are detected.
885 if len(buildStatement.OutputPaths) > 0 {
886 cmd.Text("rm -f")
887 for _, outputPath := range buildStatement.OutputPaths {
Liz Kammerd7d5b722021-10-01 10:33:12 -0400888 cmd.Text(outputPath)
Chris Parsonse37a4de2021-09-23 17:10:50 -0400889 }
890 cmd.Text("&&")
891 }
Chris Parsons94a0bba2021-06-04 15:03:47 -0400892
893 for _, pair := range buildStatement.Env {
894 // Set per-action env variables, if any.
895 cmd.Flag(pair.Key + "=" + pair.Value)
896 }
897
898 // The actual Bazel action.
Usta Shrestha2ccdb422022-06-02 10:19:13 -0400899 cmd.Text(buildStatement.Command)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500900
901 for _, outputPath := range buildStatement.OutputPaths {
902 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400903 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500904 for _, inputPath := range buildStatement.InputPaths {
905 cmd.Implicit(PathForBazelOut(ctx, inputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400906 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400907 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
908 otherDepsetName := bazelDepsetName(inputDepsetHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400909 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
910 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500911
Liz Kammerde116852021-03-25 16:42:37 -0400912 if depfile := buildStatement.Depfile; depfile != nil {
913 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
914 }
915
Liz Kammerc49e6822021-06-08 15:04:11 -0400916 for _, symlinkPath := range buildStatement.SymlinkPaths {
917 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
918 }
919
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500920 // This is required to silence warnings pertaining to unexpected timestamps. Particularly,
921 // some Bazel builtins (such as files in the bazel_tools directory) have far-future
922 // timestamps. Without restat, Ninja would emit warnings that the input files of a
923 // build statement have later timestamps than the outputs.
924 rule.Restat()
925
Chris Parsons155d7682022-02-18 16:32:24 -0500926 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
927 rule.Build(fmt.Sprintf("bazel %d", index), desc)
Chris Parsonsa798d962020-10-12 23:44:08 -0400928 }
929}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500930
931func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -0400932 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500933}
934
Chris Parsons787fb362021-10-14 18:43:51 -0400935func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -0400936 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -0400937 if len(arch) == 0 || arch == "common" {
938 // Use host platform, which is currently hardcoded to be x86_64.
939 arch = "x86_64"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500940 }
Usta Shrestha16ac1352022-06-22 11:01:55 -0400941 osName := key.configKey.osType.Name
942 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" {
Chris Parsons787fb362021-10-14 18:43:51 -0400943 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -0400944 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -0400945 }
Usta Shrestha16ac1352022-06-22 11:01:55 -0400946 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -0400947}
948
Chris Parsonsf874e462022-05-10 13:50:12 -0400949func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -0400950 return configKey{
951 // use string because Arch is not a valid key in go
952 arch: ctx.Arch().String(),
953 osType: ctx.Os(),
954 }
Chris Parsons8d6e4332021-02-22 16:13:50 -0500955}
Chris Parsons1a7aca02022-04-25 22:35:15 -0400956
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400957func bazelDepsetName(contentHash string) string {
958 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400959}