blob: 8ab003c2a57cedfc1971ec6967f51d70f8d6e55c [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.
114 InvokeBazel() error
115
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
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400194func (m MockBazelContext) InvokeBazel() error {
195 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
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400264func (n noopBazelContext) InvokeBazel() error {
265 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
364}
365
366func (r *mockBazelRunner) issueBazelCommand(paths *bazelPaths,
367 runName bazel.RunName,
368 command bazelCommand,
369 extraFlags ...string) (string, string, error) {
370 r.commands = append(r.commands, command)
371 if ret, ok := r.bazelCommandResults[command]; ok {
372 return ret, "", nil
373 }
374 return "", "", nil
375}
376
377type builtinBazelRunner struct{}
378
Chris Parsons808d84c2021-03-09 20:43:32 -0500379// Issues the given bazel command with given build label and additional flags.
380// Returns (stdout, stderr, error). The first and second return values are strings
381// containing the stdout and stderr of the run command, and an error is returned if
382// the invocation returned an error code.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400383func (r *builtinBazelRunner) issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Chris Parsons808d84c2021-03-09 20:43:32 -0500384 extraFlags ...string) (string, string, error) {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000385 cmdFlags := []string{
386 // --noautodetect_server_javabase has the practical consequence of preventing Bazel from
387 // attempting to download rules_java, which is incompatible with
388 // --experimental_repository_disable_download set further below.
389 // rules_java is also not needed until mixed builds start building java targets.
390 // TODO(b/197958133): Once rules_java is pulled into AOSP, remove this flag.
391 "--noautodetect_server_javabase",
392 "--output_base=" + absolutePath(paths.outputBase),
393 command.command,
394 }
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400395 cmdFlags = append(cmdFlags, command.expression)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400396 cmdFlags = append(cmdFlags, "--profile="+shared.BazelMetricsFilename(paths, runName))
Jingwen Chen91220d72021-03-24 02:18:33 -0400397
398 // Set default platforms to canonicalized values for mixed builds requests.
399 // If these are set in the bazelrc, they will have values that are
400 // non-canonicalized to @sourceroot labels, and thus be invalid when
401 // referenced from the buildroot.
402 //
403 // The actual platform values here may be overridden by configuration
404 // transitions from the buildroot.
Chris Parsonsee423b02021-02-08 23:04:59 -0500405 cmdFlags = append(cmdFlags,
Liz Kammerc0c66092021-07-26 17:38:47 -0400406 fmt.Sprintf("--platforms=%s", "//build/bazel/platforms:android_target"))
Chris Parsonsee423b02021-02-08 23:04:59 -0500407 cmdFlags = append(cmdFlags,
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200408 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"))
Jingwen Chen91220d72021-03-24 02:18:33 -0400409 // This should be parameterized on the host OS, but let's restrict to linux
410 // to keep things simple for now.
411 cmdFlags = append(cmdFlags,
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200412 fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"))
Jingwen Chen91220d72021-03-24 02:18:33 -0400413
Chris Parsons8d6e4332021-02-22 16:13:50 -0500414 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
415 cmdFlags = append(cmdFlags, "--experimental_repository_disable_download")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400416 cmdFlags = append(cmdFlags, extraFlags...)
417
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400418 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200419 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200420 bazelCmd.Env = append(os.Environ(),
421 "HOME="+paths.homeDir,
422 pwdPrefix(),
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200423 "BUILD_DIR="+absolutePath(paths.soongOutDir),
Jingwen Chen8c523582021-06-01 11:19:53 +0000424 // Make OUT_DIR absolute here so tools/bazel.sh uses the correct
425 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
426 "OUT_DIR="+absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500427 // Disables local host detection of gcc; toolchain information is defined
428 // explicitly in BUILD files.
429 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
Colin Crossff0278b2020-10-09 19:24:15 -0700430 stderr := &bytes.Buffer{}
431 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400432
433 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500434 return "", string(stderr.Bytes()),
435 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400436 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500437 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400438 }
439}
440
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400441func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500442 // TODO(cparsons): Define configuration transitions programmatically based
443 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400444 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500445#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400446# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500447#####################################################
448
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400449def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500450 return {
Chris Parsons787fb362021-10-14 18:43:51 -0400451 "//command_line_option:platforms": "@//build/bazel/platforms:%s_%s" % (attr.os, attr.arch),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500452 }
453
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400454_config_node_transition = transition(
455 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500456 inputs = [],
457 outputs = [
458 "//command_line_option:platforms",
459 ],
460)
461
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400462def _passthrough_rule_impl(ctx):
463 return [DefaultInfo(files = depset(ctx.files.deps))]
464
465config_node = rule(
466 implementation = _passthrough_rule_impl,
467 attrs = {
468 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400469 "os" : attr.string(mandatory = True),
470 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400471 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
472 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500473)
474
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400475
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500476# Rule representing the root of the build, to depend on all Bazel targets that
477# are required for the build. Building this target will build the entire Bazel
478# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400479mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400480 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500481 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400482 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500483 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400484)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500485
486def _phony_root_impl(ctx):
487 return []
488
489# Rule to depend on other targets but build nothing.
490# This is useful as follows: building a target of this rule will generate
491# symlink forests for all dependencies of the target, without executing any
492# actions of the build.
493phony_root = rule(
494 implementation = _phony_root_impl,
495 attrs = {"deps" : attr.label_list()},
496)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400497`
498 return []byte(contents)
499}
500
501func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500502 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
503 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400504 formatString := `
505# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400506load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
507
508%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400509
510mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400511 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400512)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500513
514phony_root(name = "phonyroot",
515 deps = [":buildroot"],
516)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400517`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400518 configNodeFormatString := `
519config_node(name = "%s",
520 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400521 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400522 deps = [%s],
523)
524`
525
526 configNodesSection := ""
527
Chris Parsons787fb362021-10-14 18:43:51 -0400528 labelsByConfig := map[string][]string{}
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400529 for val, _ := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200530 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400531 configString := getConfigString(val)
532 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400533 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400534
Jingwen Chen1e347862021-09-02 12:11:49 +0000535 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400536 for configString, labels := range labelsByConfig {
537 configTokens := strings.Split(configString, "|")
538 if len(configTokens) != 2 {
539 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000540 }
Chris Parsons787fb362021-10-14 18:43:51 -0400541 archString := configTokens[0]
542 osString := configTokens[1]
543 targetString := fmt.Sprintf("%s_%s", osString, archString)
544 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
545 labelsString := strings.Join(labels, ",\n ")
546 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400547 }
548
Jingwen Chen1e347862021-09-02 12:11:49 +0000549 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400550}
551
Chris Parsons944e7d02021-03-11 11:08:46 -0500552func indent(original string) string {
553 result := ""
554 for _, line := range strings.Split(original, "\n") {
555 result += " " + line + "\n"
556 }
557 return result
558}
559
Chris Parsons808d84c2021-03-09 20:43:32 -0500560// Returns the file contents of the buildroot.cquery file that should be used for the cquery
561// expression in order to obtain information about buildroot and its dependencies.
562// The contents of this file depend on the bazelContext's requests; requests are enumerated
563// and grouped by their request type. The data retrieved for each label depends on its
564// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400565func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400566 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons944e7d02021-03-11 11:08:46 -0500567 for val, _ := range context.requests {
568 cqueryId := getCqueryId(val)
569 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
570 requestTypeToCqueryIdEntries[val.requestType] =
571 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
572 }
573 labelRegistrationMapSection := ""
574 functionDefSection := ""
575 mainSwitchSection := ""
576
577 mapDeclarationFormatString := `
578%s = {
579 %s
580}
581`
582 functionDefFormatString := `
583def %s(target):
584%s
585`
586 mainSwitchSectionFormatString := `
587 if id_string in %s:
588 return id_string + ">>" + %s(target)
589`
590
Usta Shrestha0b52d832022-02-04 21:37:39 -0500591 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500592 labelMapName := requestType.Name() + "_Labels"
593 functionName := requestType.Name() + "_Fn"
594 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
595 labelMapName,
596 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
597 functionDefSection += fmt.Sprintf(functionDefFormatString,
598 functionName,
599 indent(requestType.StarlarkFunctionBody()))
600 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
601 labelMapName, functionName)
602 }
603
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400604 formatString := `
605# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400606
Chris Parsons944e7d02021-03-11 11:08:46 -0500607# Label Map Section
608%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500609
Chris Parsons944e7d02021-03-11 11:08:46 -0500610# Function Def Section
611%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500612
613def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400614 # TODO(b/199363072): filegroups and file targets aren't associated with any
615 # specific platform architecture in mixed builds. This is consistent with how
616 # Soong treats filegroups, but it may not be the case with manually-written
617 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500618 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000619 if buildoptions == None:
620 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400621 # any specific platform architecture in mixed builds, so use the host.
622 return "x86_64|linux"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500623 platforms = build_options(target)["//command_line_option:platforms"]
624 if len(platforms) != 1:
625 # An individual configured target should have only one platform architecture.
626 # Note that it's fine for there to be multiple architectures for the same label,
627 # but each is its own configured target.
628 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
629 platform_name = build_options(target)["//command_line_option:platforms"][0].name
630 if platform_name == "host":
631 return "HOST"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400632 elif platform_name.startswith("android_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400633 return platform_name[len("android_"):] + "|" + platform_name[:len("android_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400634 elif platform_name.startswith("linux_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400635 return platform_name[len("linux_"):] + "|" + platform_name[:len("linux_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400636 else:
637 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500638 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500639
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400640def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500641 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500642
643 # Main switch section
644 %s
645 # This target was not requested via cquery, and thus must be a dependency
646 # of a requested target.
647 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400648`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400649
Chris Parsons944e7d02021-03-11 11:08:46 -0500650 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
651 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400652}
653
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200654// Returns a path containing build-related metadata required for interfacing
655// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400656func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200657 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500658}
659
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200660// Returns the path where the contents of the @soong_injection repository live.
661// It is used by Soong to tell Bazel things it cannot over the command line.
662func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200663 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200664}
665
666// Returns the path of the synthetic Bazel workspace that contains a symlink
667// forest composed the whole source tree and BUILD files generated by bp2build.
668func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200669 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200670}
671
Jingwen Chen8c523582021-06-01 11:19:53 +0000672// Returns the path to the top level out dir ($OUT_DIR).
673func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200674 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000675}
676
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400677// Issues commands to Bazel to receive results for all cquery requests
678// queued in the BazelContext.
679func (context *bazelContext) InvokeBazel() error {
680 context.results = make(map[cqueryKey]string)
681
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400682 var cqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500683 var cqueryErr string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400684 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500685
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200686 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200687 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
688 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
689 err = os.MkdirAll(mixedBuildsPath, 0777)
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500690 }
Chris Parsons8ccdb632020-11-17 15:41:01 -0500691 if err != nil {
692 return err
693 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500694 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
695 err = os.MkdirAll(metricsDir, 0777)
696 if err != nil {
697 return err
698 }
699 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200700 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666)
701 if err != nil {
702 return err
703 }
704
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400705 err = ioutil.WriteFile(
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200706 filepath.Join(mixedBuildsPath, "main.bzl"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400707 context.mainBzlFileContents(), 0666)
708 if err != nil {
709 return err
710 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200711
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400712 err = ioutil.WriteFile(
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200713 filepath.Join(mixedBuildsPath, "BUILD.bazel"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400714 context.mainBuildFileContents(), 0666)
715 if err != nil {
716 return err
717 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200718 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400719 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800720 absolutePath(cqueryFileRelpath),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400721 context.cqueryStarlarkFileContents(), 0666)
722 if err != nil {
723 return err
724 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000725
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200726 buildrootLabel := "@soong_injection//mixed_builds:buildroot"
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400727 cqueryOutput, cqueryErr, err = context.issueBazelCommand(
728 context.paths,
729 bazel.CqueryBuildRootRunName,
Liz Kammerc19d5cd2021-10-06 18:16:58 -0400730 bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)},
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400731 "--output=starlark",
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200732 "--starlark:file="+absolutePath(cqueryFileRelpath))
733 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500734 []byte(cqueryOutput), 0666)
735 if err != nil {
736 return err
737 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400738
739 if err != nil {
740 return err
741 }
742
743 cqueryResults := map[string]string{}
744 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
745 if strings.Contains(outputLine, ">>") {
746 splitLine := strings.SplitN(outputLine, ">>", 2)
747 cqueryResults[splitLine[0]] = splitLine[1]
748 }
749 }
750
Usta Shrestha902fd172022-03-02 15:27:49 -0500751 for val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500752 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -0500753 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400754 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500755 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
756 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400757 }
758 }
759
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500760 // Issue an aquery command to retrieve action information about the bazel build tree.
761 //
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400762 // TODO(cparsons): Use --target_pattern_file to avoid command line limits.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500763 var aqueryOutput string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400764 aqueryOutput, _, err = context.issueBazelCommand(
765 context.paths,
766 bazel.AqueryBuildRootRunName,
767 bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)},
768 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
769 // proto sources, which would add a number of unnecessary dependencies.
770 "--output=jsonproto")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400771
772 if err != nil {
773 return err
774 }
775
Chris Parsons1a7aca02022-04-25 22:35:15 -0400776 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
Chris Parsons4f069892021-01-15 12:22:41 -0500777 if err != nil {
778 return err
779 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500780
781 // Issue a build command of the phony root to generate symlink forests for dependencies of the
782 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
783 // but some of symlinks may be required to resolve source dependencies of the build.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400784 _, _, err = context.issueBazelCommand(
785 context.paths,
786 bazel.BazelBuildPhonyRootRunName,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200787 bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"})
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500788
789 if err != nil {
790 return err
791 }
792
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400793 // Clear requests.
794 context.requests = map[cqueryKey]bool{}
795 return nil
796}
Chris Parsonsa798d962020-10-12 23:44:08 -0400797
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500798func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
799 return context.buildStatements
800}
801
Chris Parsons1a7aca02022-04-25 22:35:15 -0400802func (context *bazelContext) AqueryDepsets() []bazel.AqueryDepset {
803 return context.depsets
804}
805
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500806func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400807 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500808}
809
Chris Parsonsa798d962020-10-12 23:44:08 -0400810// Singleton used for registering BUILD file ninja dependencies (needed
811// for correctness of builds which use Bazel.
812func BazelSingleton() Singleton {
813 return &bazelSingleton{}
814}
815
816type bazelSingleton struct{}
817
818func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500819 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
820 if !ctx.Config().BazelContext.BazelEnabled() {
821 return
822 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400823
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500824 // Add ninja file dependencies for files which all bazel invocations require.
825 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200826 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500827 ctx.AddNinjaFileDeps(bazelBuildList)
828
829 data, err := ioutil.ReadFile(bazelBuildList)
830 if err != nil {
831 ctx.Errorf(err.Error())
832 }
833 files := strings.Split(strings.TrimSpace(string(data)), "\n")
834 for _, file := range files {
835 ctx.AddNinjaFileDeps(file)
836 }
837
Chris Parsons1a7aca02022-04-25 22:35:15 -0400838 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
839 var outputs []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400840 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
841 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400842 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
843 }
844 for _, artifactPath := range depset.DirectArtifacts {
845 outputs = append(outputs, PathForBazelOut(ctx, artifactPath))
846 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400847 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400848 ctx.Build(pctx, BuildParams{
849 Rule: blueprint.Phony,
850 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
851 Implicits: outputs,
852 })
853 }
854
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500855 // Register bazel-owned build statements (obtained from the aquery invocation).
856 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500857 if len(buildStatement.Command) < 1 {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000858 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500859 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500860 rule := NewRuleBuilder(pctx, ctx)
861 cmd := rule.Command()
Chris Parsons94a0bba2021-06-04 15:03:47 -0400862
863 // cd into Bazel's execution root, which is the action cwd.
Chris Parsonse37a4de2021-09-23 17:10:50 -0400864 cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ &&", ctx.Config().BazelContext.OutputBase()))
865
866 // Remove old outputs, as some actions might not rerun if the outputs are detected.
867 if len(buildStatement.OutputPaths) > 0 {
868 cmd.Text("rm -f")
869 for _, outputPath := range buildStatement.OutputPaths {
Liz Kammerd7d5b722021-10-01 10:33:12 -0400870 cmd.Text(outputPath)
Chris Parsonse37a4de2021-09-23 17:10:50 -0400871 }
872 cmd.Text("&&")
873 }
Chris Parsons94a0bba2021-06-04 15:03:47 -0400874
875 for _, pair := range buildStatement.Env {
876 // Set per-action env variables, if any.
877 cmd.Flag(pair.Key + "=" + pair.Value)
878 }
879
880 // The actual Bazel action.
Usta Shrestha2ccdb422022-06-02 10:19:13 -0400881 cmd.Text(buildStatement.Command)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500882
883 for _, outputPath := range buildStatement.OutputPaths {
884 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400885 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500886 for _, inputPath := range buildStatement.InputPaths {
887 cmd.Implicit(PathForBazelOut(ctx, inputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400888 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400889 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
890 otherDepsetName := bazelDepsetName(inputDepsetHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400891 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
892 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500893
Liz Kammerde116852021-03-25 16:42:37 -0400894 if depfile := buildStatement.Depfile; depfile != nil {
895 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
896 }
897
Liz Kammerc49e6822021-06-08 15:04:11 -0400898 for _, symlinkPath := range buildStatement.SymlinkPaths {
899 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
900 }
901
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500902 // This is required to silence warnings pertaining to unexpected timestamps. Particularly,
903 // some Bazel builtins (such as files in the bazel_tools directory) have far-future
904 // timestamps. Without restat, Ninja would emit warnings that the input files of a
905 // build statement have later timestamps than the outputs.
906 rule.Restat()
907
Chris Parsons155d7682022-02-18 16:32:24 -0500908 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
909 rule.Build(fmt.Sprintf("bazel %d", index), desc)
Chris Parsonsa798d962020-10-12 23:44:08 -0400910 }
911}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500912
913func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -0400914 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500915}
916
Chris Parsons787fb362021-10-14 18:43:51 -0400917func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -0400918 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -0400919 if len(arch) == 0 || arch == "common" {
920 // Use host platform, which is currently hardcoded to be x86_64.
921 arch = "x86_64"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500922 }
Chris Parsons787fb362021-10-14 18:43:51 -0400923 os := key.configKey.osType.Name
Chris Parsons494eef32021-11-09 10:29:52 -0500924 if len(os) == 0 || os == "common_os" || os == "linux_glibc" {
Chris Parsons787fb362021-10-14 18:43:51 -0400925 // Use host OS, which is currently hardcoded to be linux.
926 os = "linux"
927 }
928 return arch + "|" + os
929}
930
Chris Parsonsf874e462022-05-10 13:50:12 -0400931func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -0400932 return configKey{
933 // use string because Arch is not a valid key in go
934 arch: ctx.Arch().String(),
935 osType: ctx.Os(),
936 }
Chris Parsons8d6e4332021-02-22 16:13:50 -0500937}
Chris Parsons1a7aca02022-04-25 22:35:15 -0400938
Chris Parsons0bfb1c02022-05-12 16:43:01 -0400939func bazelDepsetName(contentHash string) string {
940 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -0400941}