blob: abc793f8eb183f579d39b2c297b27db9aecfa997 [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
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050031 "github.com/google/blueprint/bootstrap"
32
Patrice Arruda05ab2d02020-12-12 06:24:26 +000033 "android/soong/bazel"
34 "android/soong/shared"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040035)
36
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040037type CqueryRequestType int
38
39const (
40 getAllFiles CqueryRequestType = iota
Chris Parsons808d84c2021-03-09 20:43:32 -050041 getAllFilesAndCcObjectFiles
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040042)
43
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040044// Map key to describe bazel cquery requests.
45type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040046 label string
Chris Parsons944e7d02021-03-11 11:08:46 -050047 requestType cquery.RequestType
Chris Parsons8d6e4332021-02-22 16:13:50 -050048 archType ArchType
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040049}
50
51type BazelContext interface {
52 // The below methods involve queuing cquery requests to be later invoked
53 // by bazel. If any of these methods return (_, false), then the request
54 // has been queued to be run later.
55
56 // Returns result files built by building the given bazel target label.
Chris Parsons944e7d02021-03-11 11:08:46 -050057 GetOutputFiles(label string, archType ArchType) ([]string, bool)
Chris Parsons8d6e4332021-02-22 16:13:50 -050058
Chris Parsons944e7d02021-03-11 11:08:46 -050059 // TODO(cparsons): Other cquery-related methods should be added here.
60 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
61 GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool)
Chris Parsons808d84c2021-03-09 20:43:32 -050062
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040063 // ** End cquery methods
64
65 // Issues commands to Bazel to receive results for all cquery requests
66 // queued in the BazelContext.
67 InvokeBazel() error
68
69 // Returns true if bazel is enabled for the given configuration.
70 BazelEnabled() bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050071
72 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
73 OutputBase() string
74
75 // Returns build statements which should get registered to reflect Bazel's outputs.
76 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040077}
78
79// A context object which tracks queued requests that need to be made to Bazel,
80// and their results after the requests have been made.
81type bazelContext struct {
82 homeDir string
83 bazelPath string
84 outputBase string
85 workspaceDir string
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040086 buildDir string
Patrice Arruda05ab2d02020-12-12 06:24:26 +000087 metricsDir string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040088
89 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
90 requestMutex sync.Mutex // requests can be written in parallel
91
92 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050093
94 // Build statements which should get registered to reflect Bazel's outputs.
95 buildStatements []bazel.BuildStatement
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040096}
97
98var _ BazelContext = &bazelContext{}
99
100// A bazel context to use when Bazel is disabled.
101type noopBazelContext struct{}
102
103var _ BazelContext = noopBazelContext{}
104
105// A bazel context to use for tests.
106type MockBazelContext struct {
107 AllFiles map[string][]string
108}
109
Chris Parsons944e7d02021-03-11 11:08:46 -0500110func (m MockBazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500111 result, ok := m.AllFiles[label]
112 return result, ok
113}
114
Chris Parsons944e7d02021-03-11 11:08:46 -0500115func (m MockBazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500116 result, ok := m.AllFiles[label]
117 return result, result, ok
118}
119
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400120func (m MockBazelContext) InvokeBazel() error {
121 panic("unimplemented")
122}
123
124func (m MockBazelContext) BazelEnabled() bool {
125 return true
126}
127
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500128func (m MockBazelContext) OutputBase() string {
129 return "outputbase"
130}
131
132func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
133 return []bazel.BuildStatement{}
134}
135
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400136var _ BazelContext = MockBazelContext{}
137
Chris Parsons944e7d02021-03-11 11:08:46 -0500138func (bazelCtx *bazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
139 rawString, ok := bazelCtx.cquery(label, cquery.GetOutputFiles, archType)
140 var ret []string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400141 if ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500142 bazelOutput := strings.TrimSpace(rawString)
143 ret = cquery.GetOutputFiles.ParseResult(bazelOutput).([]string)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400144 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500145 return ret, ok
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400146}
147
Chris Parsons944e7d02021-03-11 11:08:46 -0500148func (bazelCtx *bazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
149 var outputFiles []string
Chris Parsons808d84c2021-03-09 20:43:32 -0500150 var ccObjects []string
151
Chris Parsons944e7d02021-03-11 11:08:46 -0500152 result, ok := bazelCtx.cquery(label, cquery.GetOutputFilesAndCcObjectFiles, archType)
Chris Parsons808d84c2021-03-09 20:43:32 -0500153 if ok {
154 bazelOutput := strings.TrimSpace(result)
Chris Parsons944e7d02021-03-11 11:08:46 -0500155 returnResult := cquery.GetOutputFilesAndCcObjectFiles.ParseResult(bazelOutput).(cquery.GetOutputFilesAndCcObjectFiles_Result)
156 outputFiles = returnResult.OutputFiles
157 ccObjects = returnResult.CcObjectFiles
Chris Parsons808d84c2021-03-09 20:43:32 -0500158 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500159
160 return outputFiles, ccObjects, ok
Chris Parsons808d84c2021-03-09 20:43:32 -0500161}
162
Chris Parsons944e7d02021-03-11 11:08:46 -0500163func (n noopBazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500164 panic("unimplemented")
165}
166
Chris Parsons944e7d02021-03-11 11:08:46 -0500167func (n noopBazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500168 panic("unimplemented")
169}
170
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400171func (n noopBazelContext) InvokeBazel() error {
172 panic("unimplemented")
173}
174
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500175func (m noopBazelContext) OutputBase() string {
176 return ""
177}
178
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400179func (n noopBazelContext) BazelEnabled() bool {
180 return false
181}
182
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500183func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
184 return []bazel.BuildStatement{}
185}
186
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400187func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons8b77a002020-10-27 18:59:25 -0400188 // TODO(cparsons): Assess USE_BAZEL=1 instead once "mixed Soong/Bazel builds"
189 // are production ready.
190 if c.Getenv("USE_BAZEL_ANALYSIS") != "1" {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400191 return noopBazelContext{}, nil
192 }
193
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400194 bazelCtx := bazelContext{buildDir: c.buildDir, requests: make(map[cqueryKey]bool)}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400195 missingEnvVars := []string{}
196 if len(c.Getenv("BAZEL_HOME")) > 1 {
197 bazelCtx.homeDir = c.Getenv("BAZEL_HOME")
198 } else {
199 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
200 }
201 if len(c.Getenv("BAZEL_PATH")) > 1 {
202 bazelCtx.bazelPath = c.Getenv("BAZEL_PATH")
203 } else {
204 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
205 }
206 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
207 bazelCtx.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
208 } else {
209 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
210 }
211 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
212 bazelCtx.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
213 } else {
214 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
215 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000216 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
217 bazelCtx.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
218 } else {
219 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
220 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400221 if len(missingEnvVars) > 0 {
222 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
223 } else {
224 return &bazelCtx, nil
225 }
226}
227
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000228func (context *bazelContext) BazelMetricsDir() string {
229 return context.metricsDir
230}
231
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400232func (context *bazelContext) BazelEnabled() bool {
233 return true
234}
235
236// Adds a cquery request to the Bazel request queue, to be later invoked, or
237// returns the result of the given request if the request was already made.
238// If the given request was already made (and the results are available), then
239// returns (result, true). If the request is queued but no results are available,
240// then returns ("", false).
Chris Parsons944e7d02021-03-11 11:08:46 -0500241func (context *bazelContext) cquery(label string, requestType cquery.RequestType,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500242 archType ArchType) (string, bool) {
243 key := cqueryKey{label, requestType, archType}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400244 if result, ok := context.results[key]; ok {
245 return result, true
246 } else {
247 context.requestMutex.Lock()
248 defer context.requestMutex.Unlock()
249 context.requests[key] = true
250 return "", false
251 }
252}
253
254func pwdPrefix() string {
255 // Darwin doesn't have /proc
256 if runtime.GOOS != "darwin" {
257 return "PWD=/proc/self/cwd"
258 }
259 return ""
260}
261
Chris Parsons808d84c2021-03-09 20:43:32 -0500262// Issues the given bazel command with given build label and additional flags.
263// Returns (stdout, stderr, error). The first and second return values are strings
264// containing the stdout and stderr of the run command, and an error is returned if
265// the invocation returned an error code.
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000266func (context *bazelContext) issueBazelCommand(runName bazel.RunName, command string, labels []string,
Chris Parsons808d84c2021-03-09 20:43:32 -0500267 extraFlags ...string) (string, string, error) {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400268
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500269 cmdFlags := []string{"--output_base=" + context.outputBase, command}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400270 cmdFlags = append(cmdFlags, labels...)
Chris Parsons8ccdb632020-11-17 15:41:01 -0500271 cmdFlags = append(cmdFlags, "--package_path=%workspace%/"+context.intermediatesDir())
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000272 cmdFlags = append(cmdFlags, "--profile="+shared.BazelMetricsFilename(context, runName))
Chris Parsonsee423b02021-02-08 23:04:59 -0500273 // Set default platforms to canonicalized values for mixed builds requests. If these are set
274 // in the bazelrc, they will have values that are non-canonicalized, and thus be invalid.
275 // The actual platform values here may be overridden by configuration transitions from the buildroot.
276 cmdFlags = append(cmdFlags,
277 fmt.Sprintf("--platforms=%s", canonicalizeLabel("//build/bazel/platforms:generic_x86_64")))
278 cmdFlags = append(cmdFlags,
279 fmt.Sprintf("--extra_toolchains=%s", canonicalizeLabel("//prebuilts/clang/host/linux-x86:all")))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500280 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
281 cmdFlags = append(cmdFlags, "--experimental_repository_disable_download")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400282 cmdFlags = append(cmdFlags, extraFlags...)
283
284 bazelCmd := exec.Command(context.bazelPath, cmdFlags...)
285 bazelCmd.Dir = context.workspaceDir
Chris Parsons8d6e4332021-02-22 16:13:50 -0500286 bazelCmd.Env = append(os.Environ(), "HOME="+context.homeDir, pwdPrefix(),
287 // Disables local host detection of gcc; toolchain information is defined
288 // explicitly in BUILD files.
289 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
Colin Crossff0278b2020-10-09 19:24:15 -0700290 stderr := &bytes.Buffer{}
291 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400292
293 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500294 return "", string(stderr.Bytes()),
295 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400296 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500297 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400298 }
299}
300
Chris Parsons8ccdb632020-11-17 15:41:01 -0500301// Returns the string contents of a workspace file that should be output
302// adjacent to the main bzl file and build file.
303// This workspace file allows, via local_repository rule, sourcetree-level
304// BUILD targets to be referenced via @sourceroot.
305func (context *bazelContext) workspaceFileContents() []byte {
306 formatString := `
307# This file is generated by soong_build. Do not edit.
308local_repository(
309 name = "sourceroot",
310 path = "%s",
311)
Liz Kammer8206d4f2021-03-03 16:40:52 -0500312
313local_repository(
314 name = "rules_cc",
315 path = "%s/build/bazel/rules_cc",
316)
Chris Parsons8ccdb632020-11-17 15:41:01 -0500317`
Liz Kammer8206d4f2021-03-03 16:40:52 -0500318 return []byte(fmt.Sprintf(formatString, context.workspaceDir, context.workspaceDir))
Chris Parsons8ccdb632020-11-17 15:41:01 -0500319}
320
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400321func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500322 // TODO(cparsons): Define configuration transitions programmatically based
323 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400324 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500325#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400326# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500327#####################################################
328
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400329def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500330 return {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400331 "//command_line_option:platforms": "@sourceroot//build/bazel/platforms:generic_%s" % attr.arch,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500332 }
333
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400334_config_node_transition = transition(
335 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500336 inputs = [],
337 outputs = [
338 "//command_line_option:platforms",
339 ],
340)
341
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400342def _passthrough_rule_impl(ctx):
343 return [DefaultInfo(files = depset(ctx.files.deps))]
344
345config_node = rule(
346 implementation = _passthrough_rule_impl,
347 attrs = {
348 "arch" : attr.string(mandatory = True),
349 "deps" : attr.label_list(cfg = _config_node_transition),
350 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
351 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500352)
353
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400354
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500355# Rule representing the root of the build, to depend on all Bazel targets that
356# are required for the build. Building this target will build the entire Bazel
357# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400358mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400359 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500360 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400361 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500362 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400363)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500364
365def _phony_root_impl(ctx):
366 return []
367
368# Rule to depend on other targets but build nothing.
369# This is useful as follows: building a target of this rule will generate
370# symlink forests for all dependencies of the target, without executing any
371# actions of the build.
372phony_root = rule(
373 implementation = _phony_root_impl,
374 attrs = {"deps" : attr.label_list()},
375)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400376`
377 return []byte(contents)
378}
379
Chris Parsons8ccdb632020-11-17 15:41:01 -0500380// Returns a "canonicalized" corresponding to the given sourcetree-level label.
381// This abstraction is required because a sourcetree label such as //foo/bar:baz
382// must be referenced via the local repository prefix, such as
383// @sourceroot//foo/bar:baz.
384func canonicalizeLabel(label string) string {
385 if strings.HasPrefix(label, "//") {
386 return "@sourceroot" + label
387 } else {
388 return "@sourceroot//" + label
389 }
390}
391
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400392func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500393 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
394 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400395 formatString := `
396# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400397load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
398
399%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400400
401mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400402 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400403)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500404
405phony_root(name = "phonyroot",
406 deps = [":buildroot"],
407)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400408`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400409 configNodeFormatString := `
410config_node(name = "%s",
411 arch = "%s",
412 deps = [%s],
413)
414`
415
416 configNodesSection := ""
417
418 labelsByArch := map[string][]string{}
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400419 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500420 labelString := fmt.Sprintf("\"%s\"", canonicalizeLabel(val.label))
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400421 archString := getArchString(val)
422 labelsByArch[archString] = append(labelsByArch[archString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400423 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400424
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400425 configNodeLabels := []string{}
426 for archString, labels := range labelsByArch {
427 configNodeLabels = append(configNodeLabels, fmt.Sprintf("\":%s\"", archString))
428 labelsString := strings.Join(labels, ",\n ")
429 configNodesSection += fmt.Sprintf(configNodeFormatString, archString, archString, labelsString)
430 }
431
432 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(configNodeLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400433}
434
Chris Parsons944e7d02021-03-11 11:08:46 -0500435func indent(original string) string {
436 result := ""
437 for _, line := range strings.Split(original, "\n") {
438 result += " " + line + "\n"
439 }
440 return result
441}
442
Chris Parsons808d84c2021-03-09 20:43:32 -0500443// Returns the file contents of the buildroot.cquery file that should be used for the cquery
444// expression in order to obtain information about buildroot and its dependencies.
445// The contents of this file depend on the bazelContext's requests; requests are enumerated
446// and grouped by their request type. The data retrieved for each label depends on its
447// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400448func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Chris Parsons944e7d02021-03-11 11:08:46 -0500449 requestTypeToCqueryIdEntries := map[cquery.RequestType][]string{}
450 for val, _ := range context.requests {
451 cqueryId := getCqueryId(val)
452 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
453 requestTypeToCqueryIdEntries[val.requestType] =
454 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
455 }
456 labelRegistrationMapSection := ""
457 functionDefSection := ""
458 mainSwitchSection := ""
459
460 mapDeclarationFormatString := `
461%s = {
462 %s
463}
464`
465 functionDefFormatString := `
466def %s(target):
467%s
468`
469 mainSwitchSectionFormatString := `
470 if id_string in %s:
471 return id_string + ">>" + %s(target)
472`
473
474 for _, requestType := range cquery.RequestTypes {
475 labelMapName := requestType.Name() + "_Labels"
476 functionName := requestType.Name() + "_Fn"
477 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
478 labelMapName,
479 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
480 functionDefSection += fmt.Sprintf(functionDefFormatString,
481 functionName,
482 indent(requestType.StarlarkFunctionBody()))
483 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
484 labelMapName, functionName)
485 }
486
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400487 formatString := `
488# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400489
Chris Parsons944e7d02021-03-11 11:08:46 -0500490# Label Map Section
491%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500492
Chris Parsons944e7d02021-03-11 11:08:46 -0500493# Function Def Section
494%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500495
496def get_arch(target):
497 buildoptions = build_options(target)
498 platforms = build_options(target)["//command_line_option:platforms"]
499 if len(platforms) != 1:
500 # An individual configured target should have only one platform architecture.
501 # Note that it's fine for there to be multiple architectures for the same label,
502 # but each is its own configured target.
503 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
504 platform_name = build_options(target)["//command_line_option:platforms"][0].name
505 if platform_name == "host":
506 return "HOST"
507 elif not platform_name.startswith("generic_"):
508 fail("expected platform name of the form 'generic_<arch>', but was " + str(platforms))
509 return "UNKNOWN"
510 return platform_name[len("generic_"):]
511
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400512def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500513 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500514
515 # Main switch section
516 %s
517 # This target was not requested via cquery, and thus must be a dependency
518 # of a requested target.
519 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400520`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400521
Chris Parsons944e7d02021-03-11 11:08:46 -0500522 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
523 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400524}
525
Chris Parsons8ccdb632020-11-17 15:41:01 -0500526// Returns a workspace-relative path containing build-related metadata required
527// for interfacing with Bazel. Example: out/soong/bazel.
528func (context *bazelContext) intermediatesDir() string {
529 return filepath.Join(context.buildDir, "bazel")
530}
531
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400532// Issues commands to Bazel to receive results for all cquery requests
533// queued in the BazelContext.
534func (context *bazelContext) InvokeBazel() error {
535 context.results = make(map[cqueryKey]string)
536
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400537 var cqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500538 var cqueryErr string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400539 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500540
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500541 intermediatesDirPath := absolutePath(context.intermediatesDir())
542 if _, err := os.Stat(intermediatesDirPath); os.IsNotExist(err) {
543 err = os.Mkdir(intermediatesDirPath, 0777)
544 }
545
Chris Parsons8ccdb632020-11-17 15:41:01 -0500546 if err != nil {
547 return err
548 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400549 err = ioutil.WriteFile(
Chris Parsons8ccdb632020-11-17 15:41:01 -0500550 absolutePath(filepath.Join(context.intermediatesDir(), "main.bzl")),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400551 context.mainBzlFileContents(), 0666)
552 if err != nil {
553 return err
554 }
555 err = ioutil.WriteFile(
Chris Parsons8ccdb632020-11-17 15:41:01 -0500556 absolutePath(filepath.Join(context.intermediatesDir(), "BUILD.bazel")),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400557 context.mainBuildFileContents(), 0666)
558 if err != nil {
559 return err
560 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800561 cqueryFileRelpath := filepath.Join(context.intermediatesDir(), "buildroot.cquery")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400562 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800563 absolutePath(cqueryFileRelpath),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400564 context.cqueryStarlarkFileContents(), 0666)
565 if err != nil {
566 return err
567 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800568 workspaceFileRelpath := filepath.Join(context.intermediatesDir(), "WORKSPACE.bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500569 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800570 absolutePath(workspaceFileRelpath),
Chris Parsons8ccdb632020-11-17 15:41:01 -0500571 context.workspaceFileContents(), 0666)
572 if err != nil {
573 return err
574 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800575 buildrootLabel := "//:buildroot"
Chris Parsons808d84c2021-03-09 20:43:32 -0500576 cqueryOutput, cqueryErr, err = context.issueBazelCommand(bazel.CqueryBuildRootRunName, "cquery",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500577 []string{fmt.Sprintf("kind(rule, deps(%s))", buildrootLabel)},
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400578 "--output=starlark",
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800579 "--starlark:file="+cqueryFileRelpath)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500580 err = ioutil.WriteFile(
581 absolutePath(filepath.Join(context.intermediatesDir(), "cquery.out")),
582 []byte(cqueryOutput), 0666)
583 if err != nil {
584 return err
585 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400586
587 if err != nil {
588 return err
589 }
590
591 cqueryResults := map[string]string{}
592 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
593 if strings.Contains(outputLine, ">>") {
594 splitLine := strings.SplitN(outputLine, ">>", 2)
595 cqueryResults[splitLine[0]] = splitLine[1]
596 }
597 }
598
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400599 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500600 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400601 context.results[val] = string(cqueryResult)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400602 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500603 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
604 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400605 }
606 }
607
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500608 // Issue an aquery command to retrieve action information about the bazel build tree.
609 //
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400610 // TODO(cparsons): Use --target_pattern_file to avoid command line limits.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500611 var aqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500612 aqueryOutput, _, err = context.issueBazelCommand(bazel.AqueryBuildRootRunName, "aquery",
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800613 []string{fmt.Sprintf("deps(%s)", buildrootLabel),
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500614 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
615 // proto sources, which would add a number of unnecessary dependencies.
616 "--output=jsonproto"})
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400617
618 if err != nil {
619 return err
620 }
621
Chris Parsons4f069892021-01-15 12:22:41 -0500622 context.buildStatements, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
623 if err != nil {
624 return err
625 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500626
627 // Issue a build command of the phony root to generate symlink forests for dependencies of the
628 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
629 // but some of symlinks may be required to resolve source dependencies of the build.
Chris Parsons808d84c2021-03-09 20:43:32 -0500630 _, _, err = context.issueBazelCommand(bazel.BazelBuildPhonyRootRunName, "build",
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500631 []string{"//:phonyroot"})
632
633 if err != nil {
634 return err
635 }
636
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400637 // Clear requests.
638 context.requests = map[cqueryKey]bool{}
639 return nil
640}
Chris Parsonsa798d962020-10-12 23:44:08 -0400641
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500642func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
643 return context.buildStatements
644}
645
646func (context *bazelContext) OutputBase() string {
647 return context.outputBase
648}
649
Chris Parsonsa798d962020-10-12 23:44:08 -0400650// Singleton used for registering BUILD file ninja dependencies (needed
651// for correctness of builds which use Bazel.
652func BazelSingleton() Singleton {
653 return &bazelSingleton{}
654}
655
656type bazelSingleton struct{}
657
658func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500659 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
660 if !ctx.Config().BazelContext.BazelEnabled() {
661 return
662 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400663
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500664 // Add ninja file dependencies for files which all bazel invocations require.
665 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100666 filepath.Dir(bootstrap.CmdlineModuleListFile()), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500667 ctx.AddNinjaFileDeps(bazelBuildList)
668
669 data, err := ioutil.ReadFile(bazelBuildList)
670 if err != nil {
671 ctx.Errorf(err.Error())
672 }
673 files := strings.Split(strings.TrimSpace(string(data)), "\n")
674 for _, file := range files {
675 ctx.AddNinjaFileDeps(file)
676 }
677
678 // Register bazel-owned build statements (obtained from the aquery invocation).
679 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500680 if len(buildStatement.Command) < 1 {
681 panic(fmt.Sprintf("unhandled build statement: %s", buildStatement))
682 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500683 rule := NewRuleBuilder(pctx, ctx)
684 cmd := rule.Command()
685 cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ && %s",
686 ctx.Config().BazelContext.OutputBase(), buildStatement.Command))
687
688 for _, outputPath := range buildStatement.OutputPaths {
689 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400690 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500691 for _, inputPath := range buildStatement.InputPaths {
692 cmd.Implicit(PathForBazelOut(ctx, inputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400693 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500694
695 // This is required to silence warnings pertaining to unexpected timestamps. Particularly,
696 // some Bazel builtins (such as files in the bazel_tools directory) have far-future
697 // timestamps. Without restat, Ninja would emit warnings that the input files of a
698 // build statement have later timestamps than the outputs.
699 rule.Restat()
700
Liz Kammer13548d72020-12-16 11:13:30 -0800701 rule.Build(fmt.Sprintf("bazel %d", index), buildStatement.Mnemonic)
Chris Parsonsa798d962020-10-12 23:44:08 -0400702 }
703}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500704
705func getCqueryId(key cqueryKey) string {
706 return canonicalizeLabel(key.label) + "|" + getArchString(key)
707}
708
709func getArchString(key cqueryKey) string {
710 arch := key.archType.Name
711 if len(arch) > 0 {
712 return arch
713 } else {
714 return "x86_64"
715 }
716}