blob: 3c6212e0c51d3389aedfc3788dae1d622b7d1aba [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"
Liz Kammer8206d4f2021-03-03 16:40:52 -050031
Patrice Arruda05ab2d02020-12-12 06:24:26 +000032 "android/soong/bazel"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040033)
34
Liz Kammerf29df7c2021-04-02 13:37:39 -040035type cqueryRequest interface {
36 // Name returns a string name for this request type. Such request type names must be unique,
37 // and must only consist of alphanumeric characters.
38 Name() string
39
40 // StarlarkFunctionBody returns a starlark function body to process this request type.
41 // The returned string is the body of a Starlark function which obtains
42 // all request-relevant information about a target and returns a string containing
43 // this information.
44 // The function should have the following properties:
45 // - `target` is the only parameter to this function (a configured target).
46 // - The return value must be a string.
47 // - The function body should not be indented outside of its own scope.
48 StarlarkFunctionBody() string
49}
50
Chris Parsons787fb362021-10-14 18:43:51 -040051// Portion of cquery map key to describe target configuration.
52type configKey struct {
53 archType ArchType
54 osType OsType
55}
56
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040057// Map key to describe bazel cquery requests.
58type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040059 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -040060 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -040061 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040062}
63
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux0d990452021-08-11 16:46:13 +000064// bazelHandler is the interface for a helper object related to deferring to Bazel for
65// processing a module (during Bazel mixed builds). Individual module types should define
66// their own bazel handler if they support deferring to Bazel.
67type BazelHandler interface {
68 // Issue query to Bazel to retrieve information about Bazel's view of the current module.
69 // If Bazel returns this information, set module properties on the current module to reflect
70 // the returned information.
71 // Returns true if information was available from Bazel, false if bazel invocation still needs to occur.
72 GenerateBazelBuildActions(ctx ModuleContext, label string) bool
73}
74
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040075type BazelContext interface {
76 // The below methods involve queuing cquery requests to be later invoked
77 // by bazel. If any of these methods return (_, false), then the request
78 // has been queued to be run later.
79
80 // Returns result files built by building the given bazel target label.
Chris Parsons787fb362021-10-14 18:43:51 -040081 GetOutputFiles(label string, cfgKey configKey) ([]string, bool)
Chris Parsons8d6e4332021-02-22 16:13:50 -050082
Chris Parsons944e7d02021-03-11 11:08:46 -050083 // TODO(cparsons): Other cquery-related methods should be added here.
84 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsons787fb362021-10-14 18:43:51 -040085 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, bool, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -040086
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +000087 // Returns the executable binary resultant from building together the python sources
Chris Parsons787fb362021-10-14 18:43:51 -040088 GetPythonBinary(label string, cfgKey configKey) (string, bool)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +000089
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040090 // ** End cquery methods
91
92 // Issues commands to Bazel to receive results for all cquery requests
93 // queued in the BazelContext.
94 InvokeBazel() error
95
96 // Returns true if bazel is enabled for the given configuration.
97 BazelEnabled() bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050098
99 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
100 OutputBase() string
101
102 // Returns build statements which should get registered to reflect Bazel's outputs.
103 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400104}
105
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400106type bazelRunner interface {
107 issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) (string, string, error)
108}
109
110type bazelPaths struct {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400111 homeDir string
112 bazelPath string
113 outputBase string
114 workspaceDir string
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200115 soongOutDir string
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000116 metricsDir string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400117}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400118
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400119// A context object which tracks queued requests that need to be made to Bazel,
120// and their results after the requests have been made.
121type bazelContext struct {
122 bazelRunner
123 paths *bazelPaths
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400124 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
125 requestMutex sync.Mutex // requests can be written in parallel
126
127 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500128
129 // Build statements which should get registered to reflect Bazel's outputs.
130 buildStatements []bazel.BuildStatement
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400131}
132
133var _ BazelContext = &bazelContext{}
134
135// A bazel context to use when Bazel is disabled.
136type noopBazelContext struct{}
137
138var _ BazelContext = noopBazelContext{}
139
140// A bazel context to use for tests.
141type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400142 OutputBaseDir string
143
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000144 LabelToOutputFiles map[string][]string
145 LabelToCcInfo map[string]cquery.CcInfo
146 LabelToPythonBinary map[string]string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400147}
148
Chris Parsons787fb362021-10-14 18:43:51 -0400149func (m MockBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, bool) {
Liz Kammera92e8442021-04-07 20:25:21 -0400150 result, ok := m.LabelToOutputFiles[label]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500151 return result, ok
152}
153
Chris Parsons787fb362021-10-14 18:43:51 -0400154func (m MockBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, bool, error) {
Liz Kammerb71794d2021-04-09 14:07:00 -0400155 result, ok := m.LabelToCcInfo[label]
Liz Kammerfe23bf32021-04-09 16:17:05 -0400156 return result, ok, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400157}
158
Chris Parsons787fb362021-10-14 18:43:51 -0400159func (m MockBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, bool) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000160 result, ok := m.LabelToPythonBinary[label]
161 return result, ok
162}
163
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400164func (m MockBazelContext) InvokeBazel() error {
165 panic("unimplemented")
166}
167
168func (m MockBazelContext) BazelEnabled() bool {
169 return true
170}
171
Liz Kammera92e8442021-04-07 20:25:21 -0400172func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500173
174func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
175 return []bazel.BuildStatement{}
176}
177
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400178var _ BazelContext = MockBazelContext{}
179
Chris Parsons787fb362021-10-14 18:43:51 -0400180func (bazelCtx *bazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, bool) {
181 rawString, ok := bazelCtx.cquery(label, cquery.GetOutputFiles, cfgKey)
Chris Parsons944e7d02021-03-11 11:08:46 -0500182 var ret []string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400183 if ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500184 bazelOutput := strings.TrimSpace(rawString)
Liz Kammerf29df7c2021-04-02 13:37:39 -0400185 ret = cquery.GetOutputFiles.ParseResult(bazelOutput)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400186 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500187 return ret, ok
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400188}
189
Chris Parsons787fb362021-10-14 18:43:51 -0400190func (bazelCtx *bazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, bool, error) {
191 result, ok := bazelCtx.cquery(label, cquery.GetCcInfo, cfgKey)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400192 if !ok {
Liz Kammerfe23bf32021-04-09 16:17:05 -0400193 return cquery.CcInfo{}, ok, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400194 }
195
196 bazelOutput := strings.TrimSpace(result)
Liz Kammerfe23bf32021-04-09 16:17:05 -0400197 ret, err := cquery.GetCcInfo.ParseResult(bazelOutput)
198 return ret, ok, err
Liz Kammer3f9e1552021-04-02 18:47:09 -0400199}
200
Chris Parsons787fb362021-10-14 18:43:51 -0400201func (bazelCtx *bazelContext) GetPythonBinary(label string, cfgKey configKey) (string, bool) {
202 rawString, ok := bazelCtx.cquery(label, cquery.GetPythonBinary, cfgKey)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000203 var ret string
204 if ok {
205 bazelOutput := strings.TrimSpace(rawString)
206 ret = cquery.GetPythonBinary.ParseResult(bazelOutput)
207 }
208 return ret, ok
209}
210
Chris Parsons787fb362021-10-14 18:43:51 -0400211func (n noopBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, bool) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500212 panic("unimplemented")
213}
214
Chris Parsons787fb362021-10-14 18:43:51 -0400215func (n noopBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, bool, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500216 panic("unimplemented")
217}
218
Chris Parsons787fb362021-10-14 18:43:51 -0400219func (n noopBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, bool) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000220 panic("unimplemented")
221}
222
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400223func (n noopBazelContext) InvokeBazel() error {
224 panic("unimplemented")
225}
226
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500227func (m noopBazelContext) OutputBase() string {
228 return ""
229}
230
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400231func (n noopBazelContext) BazelEnabled() bool {
232 return false
233}
234
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500235func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
236 return []bazel.BuildStatement{}
237}
238
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400239func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons8b77a002020-10-27 18:59:25 -0400240 // TODO(cparsons): Assess USE_BAZEL=1 instead once "mixed Soong/Bazel builds"
241 // are production ready.
Jingwen Chen442b1a42021-06-17 07:02:15 +0000242 if !c.IsEnvTrue("USE_BAZEL_ANALYSIS") {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400243 return noopBazelContext{}, nil
244 }
245
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400246 p, err := bazelPathsFromConfig(c)
247 if err != nil {
248 return nil, err
249 }
250 return &bazelContext{
251 bazelRunner: &builtinBazelRunner{},
252 paths: p,
253 requests: make(map[cqueryKey]bool),
254 }, nil
255}
256
257func bazelPathsFromConfig(c *config) (*bazelPaths, error) {
258 p := bazelPaths{
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200259 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400260 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400261 missingEnvVars := []string{}
262 if len(c.Getenv("BAZEL_HOME")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400263 p.homeDir = c.Getenv("BAZEL_HOME")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400264 } else {
265 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
266 }
267 if len(c.Getenv("BAZEL_PATH")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400268 p.bazelPath = c.Getenv("BAZEL_PATH")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400269 } else {
270 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
271 }
272 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400273 p.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400274 } else {
275 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
276 }
277 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400278 p.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400279 } else {
280 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
281 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000282 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400283 p.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000284 } else {
285 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
286 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400287 if len(missingEnvVars) > 0 {
288 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
289 } else {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400290 return &p, nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400291 }
292}
293
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400294func (p *bazelPaths) BazelMetricsDir() string {
295 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000296}
297
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400298func (context *bazelContext) BazelEnabled() bool {
299 return true
300}
301
302// Adds a cquery request to the Bazel request queue, to be later invoked, or
303// returns the result of the given request if the request was already made.
304// If the given request was already made (and the results are available), then
305// returns (result, true). If the request is queued but no results are available,
306// then returns ("", false).
Liz Kammerf29df7c2021-04-02 13:37:39 -0400307func (context *bazelContext) cquery(label string, requestType cqueryRequest,
Chris Parsons787fb362021-10-14 18:43:51 -0400308 cfgKey configKey) (string, bool) {
309 key := cqueryKey{label, requestType, cfgKey}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400310 if result, ok := context.results[key]; ok {
311 return result, true
312 } else {
313 context.requestMutex.Lock()
314 defer context.requestMutex.Unlock()
315 context.requests[key] = true
316 return "", false
317 }
318}
319
320func pwdPrefix() string {
321 // Darwin doesn't have /proc
322 if runtime.GOOS != "darwin" {
323 return "PWD=/proc/self/cwd"
324 }
325 return ""
326}
327
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400328type bazelCommand struct {
329 command string
330 // query or label
331 expression string
332}
333
334type mockBazelRunner struct {
335 bazelCommandResults map[bazelCommand]string
336 commands []bazelCommand
337}
338
339func (r *mockBazelRunner) issueBazelCommand(paths *bazelPaths,
340 runName bazel.RunName,
341 command bazelCommand,
342 extraFlags ...string) (string, string, error) {
343 r.commands = append(r.commands, command)
344 if ret, ok := r.bazelCommandResults[command]; ok {
345 return ret, "", nil
346 }
347 return "", "", nil
348}
349
350type builtinBazelRunner struct{}
351
Chris Parsons808d84c2021-03-09 20:43:32 -0500352// Issues the given bazel command with given build label and additional flags.
353// Returns (stdout, stderr, error). The first and second return values are strings
354// containing the stdout and stderr of the run command, and an error is returned if
355// the invocation returned an error code.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400356func (r *builtinBazelRunner) issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Chris Parsons808d84c2021-03-09 20:43:32 -0500357 extraFlags ...string) (string, string, error) {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000358 cmdFlags := []string{
359 // --noautodetect_server_javabase has the practical consequence of preventing Bazel from
360 // attempting to download rules_java, which is incompatible with
361 // --experimental_repository_disable_download set further below.
362 // rules_java is also not needed until mixed builds start building java targets.
363 // TODO(b/197958133): Once rules_java is pulled into AOSP, remove this flag.
364 "--noautodetect_server_javabase",
365 "--output_base=" + absolutePath(paths.outputBase),
366 command.command,
367 }
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400368 cmdFlags = append(cmdFlags, command.expression)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400369 cmdFlags = append(cmdFlags, "--profile="+shared.BazelMetricsFilename(paths, runName))
Jingwen Chen91220d72021-03-24 02:18:33 -0400370
371 // Set default platforms to canonicalized values for mixed builds requests.
372 // If these are set in the bazelrc, they will have values that are
373 // non-canonicalized to @sourceroot labels, and thus be invalid when
374 // referenced from the buildroot.
375 //
376 // The actual platform values here may be overridden by configuration
377 // transitions from the buildroot.
Chris Parsonsee423b02021-02-08 23:04:59 -0500378 cmdFlags = append(cmdFlags,
Liz Kammerc0c66092021-07-26 17:38:47 -0400379 fmt.Sprintf("--platforms=%s", "//build/bazel/platforms:android_target"))
Chris Parsonsee423b02021-02-08 23:04:59 -0500380 cmdFlags = append(cmdFlags,
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200381 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"))
Jingwen Chen91220d72021-03-24 02:18:33 -0400382 // This should be parameterized on the host OS, but let's restrict to linux
383 // to keep things simple for now.
384 cmdFlags = append(cmdFlags,
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200385 fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"))
Jingwen Chen91220d72021-03-24 02:18:33 -0400386
Chris Parsons8d6e4332021-02-22 16:13:50 -0500387 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
388 cmdFlags = append(cmdFlags, "--experimental_repository_disable_download")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400389 cmdFlags = append(cmdFlags, extraFlags...)
390
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400391 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200392 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200393 bazelCmd.Env = append(os.Environ(),
394 "HOME="+paths.homeDir,
395 pwdPrefix(),
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200396 "BUILD_DIR="+absolutePath(paths.soongOutDir),
Jingwen Chen8c523582021-06-01 11:19:53 +0000397 // Make OUT_DIR absolute here so tools/bazel.sh uses the correct
398 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
399 "OUT_DIR="+absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500400 // Disables local host detection of gcc; toolchain information is defined
401 // explicitly in BUILD files.
402 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
Colin Crossff0278b2020-10-09 19:24:15 -0700403 stderr := &bytes.Buffer{}
404 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400405
406 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500407 return "", string(stderr.Bytes()),
408 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400409 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500410 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400411 }
412}
413
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400414func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500415 // TODO(cparsons): Define configuration transitions programmatically based
416 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400417 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500418#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400419# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500420#####################################################
421
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400422def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500423 return {
Chris Parsons787fb362021-10-14 18:43:51 -0400424 "//command_line_option:platforms": "@//build/bazel/platforms:%s_%s" % (attr.os, attr.arch),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500425 }
426
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400427_config_node_transition = transition(
428 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500429 inputs = [],
430 outputs = [
431 "//command_line_option:platforms",
432 ],
433)
434
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400435def _passthrough_rule_impl(ctx):
436 return [DefaultInfo(files = depset(ctx.files.deps))]
437
438config_node = rule(
439 implementation = _passthrough_rule_impl,
440 attrs = {
441 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400442 "os" : attr.string(mandatory = True),
443 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400444 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
445 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500446)
447
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400448
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500449# Rule representing the root of the build, to depend on all Bazel targets that
450# are required for the build. Building this target will build the entire Bazel
451# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400452mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400453 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500454 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400455 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500456 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400457)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500458
459def _phony_root_impl(ctx):
460 return []
461
462# Rule to depend on other targets but build nothing.
463# This is useful as follows: building a target of this rule will generate
464# symlink forests for all dependencies of the target, without executing any
465# actions of the build.
466phony_root = rule(
467 implementation = _phony_root_impl,
468 attrs = {"deps" : attr.label_list()},
469)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400470`
471 return []byte(contents)
472}
473
474func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500475 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
476 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400477 formatString := `
478# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400479load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
480
481%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400482
483mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400484 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400485)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500486
487phony_root(name = "phonyroot",
488 deps = [":buildroot"],
489)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400490`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400491 configNodeFormatString := `
492config_node(name = "%s",
493 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400494 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400495 deps = [%s],
496)
497`
498
499 configNodesSection := ""
500
Chris Parsons787fb362021-10-14 18:43:51 -0400501 labelsByConfig := map[string][]string{}
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400502 for val, _ := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200503 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400504 configString := getConfigString(val)
505 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400506 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400507
Jingwen Chen1e347862021-09-02 12:11:49 +0000508 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400509 for configString, labels := range labelsByConfig {
510 configTokens := strings.Split(configString, "|")
511 if len(configTokens) != 2 {
512 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000513 }
Chris Parsons787fb362021-10-14 18:43:51 -0400514 archString := configTokens[0]
515 osString := configTokens[1]
516 targetString := fmt.Sprintf("%s_%s", osString, archString)
517 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
518 labelsString := strings.Join(labels, ",\n ")
519 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400520 }
521
Jingwen Chen1e347862021-09-02 12:11:49 +0000522 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400523}
524
Chris Parsons944e7d02021-03-11 11:08:46 -0500525func indent(original string) string {
526 result := ""
527 for _, line := range strings.Split(original, "\n") {
528 result += " " + line + "\n"
529 }
530 return result
531}
532
Chris Parsons808d84c2021-03-09 20:43:32 -0500533// Returns the file contents of the buildroot.cquery file that should be used for the cquery
534// expression in order to obtain information about buildroot and its dependencies.
535// The contents of this file depend on the bazelContext's requests; requests are enumerated
536// and grouped by their request type. The data retrieved for each label depends on its
537// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400538func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400539 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons944e7d02021-03-11 11:08:46 -0500540 for val, _ := range context.requests {
541 cqueryId := getCqueryId(val)
542 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
543 requestTypeToCqueryIdEntries[val.requestType] =
544 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
545 }
546 labelRegistrationMapSection := ""
547 functionDefSection := ""
548 mainSwitchSection := ""
549
550 mapDeclarationFormatString := `
551%s = {
552 %s
553}
554`
555 functionDefFormatString := `
556def %s(target):
557%s
558`
559 mainSwitchSectionFormatString := `
560 if id_string in %s:
561 return id_string + ">>" + %s(target)
562`
563
Liz Kammer66ffdb72021-04-02 13:26:07 -0400564 for requestType, _ := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500565 labelMapName := requestType.Name() + "_Labels"
566 functionName := requestType.Name() + "_Fn"
567 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
568 labelMapName,
569 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
570 functionDefSection += fmt.Sprintf(functionDefFormatString,
571 functionName,
572 indent(requestType.StarlarkFunctionBody()))
573 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
574 labelMapName, functionName)
575 }
576
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400577 formatString := `
578# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400579
Chris Parsons944e7d02021-03-11 11:08:46 -0500580# Label Map Section
581%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500582
Chris Parsons944e7d02021-03-11 11:08:46 -0500583# Function Def Section
584%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500585
586def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400587 # TODO(b/199363072): filegroups and file targets aren't associated with any
588 # specific platform architecture in mixed builds. This is consistent with how
589 # Soong treats filegroups, but it may not be the case with manually-written
590 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500591 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000592 if buildoptions == None:
593 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400594 # any specific platform architecture in mixed builds, so use the host.
595 return "x86_64|linux"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500596 platforms = build_options(target)["//command_line_option:platforms"]
597 if len(platforms) != 1:
598 # An individual configured target should have only one platform architecture.
599 # Note that it's fine for there to be multiple architectures for the same label,
600 # but each is its own configured target.
601 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
602 platform_name = build_options(target)["//command_line_option:platforms"][0].name
603 if platform_name == "host":
604 return "HOST"
Chris Parsons787fb362021-10-14 18:43:51 -0400605 elif platform_name.startswith("linux_glibc_"):
606 return platform_name[len("linux_glibc_"):] + "|" + platform_name[:len("linux_glibc_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400607 elif platform_name.startswith("android_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400608 return platform_name[len("android_"):] + "|" + platform_name[:len("android_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400609 elif platform_name.startswith("linux_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400610 return platform_name[len("linux_"):] + "|" + platform_name[:len("linux_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400611 else:
612 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500613 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500614
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400615def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500616 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500617
618 # Main switch section
619 %s
620 # This target was not requested via cquery, and thus must be a dependency
621 # of a requested target.
622 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400623`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400624
Chris Parsons944e7d02021-03-11 11:08:46 -0500625 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
626 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400627}
628
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200629// Returns a path containing build-related metadata required for interfacing
630// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400631func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200632 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500633}
634
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200635// Returns the path where the contents of the @soong_injection repository live.
636// It is used by Soong to tell Bazel things it cannot over the command line.
637func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200638 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200639}
640
641// Returns the path of the synthetic Bazel workspace that contains a symlink
642// forest composed the whole source tree and BUILD files generated by bp2build.
643func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200644 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200645}
646
Jingwen Chen8c523582021-06-01 11:19:53 +0000647// Returns the path to the top level out dir ($OUT_DIR).
648func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200649 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000650}
651
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400652// Issues commands to Bazel to receive results for all cquery requests
653// queued in the BazelContext.
654func (context *bazelContext) InvokeBazel() error {
655 context.results = make(map[cqueryKey]string)
656
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400657 var cqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500658 var cqueryErr string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400659 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500660
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200661 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200662 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
663 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
664 err = os.MkdirAll(mixedBuildsPath, 0777)
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500665 }
Chris Parsons8ccdb632020-11-17 15:41:01 -0500666 if err != nil {
667 return err
668 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200669
670 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666)
671 if err != nil {
672 return err
673 }
674
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400675 err = ioutil.WriteFile(
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200676 filepath.Join(mixedBuildsPath, "main.bzl"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400677 context.mainBzlFileContents(), 0666)
678 if err != nil {
679 return err
680 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200681
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400682 err = ioutil.WriteFile(
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200683 filepath.Join(mixedBuildsPath, "BUILD.bazel"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400684 context.mainBuildFileContents(), 0666)
685 if err != nil {
686 return err
687 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200688 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400689 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800690 absolutePath(cqueryFileRelpath),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400691 context.cqueryStarlarkFileContents(), 0666)
692 if err != nil {
693 return err
694 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000695
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200696 buildrootLabel := "@soong_injection//mixed_builds:buildroot"
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400697 cqueryOutput, cqueryErr, err = context.issueBazelCommand(
698 context.paths,
699 bazel.CqueryBuildRootRunName,
Liz Kammerc19d5cd2021-10-06 18:16:58 -0400700 bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)},
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400701 "--output=starlark",
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200702 "--starlark:file="+absolutePath(cqueryFileRelpath))
703 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500704 []byte(cqueryOutput), 0666)
705 if err != nil {
706 return err
707 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400708
709 if err != nil {
710 return err
711 }
712
713 cqueryResults := map[string]string{}
714 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
715 if strings.Contains(outputLine, ">>") {
716 splitLine := strings.SplitN(outputLine, ">>", 2)
717 cqueryResults[splitLine[0]] = splitLine[1]
718 }
719 }
720
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400721 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500722 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400723 context.results[val] = string(cqueryResult)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400724 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500725 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
726 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400727 }
728 }
729
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500730 // Issue an aquery command to retrieve action information about the bazel build tree.
731 //
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400732 // TODO(cparsons): Use --target_pattern_file to avoid command line limits.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500733 var aqueryOutput string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400734 aqueryOutput, _, err = context.issueBazelCommand(
735 context.paths,
736 bazel.AqueryBuildRootRunName,
737 bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)},
738 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
739 // proto sources, which would add a number of unnecessary dependencies.
740 "--output=jsonproto")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400741
742 if err != nil {
743 return err
744 }
745
Chris Parsons4f069892021-01-15 12:22:41 -0500746 context.buildStatements, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
747 if err != nil {
748 return err
749 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500750
751 // Issue a build command of the phony root to generate symlink forests for dependencies of the
752 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
753 // but some of symlinks may be required to resolve source dependencies of the build.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400754 _, _, err = context.issueBazelCommand(
755 context.paths,
756 bazel.BazelBuildPhonyRootRunName,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200757 bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"})
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500758
759 if err != nil {
760 return err
761 }
762
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400763 // Clear requests.
764 context.requests = map[cqueryKey]bool{}
765 return nil
766}
Chris Parsonsa798d962020-10-12 23:44:08 -0400767
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500768func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
769 return context.buildStatements
770}
771
772func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400773 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500774}
775
Chris Parsonsa798d962020-10-12 23:44:08 -0400776// Singleton used for registering BUILD file ninja dependencies (needed
777// for correctness of builds which use Bazel.
778func BazelSingleton() Singleton {
779 return &bazelSingleton{}
780}
781
782type bazelSingleton struct{}
783
784func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500785 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
786 if !ctx.Config().BazelContext.BazelEnabled() {
787 return
788 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400789
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500790 // Add ninja file dependencies for files which all bazel invocations require.
791 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200792 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500793 ctx.AddNinjaFileDeps(bazelBuildList)
794
795 data, err := ioutil.ReadFile(bazelBuildList)
796 if err != nil {
797 ctx.Errorf(err.Error())
798 }
799 files := strings.Split(strings.TrimSpace(string(data)), "\n")
800 for _, file := range files {
801 ctx.AddNinjaFileDeps(file)
802 }
803
804 // Register bazel-owned build statements (obtained from the aquery invocation).
805 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500806 if len(buildStatement.Command) < 1 {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000807 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500808 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500809 rule := NewRuleBuilder(pctx, ctx)
810 cmd := rule.Command()
Chris Parsons94a0bba2021-06-04 15:03:47 -0400811
812 // cd into Bazel's execution root, which is the action cwd.
Chris Parsonse37a4de2021-09-23 17:10:50 -0400813 cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ &&", ctx.Config().BazelContext.OutputBase()))
814
815 // Remove old outputs, as some actions might not rerun if the outputs are detected.
816 if len(buildStatement.OutputPaths) > 0 {
817 cmd.Text("rm -f")
818 for _, outputPath := range buildStatement.OutputPaths {
Liz Kammerd7d5b722021-10-01 10:33:12 -0400819 cmd.Text(outputPath)
Chris Parsonse37a4de2021-09-23 17:10:50 -0400820 }
821 cmd.Text("&&")
822 }
Chris Parsons94a0bba2021-06-04 15:03:47 -0400823
824 for _, pair := range buildStatement.Env {
825 // Set per-action env variables, if any.
826 cmd.Flag(pair.Key + "=" + pair.Value)
827 }
828
829 // The actual Bazel action.
830 cmd.Text(" " + buildStatement.Command)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500831
832 for _, outputPath := range buildStatement.OutputPaths {
833 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400834 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500835 for _, inputPath := range buildStatement.InputPaths {
836 cmd.Implicit(PathForBazelOut(ctx, inputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400837 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500838
Liz Kammerde116852021-03-25 16:42:37 -0400839 if depfile := buildStatement.Depfile; depfile != nil {
840 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
841 }
842
Liz Kammerc49e6822021-06-08 15:04:11 -0400843 for _, symlinkPath := range buildStatement.SymlinkPaths {
844 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
845 }
846
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500847 // This is required to silence warnings pertaining to unexpected timestamps. Particularly,
848 // some Bazel builtins (such as files in the bazel_tools directory) have far-future
849 // timestamps. Without restat, Ninja would emit warnings that the input files of a
850 // build statement have later timestamps than the outputs.
851 rule.Restat()
852
Liz Kammer13548d72020-12-16 11:13:30 -0800853 rule.Build(fmt.Sprintf("bazel %d", index), buildStatement.Mnemonic)
Chris Parsonsa798d962020-10-12 23:44:08 -0400854 }
855}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500856
857func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -0400858 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500859}
860
Chris Parsons787fb362021-10-14 18:43:51 -0400861func getConfigString(key cqueryKey) string {
862 arch := key.configKey.archType.Name
863 if len(arch) == 0 || arch == "common" {
864 // Use host platform, which is currently hardcoded to be x86_64.
865 arch = "x86_64"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500866 }
Chris Parsons787fb362021-10-14 18:43:51 -0400867 os := key.configKey.osType.Name
868 if len(os) == 0 || os == "common_os" {
869 // Use host OS, which is currently hardcoded to be linux.
870 os = "linux"
871 }
872 return arch + "|" + os
873}
874
875func GetConfigKey(ctx ModuleContext) configKey {
876 return configKey{archType: ctx.Arch().ArchType, osType: ctx.Os()}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500877}