blob: 9c922dda47b169d7bc903846ff90efaffe6daa23 [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"
Liz Kammer8206d4f2021-03-03 16:40:52 -050030
Patrice Arruda05ab2d02020-12-12 06:24:26 +000031 "android/soong/bazel"
32 "android/soong/shared"
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 Parsonsf3c96ef2020-09-29 02:23:17 -040051// Map key to describe bazel cquery requests.
52type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040053 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -040054 requestType cqueryRequest
Chris Parsons8d6e4332021-02-22 16:13:50 -050055 archType ArchType
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040056}
57
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux0d990452021-08-11 16:46:13 +000058// bazelHandler is the interface for a helper object related to deferring to Bazel for
59// processing a module (during Bazel mixed builds). Individual module types should define
60// their own bazel handler if they support deferring to Bazel.
61type BazelHandler interface {
62 // Issue query to Bazel to retrieve information about Bazel's view of the current module.
63 // If Bazel returns this information, set module properties on the current module to reflect
64 // the returned information.
65 // Returns true if information was available from Bazel, false if bazel invocation still needs to occur.
66 GenerateBazelBuildActions(ctx ModuleContext, label string) bool
67}
68
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040069type BazelContext interface {
70 // The below methods involve queuing cquery requests to be later invoked
71 // by bazel. If any of these methods return (_, false), then the request
72 // has been queued to be run later.
73
74 // Returns result files built by building the given bazel target label.
Chris Parsons944e7d02021-03-11 11:08:46 -050075 GetOutputFiles(label string, archType ArchType) ([]string, bool)
Chris Parsons8d6e4332021-02-22 16:13:50 -050076
Chris Parsons944e7d02021-03-11 11:08:46 -050077 // TODO(cparsons): Other cquery-related methods should be added here.
78 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Liz Kammerfe23bf32021-04-09 16:17:05 -040079 GetCcInfo(label string, archType ArchType) (cquery.CcInfo, bool, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -040080
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +000081 // Returns the executable binary resultant from building together the python sources
82 GetPythonBinary(label string, archType ArchType) (string, bool)
83
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040084 // ** End cquery methods
85
86 // Issues commands to Bazel to receive results for all cquery requests
87 // queued in the BazelContext.
88 InvokeBazel() error
89
90 // Returns true if bazel is enabled for the given configuration.
91 BazelEnabled() bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050092
93 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
94 OutputBase() string
95
96 // Returns build statements which should get registered to reflect Bazel's outputs.
97 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040098}
99
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400100type bazelRunner interface {
101 issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) (string, string, error)
102}
103
104type bazelPaths struct {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400105 homeDir string
106 bazelPath string
107 outputBase string
108 workspaceDir string
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200109 soongOutDir string
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000110 metricsDir string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400111}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400112
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400113// A context object which tracks queued requests that need to be made to Bazel,
114// and their results after the requests have been made.
115type bazelContext struct {
116 bazelRunner
117 paths *bazelPaths
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400118 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
119 requestMutex sync.Mutex // requests can be written in parallel
120
121 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500122
123 // Build statements which should get registered to reflect Bazel's outputs.
124 buildStatements []bazel.BuildStatement
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400125}
126
127var _ BazelContext = &bazelContext{}
128
129// A bazel context to use when Bazel is disabled.
130type noopBazelContext struct{}
131
132var _ BazelContext = noopBazelContext{}
133
134// A bazel context to use for tests.
135type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400136 OutputBaseDir string
137
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000138 LabelToOutputFiles map[string][]string
139 LabelToCcInfo map[string]cquery.CcInfo
140 LabelToPythonBinary map[string]string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400141}
142
Chris Parsons944e7d02021-03-11 11:08:46 -0500143func (m MockBazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
Liz Kammera92e8442021-04-07 20:25:21 -0400144 result, ok := m.LabelToOutputFiles[label]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500145 return result, ok
146}
147
Liz Kammerfe23bf32021-04-09 16:17:05 -0400148func (m MockBazelContext) GetCcInfo(label string, archType ArchType) (cquery.CcInfo, bool, error) {
Liz Kammerb71794d2021-04-09 14:07:00 -0400149 result, ok := m.LabelToCcInfo[label]
Liz Kammerfe23bf32021-04-09 16:17:05 -0400150 return result, ok, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400151}
152
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000153func (m MockBazelContext) GetPythonBinary(label string, archType ArchType) (string, bool) {
154 result, ok := m.LabelToPythonBinary[label]
155 return result, ok
156}
157
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400158func (m MockBazelContext) InvokeBazel() error {
159 panic("unimplemented")
160}
161
162func (m MockBazelContext) BazelEnabled() bool {
163 return true
164}
165
Liz Kammera92e8442021-04-07 20:25:21 -0400166func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500167
168func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
169 return []bazel.BuildStatement{}
170}
171
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400172var _ BazelContext = MockBazelContext{}
173
Chris Parsons944e7d02021-03-11 11:08:46 -0500174func (bazelCtx *bazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
175 rawString, ok := bazelCtx.cquery(label, cquery.GetOutputFiles, archType)
176 var ret []string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400177 if ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500178 bazelOutput := strings.TrimSpace(rawString)
Liz Kammerf29df7c2021-04-02 13:37:39 -0400179 ret = cquery.GetOutputFiles.ParseResult(bazelOutput)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400180 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500181 return ret, ok
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400182}
183
Liz Kammerfe23bf32021-04-09 16:17:05 -0400184func (bazelCtx *bazelContext) GetCcInfo(label string, archType ArchType) (cquery.CcInfo, bool, error) {
Liz Kammerb71794d2021-04-09 14:07:00 -0400185 result, ok := bazelCtx.cquery(label, cquery.GetCcInfo, archType)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400186 if !ok {
Liz Kammerfe23bf32021-04-09 16:17:05 -0400187 return cquery.CcInfo{}, ok, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400188 }
189
190 bazelOutput := strings.TrimSpace(result)
Liz Kammerfe23bf32021-04-09 16:17:05 -0400191 ret, err := cquery.GetCcInfo.ParseResult(bazelOutput)
192 return ret, ok, err
Liz Kammer3f9e1552021-04-02 18:47:09 -0400193}
194
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000195func (bazelCtx *bazelContext) GetPythonBinary(label string, archType ArchType) (string, bool) {
196 rawString, ok := bazelCtx.cquery(label, cquery.GetPythonBinary, archType)
197 var ret string
198 if ok {
199 bazelOutput := strings.TrimSpace(rawString)
200 ret = cquery.GetPythonBinary.ParseResult(bazelOutput)
201 }
202 return ret, ok
203}
204
Chris Parsons944e7d02021-03-11 11:08:46 -0500205func (n noopBazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500206 panic("unimplemented")
207}
208
Liz Kammerfe23bf32021-04-09 16:17:05 -0400209func (n noopBazelContext) GetCcInfo(label string, archType ArchType) (cquery.CcInfo, bool, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500210 panic("unimplemented")
211}
212
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000213func (n noopBazelContext) GetPythonBinary(label string, archType ArchType) (string, bool) {
214 panic("unimplemented")
215}
216
Liz Kammer3f9e1552021-04-02 18:47:09 -0400217func (n noopBazelContext) GetPrebuiltCcStaticLibraryFiles(label string, archType ArchType) ([]string, bool) {
218 panic("unimplemented")
219}
220
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400221func (n noopBazelContext) InvokeBazel() error {
222 panic("unimplemented")
223}
224
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500225func (m noopBazelContext) OutputBase() string {
226 return ""
227}
228
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400229func (n noopBazelContext) BazelEnabled() bool {
230 return false
231}
232
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500233func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
234 return []bazel.BuildStatement{}
235}
236
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400237func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons8b77a002020-10-27 18:59:25 -0400238 // TODO(cparsons): Assess USE_BAZEL=1 instead once "mixed Soong/Bazel builds"
239 // are production ready.
Jingwen Chen442b1a42021-06-17 07:02:15 +0000240 if !c.IsEnvTrue("USE_BAZEL_ANALYSIS") {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400241 return noopBazelContext{}, nil
242 }
243
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400244 p, err := bazelPathsFromConfig(c)
245 if err != nil {
246 return nil, err
247 }
248 return &bazelContext{
249 bazelRunner: &builtinBazelRunner{},
250 paths: p,
251 requests: make(map[cqueryKey]bool),
252 }, nil
253}
254
255func bazelPathsFromConfig(c *config) (*bazelPaths, error) {
256 p := bazelPaths{
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200257 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400258 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400259 missingEnvVars := []string{}
260 if len(c.Getenv("BAZEL_HOME")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400261 p.homeDir = c.Getenv("BAZEL_HOME")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400262 } else {
263 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
264 }
265 if len(c.Getenv("BAZEL_PATH")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400266 p.bazelPath = c.Getenv("BAZEL_PATH")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400267 } else {
268 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
269 }
270 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400271 p.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400272 } else {
273 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
274 }
275 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400276 p.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400277 } else {
278 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
279 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000280 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400281 p.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000282 } else {
283 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
284 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400285 if len(missingEnvVars) > 0 {
286 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
287 } else {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400288 return &p, nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400289 }
290}
291
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400292func (p *bazelPaths) BazelMetricsDir() string {
293 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000294}
295
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400296func (context *bazelContext) BazelEnabled() bool {
297 return true
298}
299
300// Adds a cquery request to the Bazel request queue, to be later invoked, or
301// returns the result of the given request if the request was already made.
302// If the given request was already made (and the results are available), then
303// returns (result, true). If the request is queued but no results are available,
304// then returns ("", false).
Liz Kammerf29df7c2021-04-02 13:37:39 -0400305func (context *bazelContext) cquery(label string, requestType cqueryRequest,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500306 archType ArchType) (string, bool) {
307 key := cqueryKey{label, requestType, archType}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400308 if result, ok := context.results[key]; ok {
309 return result, true
310 } else {
311 context.requestMutex.Lock()
312 defer context.requestMutex.Unlock()
313 context.requests[key] = true
314 return "", false
315 }
316}
317
318func pwdPrefix() string {
319 // Darwin doesn't have /proc
320 if runtime.GOOS != "darwin" {
321 return "PWD=/proc/self/cwd"
322 }
323 return ""
324}
325
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400326type bazelCommand struct {
327 command string
328 // query or label
329 expression string
330}
331
332type mockBazelRunner struct {
333 bazelCommandResults map[bazelCommand]string
334 commands []bazelCommand
335}
336
337func (r *mockBazelRunner) issueBazelCommand(paths *bazelPaths,
338 runName bazel.RunName,
339 command bazelCommand,
340 extraFlags ...string) (string, string, error) {
341 r.commands = append(r.commands, command)
342 if ret, ok := r.bazelCommandResults[command]; ok {
343 return ret, "", nil
344 }
345 return "", "", nil
346}
347
348type builtinBazelRunner struct{}
349
Chris Parsons808d84c2021-03-09 20:43:32 -0500350// Issues the given bazel command with given build label and additional flags.
351// Returns (stdout, stderr, error). The first and second return values are strings
352// containing the stdout and stderr of the run command, and an error is returned if
353// the invocation returned an error code.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400354func (r *builtinBazelRunner) issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Chris Parsons808d84c2021-03-09 20:43:32 -0500355 extraFlags ...string) (string, string, error) {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000356 cmdFlags := []string{
357 // --noautodetect_server_javabase has the practical consequence of preventing Bazel from
358 // attempting to download rules_java, which is incompatible with
359 // --experimental_repository_disable_download set further below.
360 // rules_java is also not needed until mixed builds start building java targets.
361 // TODO(b/197958133): Once rules_java is pulled into AOSP, remove this flag.
362 "--noautodetect_server_javabase",
363 "--output_base=" + absolutePath(paths.outputBase),
364 command.command,
365 }
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400366 cmdFlags = append(cmdFlags, command.expression)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400367 cmdFlags = append(cmdFlags, "--profile="+shared.BazelMetricsFilename(paths, runName))
Jingwen Chen91220d72021-03-24 02:18:33 -0400368
369 // Set default platforms to canonicalized values for mixed builds requests.
370 // If these are set in the bazelrc, they will have values that are
371 // non-canonicalized to @sourceroot labels, and thus be invalid when
372 // referenced from the buildroot.
373 //
374 // The actual platform values here may be overridden by configuration
375 // transitions from the buildroot.
Chris Parsonsee423b02021-02-08 23:04:59 -0500376 cmdFlags = append(cmdFlags,
Liz Kammerc0c66092021-07-26 17:38:47 -0400377 fmt.Sprintf("--platforms=%s", "//build/bazel/platforms:android_target"))
Chris Parsonsee423b02021-02-08 23:04:59 -0500378 cmdFlags = append(cmdFlags,
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200379 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"))
Jingwen Chen91220d72021-03-24 02:18:33 -0400380 // This should be parameterized on the host OS, but let's restrict to linux
381 // to keep things simple for now.
382 cmdFlags = append(cmdFlags,
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200383 fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"))
Jingwen Chen91220d72021-03-24 02:18:33 -0400384
Chris Parsons8d6e4332021-02-22 16:13:50 -0500385 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
386 cmdFlags = append(cmdFlags, "--experimental_repository_disable_download")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400387 cmdFlags = append(cmdFlags, extraFlags...)
388
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400389 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200390 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200391 bazelCmd.Env = append(os.Environ(),
392 "HOME="+paths.homeDir,
393 pwdPrefix(),
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200394 "BUILD_DIR="+absolutePath(paths.soongOutDir),
Jingwen Chen8c523582021-06-01 11:19:53 +0000395 // Make OUT_DIR absolute here so tools/bazel.sh uses the correct
396 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
397 "OUT_DIR="+absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500398 // Disables local host detection of gcc; toolchain information is defined
399 // explicitly in BUILD files.
400 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
Colin Crossff0278b2020-10-09 19:24:15 -0700401 stderr := &bytes.Buffer{}
402 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400403
404 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500405 return "", string(stderr.Bytes()),
406 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400407 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500408 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400409 }
410}
411
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400412func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500413 // TODO(cparsons): Define configuration transitions programmatically based
414 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400415 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500416#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400417# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500418#####################################################
419
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400420def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500421 return {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200422 "//command_line_option:platforms": "@//build/bazel/platforms:android_%s" % attr.arch,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500423 }
424
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400425_config_node_transition = transition(
426 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500427 inputs = [],
428 outputs = [
429 "//command_line_option:platforms",
430 ],
431)
432
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400433def _passthrough_rule_impl(ctx):
434 return [DefaultInfo(files = depset(ctx.files.deps))]
435
436config_node = rule(
437 implementation = _passthrough_rule_impl,
438 attrs = {
439 "arch" : attr.string(mandatory = True),
440 "deps" : attr.label_list(cfg = _config_node_transition),
441 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
442 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500443)
444
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400445
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500446# Rule representing the root of the build, to depend on all Bazel targets that
447# are required for the build. Building this target will build the entire Bazel
448# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400449mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400450 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500451 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400452 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500453 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400454)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500455
456def _phony_root_impl(ctx):
457 return []
458
459# Rule to depend on other targets but build nothing.
460# This is useful as follows: building a target of this rule will generate
461# symlink forests for all dependencies of the target, without executing any
462# actions of the build.
463phony_root = rule(
464 implementation = _phony_root_impl,
465 attrs = {"deps" : attr.label_list()},
466)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400467`
468 return []byte(contents)
469}
470
471func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500472 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
473 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400474 formatString := `
475# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400476load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
477
478%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400479
480mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400481 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400482)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500483
484phony_root(name = "phonyroot",
485 deps = [":buildroot"],
486)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400487`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400488 configNodeFormatString := `
489config_node(name = "%s",
490 arch = "%s",
491 deps = [%s],
492)
493`
494
495 configNodesSection := ""
496
497 labelsByArch := map[string][]string{}
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400498 for val, _ := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200499 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400500 archString := getArchString(val)
501 labelsByArch[archString] = append(labelsByArch[archString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400502 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400503
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400504 configNodeLabels := []string{}
505 for archString, labels := range labelsByArch {
506 configNodeLabels = append(configNodeLabels, fmt.Sprintf("\":%s\"", archString))
507 labelsString := strings.Join(labels, ",\n ")
508 configNodesSection += fmt.Sprintf(configNodeFormatString, archString, archString, labelsString)
509 }
510
511 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(configNodeLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400512}
513
Chris Parsons944e7d02021-03-11 11:08:46 -0500514func indent(original string) string {
515 result := ""
516 for _, line := range strings.Split(original, "\n") {
517 result += " " + line + "\n"
518 }
519 return result
520}
521
Chris Parsons808d84c2021-03-09 20:43:32 -0500522// Returns the file contents of the buildroot.cquery file that should be used for the cquery
523// expression in order to obtain information about buildroot and its dependencies.
524// The contents of this file depend on the bazelContext's requests; requests are enumerated
525// and grouped by their request type. The data retrieved for each label depends on its
526// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400527func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400528 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons944e7d02021-03-11 11:08:46 -0500529 for val, _ := range context.requests {
530 cqueryId := getCqueryId(val)
531 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
532 requestTypeToCqueryIdEntries[val.requestType] =
533 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
534 }
535 labelRegistrationMapSection := ""
536 functionDefSection := ""
537 mainSwitchSection := ""
538
539 mapDeclarationFormatString := `
540%s = {
541 %s
542}
543`
544 functionDefFormatString := `
545def %s(target):
546%s
547`
548 mainSwitchSectionFormatString := `
549 if id_string in %s:
550 return id_string + ">>" + %s(target)
551`
552
Liz Kammer66ffdb72021-04-02 13:26:07 -0400553 for requestType, _ := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500554 labelMapName := requestType.Name() + "_Labels"
555 functionName := requestType.Name() + "_Fn"
556 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
557 labelMapName,
558 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
559 functionDefSection += fmt.Sprintf(functionDefFormatString,
560 functionName,
561 indent(requestType.StarlarkFunctionBody()))
562 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
563 labelMapName, functionName)
564 }
565
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400566 formatString := `
567# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400568
Chris Parsons944e7d02021-03-11 11:08:46 -0500569# Label Map Section
570%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500571
Chris Parsons944e7d02021-03-11 11:08:46 -0500572# Function Def Section
573%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500574
575def get_arch(target):
576 buildoptions = build_options(target)
577 platforms = build_options(target)["//command_line_option:platforms"]
578 if len(platforms) != 1:
579 # An individual configured target should have only one platform architecture.
580 # Note that it's fine for there to be multiple architectures for the same label,
581 # but each is its own configured target.
582 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
583 platform_name = build_options(target)["//command_line_option:platforms"][0].name
584 if platform_name == "host":
585 return "HOST"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400586 elif platform_name.startswith("android_"):
587 return platform_name[len("android_"):]
588 elif platform_name.startswith("linux_"):
589 return platform_name[len("linux_"):]
590 else:
591 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500592 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500593
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400594def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500595 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500596
597 # Main switch section
598 %s
599 # This target was not requested via cquery, and thus must be a dependency
600 # of a requested target.
601 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400602`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400603
Chris Parsons944e7d02021-03-11 11:08:46 -0500604 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
605 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400606}
607
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200608// Returns a path containing build-related metadata required for interfacing
609// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400610func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200611 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500612}
613
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200614// Returns the path where the contents of the @soong_injection repository live.
615// It is used by Soong to tell Bazel things it cannot over the command line.
616func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200617 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200618}
619
620// Returns the path of the synthetic Bazel workspace that contains a symlink
621// forest composed the whole source tree and BUILD files generated by bp2build.
622func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200623 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200624}
625
Jingwen Chen8c523582021-06-01 11:19:53 +0000626// Returns the path to the top level out dir ($OUT_DIR).
627func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200628 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000629}
630
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400631// Issues commands to Bazel to receive results for all cquery requests
632// queued in the BazelContext.
633func (context *bazelContext) InvokeBazel() error {
634 context.results = make(map[cqueryKey]string)
635
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400636 var cqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500637 var cqueryErr string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400638 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500639
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200640 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200641 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
642 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
643 err = os.MkdirAll(mixedBuildsPath, 0777)
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500644 }
Chris Parsons8ccdb632020-11-17 15:41:01 -0500645 if err != nil {
646 return err
647 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200648
649 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666)
650 if err != nil {
651 return err
652 }
653
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400654 err = ioutil.WriteFile(
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200655 filepath.Join(mixedBuildsPath, "main.bzl"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400656 context.mainBzlFileContents(), 0666)
657 if err != nil {
658 return err
659 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200660
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400661 err = ioutil.WriteFile(
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200662 filepath.Join(mixedBuildsPath, "BUILD.bazel"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400663 context.mainBuildFileContents(), 0666)
664 if err != nil {
665 return err
666 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200667 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400668 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800669 absolutePath(cqueryFileRelpath),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400670 context.cqueryStarlarkFileContents(), 0666)
671 if err != nil {
672 return err
673 }
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200674 buildrootLabel := "@soong_injection//mixed_builds:buildroot"
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400675 cqueryOutput, cqueryErr, err = context.issueBazelCommand(
676 context.paths,
677 bazel.CqueryBuildRootRunName,
678 bazelCommand{"cquery", fmt.Sprintf("kind(rule, deps(%s))", buildrootLabel)},
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400679 "--output=starlark",
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200680 "--starlark:file="+absolutePath(cqueryFileRelpath))
681 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500682 []byte(cqueryOutput), 0666)
683 if err != nil {
684 return err
685 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400686
687 if err != nil {
688 return err
689 }
690
691 cqueryResults := map[string]string{}
692 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
693 if strings.Contains(outputLine, ">>") {
694 splitLine := strings.SplitN(outputLine, ">>", 2)
695 cqueryResults[splitLine[0]] = splitLine[1]
696 }
697 }
698
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400699 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500700 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400701 context.results[val] = string(cqueryResult)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400702 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500703 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
704 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400705 }
706 }
707
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500708 // Issue an aquery command to retrieve action information about the bazel build tree.
709 //
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400710 // TODO(cparsons): Use --target_pattern_file to avoid command line limits.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500711 var aqueryOutput string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400712 aqueryOutput, _, err = context.issueBazelCommand(
713 context.paths,
714 bazel.AqueryBuildRootRunName,
715 bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)},
716 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
717 // proto sources, which would add a number of unnecessary dependencies.
718 "--output=jsonproto")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400719
720 if err != nil {
721 return err
722 }
723
Chris Parsons4f069892021-01-15 12:22:41 -0500724 context.buildStatements, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
725 if err != nil {
726 return err
727 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500728
729 // Issue a build command of the phony root to generate symlink forests for dependencies of the
730 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
731 // but some of symlinks may be required to resolve source dependencies of the build.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400732 _, _, err = context.issueBazelCommand(
733 context.paths,
734 bazel.BazelBuildPhonyRootRunName,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200735 bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"})
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500736
737 if err != nil {
738 return err
739 }
740
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400741 // Clear requests.
742 context.requests = map[cqueryKey]bool{}
743 return nil
744}
Chris Parsonsa798d962020-10-12 23:44:08 -0400745
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500746func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
747 return context.buildStatements
748}
749
750func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400751 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500752}
753
Chris Parsonsa798d962020-10-12 23:44:08 -0400754// Singleton used for registering BUILD file ninja dependencies (needed
755// for correctness of builds which use Bazel.
756func BazelSingleton() Singleton {
757 return &bazelSingleton{}
758}
759
760type bazelSingleton struct{}
761
762func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500763 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
764 if !ctx.Config().BazelContext.BazelEnabled() {
765 return
766 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400767
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500768 // Add ninja file dependencies for files which all bazel invocations require.
769 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200770 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500771 ctx.AddNinjaFileDeps(bazelBuildList)
772
773 data, err := ioutil.ReadFile(bazelBuildList)
774 if err != nil {
775 ctx.Errorf(err.Error())
776 }
777 files := strings.Split(strings.TrimSpace(string(data)), "\n")
778 for _, file := range files {
779 ctx.AddNinjaFileDeps(file)
780 }
781
782 // Register bazel-owned build statements (obtained from the aquery invocation).
783 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500784 if len(buildStatement.Command) < 1 {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000785 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500786 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500787 rule := NewRuleBuilder(pctx, ctx)
788 cmd := rule.Command()
Chris Parsons94a0bba2021-06-04 15:03:47 -0400789
790 // cd into Bazel's execution root, which is the action cwd.
791 cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ && ", ctx.Config().BazelContext.OutputBase()))
792
793 for _, pair := range buildStatement.Env {
794 // Set per-action env variables, if any.
795 cmd.Flag(pair.Key + "=" + pair.Value)
796 }
797
798 // The actual Bazel action.
799 cmd.Text(" " + buildStatement.Command)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500800
801 for _, outputPath := range buildStatement.OutputPaths {
802 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400803 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500804 for _, inputPath := range buildStatement.InputPaths {
805 cmd.Implicit(PathForBazelOut(ctx, inputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400806 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500807
Liz Kammerde116852021-03-25 16:42:37 -0400808 if depfile := buildStatement.Depfile; depfile != nil {
809 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
810 }
811
Liz Kammerc49e6822021-06-08 15:04:11 -0400812 for _, symlinkPath := range buildStatement.SymlinkPaths {
813 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
814 }
815
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500816 // This is required to silence warnings pertaining to unexpected timestamps. Particularly,
817 // some Bazel builtins (such as files in the bazel_tools directory) have far-future
818 // timestamps. Without restat, Ninja would emit warnings that the input files of a
819 // build statement have later timestamps than the outputs.
820 rule.Restat()
821
Liz Kammer13548d72020-12-16 11:13:30 -0800822 rule.Build(fmt.Sprintf("bazel %d", index), buildStatement.Mnemonic)
Chris Parsonsa798d962020-10-12 23:44:08 -0400823 }
824}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500825
826func getCqueryId(key cqueryKey) string {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200827 return key.label + "|" + getArchString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500828}
829
830func getArchString(key cqueryKey) string {
831 arch := key.archType.Name
832 if len(arch) > 0 {
833 return arch
834 } else {
835 return "x86_64"
836 }
837}