blob: d851a98bda0c72f344b4f1c1b6194cdaf8a85b99 [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 {
Liz Kammer0940b892022-03-18 15:55:04 -040053 arch string
54 osType OsType
Chris Parsons787fb362021-10-14 18:43:51 -040055}
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 {
Usta Shrestha0b52d832022-02-04 21:37:39 -050076 // The methods below involve queuing cquery requests to be later invoked
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040077 // 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
Usta Shrestha0b52d832022-02-04 21:37:39 -0500564 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 Parsons94a0bba2021-06-04 15:03:47 -0400605 elif platform_name.startswith("android_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400606 return platform_name[len("android_"):] + "|" + platform_name[:len("android_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400607 elif platform_name.startswith("linux_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400608 return platform_name[len("linux_"):] + "|" + platform_name[:len("linux_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400609 else:
610 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500611 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500612
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400613def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500614 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500615
616 # Main switch section
617 %s
618 # This target was not requested via cquery, and thus must be a dependency
619 # of a requested target.
620 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400621`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400622
Chris Parsons944e7d02021-03-11 11:08:46 -0500623 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
624 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400625}
626
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200627// Returns a path containing build-related metadata required for interfacing
628// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400629func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200630 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500631}
632
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200633// Returns the path where the contents of the @soong_injection repository live.
634// It is used by Soong to tell Bazel things it cannot over the command line.
635func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200636 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200637}
638
639// Returns the path of the synthetic Bazel workspace that contains a symlink
640// forest composed the whole source tree and BUILD files generated by bp2build.
641func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200642 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200643}
644
Jingwen Chen8c523582021-06-01 11:19:53 +0000645// Returns the path to the top level out dir ($OUT_DIR).
646func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200647 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000648}
649
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400650// Issues commands to Bazel to receive results for all cquery requests
651// queued in the BazelContext.
652func (context *bazelContext) InvokeBazel() error {
653 context.results = make(map[cqueryKey]string)
654
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400655 var cqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500656 var cqueryErr string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400657 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500658
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200659 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200660 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
661 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
662 err = os.MkdirAll(mixedBuildsPath, 0777)
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500663 }
Chris Parsons8ccdb632020-11-17 15:41:01 -0500664 if err != nil {
665 return err
666 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500667 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
668 err = os.MkdirAll(metricsDir, 0777)
669 if err != nil {
670 return err
671 }
672 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200673 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666)
674 if err != nil {
675 return err
676 }
677
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400678 err = ioutil.WriteFile(
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200679 filepath.Join(mixedBuildsPath, "main.bzl"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400680 context.mainBzlFileContents(), 0666)
681 if err != nil {
682 return err
683 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200684
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400685 err = ioutil.WriteFile(
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200686 filepath.Join(mixedBuildsPath, "BUILD.bazel"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400687 context.mainBuildFileContents(), 0666)
688 if err != nil {
689 return err
690 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200691 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400692 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800693 absolutePath(cqueryFileRelpath),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400694 context.cqueryStarlarkFileContents(), 0666)
695 if err != nil {
696 return err
697 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000698
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200699 buildrootLabel := "@soong_injection//mixed_builds:buildroot"
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400700 cqueryOutput, cqueryErr, err = context.issueBazelCommand(
701 context.paths,
702 bazel.CqueryBuildRootRunName,
Liz Kammerc19d5cd2021-10-06 18:16:58 -0400703 bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)},
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400704 "--output=starlark",
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200705 "--starlark:file="+absolutePath(cqueryFileRelpath))
706 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500707 []byte(cqueryOutput), 0666)
708 if err != nil {
709 return err
710 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400711
712 if err != nil {
713 return err
714 }
715
716 cqueryResults := map[string]string{}
717 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
718 if strings.Contains(outputLine, ">>") {
719 splitLine := strings.SplitN(outputLine, ">>", 2)
720 cqueryResults[splitLine[0]] = splitLine[1]
721 }
722 }
723
Usta Shrestha902fd172022-03-02 15:27:49 -0500724 for val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500725 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -0500726 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400727 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500728 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
729 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400730 }
731 }
732
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500733 // Issue an aquery command to retrieve action information about the bazel build tree.
734 //
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400735 // TODO(cparsons): Use --target_pattern_file to avoid command line limits.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500736 var aqueryOutput string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400737 aqueryOutput, _, err = context.issueBazelCommand(
738 context.paths,
739 bazel.AqueryBuildRootRunName,
740 bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)},
741 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
742 // proto sources, which would add a number of unnecessary dependencies.
743 "--output=jsonproto")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400744
745 if err != nil {
746 return err
747 }
748
Chris Parsons4f069892021-01-15 12:22:41 -0500749 context.buildStatements, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
750 if err != nil {
751 return err
752 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500753
754 // Issue a build command of the phony root to generate symlink forests for dependencies of the
755 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
756 // but some of symlinks may be required to resolve source dependencies of the build.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400757 _, _, err = context.issueBazelCommand(
758 context.paths,
759 bazel.BazelBuildPhonyRootRunName,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200760 bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"})
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500761
762 if err != nil {
763 return err
764 }
765
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400766 // Clear requests.
767 context.requests = map[cqueryKey]bool{}
768 return nil
769}
Chris Parsonsa798d962020-10-12 23:44:08 -0400770
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500771func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
772 return context.buildStatements
773}
774
775func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400776 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500777}
778
Chris Parsonsa798d962020-10-12 23:44:08 -0400779// Singleton used for registering BUILD file ninja dependencies (needed
780// for correctness of builds which use Bazel.
781func BazelSingleton() Singleton {
782 return &bazelSingleton{}
783}
784
785type bazelSingleton struct{}
786
787func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500788 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
789 if !ctx.Config().BazelContext.BazelEnabled() {
790 return
791 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400792
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500793 // Add ninja file dependencies for files which all bazel invocations require.
794 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200795 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500796 ctx.AddNinjaFileDeps(bazelBuildList)
797
798 data, err := ioutil.ReadFile(bazelBuildList)
799 if err != nil {
800 ctx.Errorf(err.Error())
801 }
802 files := strings.Split(strings.TrimSpace(string(data)), "\n")
803 for _, file := range files {
804 ctx.AddNinjaFileDeps(file)
805 }
806
807 // Register bazel-owned build statements (obtained from the aquery invocation).
808 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500809 if len(buildStatement.Command) < 1 {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000810 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500811 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500812 rule := NewRuleBuilder(pctx, ctx)
813 cmd := rule.Command()
Chris Parsons94a0bba2021-06-04 15:03:47 -0400814
815 // cd into Bazel's execution root, which is the action cwd.
Chris Parsonse37a4de2021-09-23 17:10:50 -0400816 cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ &&", ctx.Config().BazelContext.OutputBase()))
817
818 // Remove old outputs, as some actions might not rerun if the outputs are detected.
819 if len(buildStatement.OutputPaths) > 0 {
820 cmd.Text("rm -f")
821 for _, outputPath := range buildStatement.OutputPaths {
Liz Kammerd7d5b722021-10-01 10:33:12 -0400822 cmd.Text(outputPath)
Chris Parsonse37a4de2021-09-23 17:10:50 -0400823 }
824 cmd.Text("&&")
825 }
Chris Parsons94a0bba2021-06-04 15:03:47 -0400826
827 for _, pair := range buildStatement.Env {
828 // Set per-action env variables, if any.
829 cmd.Flag(pair.Key + "=" + pair.Value)
830 }
831
832 // The actual Bazel action.
833 cmd.Text(" " + buildStatement.Command)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500834
835 for _, outputPath := range buildStatement.OutputPaths {
836 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400837 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500838 for _, inputPath := range buildStatement.InputPaths {
839 cmd.Implicit(PathForBazelOut(ctx, inputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400840 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500841
Liz Kammerde116852021-03-25 16:42:37 -0400842 if depfile := buildStatement.Depfile; depfile != nil {
843 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
844 }
845
Liz Kammerc49e6822021-06-08 15:04:11 -0400846 for _, symlinkPath := range buildStatement.SymlinkPaths {
847 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
848 }
849
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500850 // This is required to silence warnings pertaining to unexpected timestamps. Particularly,
851 // some Bazel builtins (such as files in the bazel_tools directory) have far-future
852 // timestamps. Without restat, Ninja would emit warnings that the input files of a
853 // build statement have later timestamps than the outputs.
854 rule.Restat()
855
Liz Kammer13548d72020-12-16 11:13:30 -0800856 rule.Build(fmt.Sprintf("bazel %d", index), buildStatement.Mnemonic)
Chris Parsonsa798d962020-10-12 23:44:08 -0400857 }
858}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500859
860func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -0400861 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500862}
863
Chris Parsons787fb362021-10-14 18:43:51 -0400864func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -0400865 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -0400866 if len(arch) == 0 || arch == "common" {
867 // Use host platform, which is currently hardcoded to be x86_64.
868 arch = "x86_64"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500869 }
Chris Parsons787fb362021-10-14 18:43:51 -0400870 os := key.configKey.osType.Name
Chris Parsons494eef32021-11-09 10:29:52 -0500871 if len(os) == 0 || os == "common_os" || os == "linux_glibc" {
Chris Parsons787fb362021-10-14 18:43:51 -0400872 // Use host OS, which is currently hardcoded to be linux.
873 os = "linux"
874 }
875 return arch + "|" + os
876}
877
878func GetConfigKey(ctx ModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -0400879 return configKey{
880 // use string because Arch is not a valid key in go
881 arch: ctx.Arch().String(),
882 osType: ctx.Os(),
883 }
Chris Parsons8d6e4332021-02-22 16:13:50 -0500884}