blob: 5b9d3bfe8cc342965dadf876fdd06f960d956a7e [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
37// Map key to describe bazel cquery requests.
38type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040039 label string
Chris Parsons944e7d02021-03-11 11:08:46 -050040 requestType cquery.RequestType
Chris Parsons8d6e4332021-02-22 16:13:50 -050041 archType ArchType
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040042}
43
44type BazelContext interface {
45 // The below methods involve queuing cquery requests to be later invoked
46 // by bazel. If any of these methods return (_, false), then the request
47 // has been queued to be run later.
48
49 // Returns result files built by building the given bazel target label.
Chris Parsons944e7d02021-03-11 11:08:46 -050050 GetOutputFiles(label string, archType ArchType) ([]string, bool)
Chris Parsons8d6e4332021-02-22 16:13:50 -050051
Chris Parsons944e7d02021-03-11 11:08:46 -050052 // TODO(cparsons): Other cquery-related methods should be added here.
53 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
54 GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool)
Chris Parsons808d84c2021-03-09 20:43:32 -050055
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040056 // ** End cquery methods
57
58 // Issues commands to Bazel to receive results for all cquery requests
59 // queued in the BazelContext.
60 InvokeBazel() error
61
62 // Returns true if bazel is enabled for the given configuration.
63 BazelEnabled() bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050064
65 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
66 OutputBase() string
67
68 // Returns build statements which should get registered to reflect Bazel's outputs.
69 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040070}
71
72// A context object which tracks queued requests that need to be made to Bazel,
73// and their results after the requests have been made.
74type bazelContext struct {
75 homeDir string
76 bazelPath string
77 outputBase string
78 workspaceDir string
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040079 buildDir string
Patrice Arruda05ab2d02020-12-12 06:24:26 +000080 metricsDir string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040081
82 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
83 requestMutex sync.Mutex // requests can be written in parallel
84
85 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050086
87 // Build statements which should get registered to reflect Bazel's outputs.
88 buildStatements []bazel.BuildStatement
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040089}
90
91var _ BazelContext = &bazelContext{}
92
93// A bazel context to use when Bazel is disabled.
94type noopBazelContext struct{}
95
96var _ BazelContext = noopBazelContext{}
97
98// A bazel context to use for tests.
99type MockBazelContext struct {
100 AllFiles map[string][]string
101}
102
Chris Parsons944e7d02021-03-11 11:08:46 -0500103func (m MockBazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500104 result, ok := m.AllFiles[label]
105 return result, ok
106}
107
Chris Parsons944e7d02021-03-11 11:08:46 -0500108func (m MockBazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500109 result, ok := m.AllFiles[label]
110 return result, result, ok
111}
112
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400113func (m MockBazelContext) InvokeBazel() error {
114 panic("unimplemented")
115}
116
117func (m MockBazelContext) BazelEnabled() bool {
118 return true
119}
120
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500121func (m MockBazelContext) OutputBase() string {
122 return "outputbase"
123}
124
125func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
126 return []bazel.BuildStatement{}
127}
128
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400129var _ BazelContext = MockBazelContext{}
130
Chris Parsons944e7d02021-03-11 11:08:46 -0500131func (bazelCtx *bazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
132 rawString, ok := bazelCtx.cquery(label, cquery.GetOutputFiles, archType)
133 var ret []string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400134 if ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500135 bazelOutput := strings.TrimSpace(rawString)
136 ret = cquery.GetOutputFiles.ParseResult(bazelOutput).([]string)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400137 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500138 return ret, ok
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400139}
140
Chris Parsons944e7d02021-03-11 11:08:46 -0500141func (bazelCtx *bazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
142 var outputFiles []string
Chris Parsons808d84c2021-03-09 20:43:32 -0500143 var ccObjects []string
144
Chris Parsons944e7d02021-03-11 11:08:46 -0500145 result, ok := bazelCtx.cquery(label, cquery.GetOutputFilesAndCcObjectFiles, archType)
Chris Parsons808d84c2021-03-09 20:43:32 -0500146 if ok {
147 bazelOutput := strings.TrimSpace(result)
Chris Parsons944e7d02021-03-11 11:08:46 -0500148 returnResult := cquery.GetOutputFilesAndCcObjectFiles.ParseResult(bazelOutput).(cquery.GetOutputFilesAndCcObjectFiles_Result)
149 outputFiles = returnResult.OutputFiles
150 ccObjects = returnResult.CcObjectFiles
Chris Parsons808d84c2021-03-09 20:43:32 -0500151 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500152
153 return outputFiles, ccObjects, ok
Chris Parsons808d84c2021-03-09 20:43:32 -0500154}
155
Chris Parsons944e7d02021-03-11 11:08:46 -0500156func (n noopBazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500157 panic("unimplemented")
158}
159
Chris Parsons944e7d02021-03-11 11:08:46 -0500160func (n noopBazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500161 panic("unimplemented")
162}
163
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400164func (n noopBazelContext) InvokeBazel() error {
165 panic("unimplemented")
166}
167
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500168func (m noopBazelContext) OutputBase() string {
169 return ""
170}
171
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400172func (n noopBazelContext) BazelEnabled() bool {
173 return false
174}
175
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500176func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
177 return []bazel.BuildStatement{}
178}
179
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400180func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons8b77a002020-10-27 18:59:25 -0400181 // TODO(cparsons): Assess USE_BAZEL=1 instead once "mixed Soong/Bazel builds"
182 // are production ready.
183 if c.Getenv("USE_BAZEL_ANALYSIS") != "1" {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400184 return noopBazelContext{}, nil
185 }
186
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400187 bazelCtx := bazelContext{buildDir: c.buildDir, requests: make(map[cqueryKey]bool)}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400188 missingEnvVars := []string{}
189 if len(c.Getenv("BAZEL_HOME")) > 1 {
190 bazelCtx.homeDir = c.Getenv("BAZEL_HOME")
191 } else {
192 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
193 }
194 if len(c.Getenv("BAZEL_PATH")) > 1 {
195 bazelCtx.bazelPath = c.Getenv("BAZEL_PATH")
196 } else {
197 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
198 }
199 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
200 bazelCtx.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
201 } else {
202 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
203 }
204 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
205 bazelCtx.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
206 } else {
207 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
208 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000209 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
210 bazelCtx.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
211 } else {
212 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
213 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400214 if len(missingEnvVars) > 0 {
215 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
216 } else {
217 return &bazelCtx, nil
218 }
219}
220
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000221func (context *bazelContext) BazelMetricsDir() string {
222 return context.metricsDir
223}
224
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400225func (context *bazelContext) BazelEnabled() bool {
226 return true
227}
228
229// Adds a cquery request to the Bazel request queue, to be later invoked, or
230// returns the result of the given request if the request was already made.
231// If the given request was already made (and the results are available), then
232// returns (result, true). If the request is queued but no results are available,
233// then returns ("", false).
Chris Parsons944e7d02021-03-11 11:08:46 -0500234func (context *bazelContext) cquery(label string, requestType cquery.RequestType,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500235 archType ArchType) (string, bool) {
236 key := cqueryKey{label, requestType, archType}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400237 if result, ok := context.results[key]; ok {
238 return result, true
239 } else {
240 context.requestMutex.Lock()
241 defer context.requestMutex.Unlock()
242 context.requests[key] = true
243 return "", false
244 }
245}
246
247func pwdPrefix() string {
248 // Darwin doesn't have /proc
249 if runtime.GOOS != "darwin" {
250 return "PWD=/proc/self/cwd"
251 }
252 return ""
253}
254
Chris Parsons808d84c2021-03-09 20:43:32 -0500255// Issues the given bazel command with given build label and additional flags.
256// Returns (stdout, stderr, error). The first and second return values are strings
257// containing the stdout and stderr of the run command, and an error is returned if
258// the invocation returned an error code.
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000259func (context *bazelContext) issueBazelCommand(runName bazel.RunName, command string, labels []string,
Chris Parsons808d84c2021-03-09 20:43:32 -0500260 extraFlags ...string) (string, string, error) {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400261
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500262 cmdFlags := []string{"--output_base=" + context.outputBase, command}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400263 cmdFlags = append(cmdFlags, labels...)
Chris Parsons8ccdb632020-11-17 15:41:01 -0500264 cmdFlags = append(cmdFlags, "--package_path=%workspace%/"+context.intermediatesDir())
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000265 cmdFlags = append(cmdFlags, "--profile="+shared.BazelMetricsFilename(context, runName))
Jingwen Chen91220d72021-03-24 02:18:33 -0400266
267 // Set default platforms to canonicalized values for mixed builds requests.
268 // If these are set in the bazelrc, they will have values that are
269 // non-canonicalized to @sourceroot labels, and thus be invalid when
270 // referenced from the buildroot.
271 //
272 // The actual platform values here may be overridden by configuration
273 // transitions from the buildroot.
Chris Parsonsee423b02021-02-08 23:04:59 -0500274 cmdFlags = append(cmdFlags,
Jingwen Chen91220d72021-03-24 02:18:33 -0400275 fmt.Sprintf("--platforms=%s", canonicalizeLabel("//build/bazel/platforms:android_x86_64")))
Chris Parsonsee423b02021-02-08 23:04:59 -0500276 cmdFlags = append(cmdFlags,
277 fmt.Sprintf("--extra_toolchains=%s", canonicalizeLabel("//prebuilts/clang/host/linux-x86:all")))
Jingwen Chen91220d72021-03-24 02:18:33 -0400278 // This should be parameterized on the host OS, but let's restrict to linux
279 // to keep things simple for now.
280 cmdFlags = append(cmdFlags,
281 fmt.Sprintf("--host_platform=%s", canonicalizeLabel("//build/bazel/platforms:linux_x86_64")))
282
Chris Parsons8d6e4332021-02-22 16:13:50 -0500283 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
284 cmdFlags = append(cmdFlags, "--experimental_repository_disable_download")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400285 cmdFlags = append(cmdFlags, extraFlags...)
286
287 bazelCmd := exec.Command(context.bazelPath, cmdFlags...)
288 bazelCmd.Dir = context.workspaceDir
Chris Parsons8d6e4332021-02-22 16:13:50 -0500289 bazelCmd.Env = append(os.Environ(), "HOME="+context.homeDir, pwdPrefix(),
290 // Disables local host detection of gcc; toolchain information is defined
291 // explicitly in BUILD files.
292 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
Colin Crossff0278b2020-10-09 19:24:15 -0700293 stderr := &bytes.Buffer{}
294 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400295
296 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500297 return "", string(stderr.Bytes()),
298 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400299 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500300 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400301 }
302}
303
Chris Parsons8ccdb632020-11-17 15:41:01 -0500304// Returns the string contents of a workspace file that should be output
305// adjacent to the main bzl file and build file.
306// This workspace file allows, via local_repository rule, sourcetree-level
307// BUILD targets to be referenced via @sourceroot.
308func (context *bazelContext) workspaceFileContents() []byte {
309 formatString := `
310# This file is generated by soong_build. Do not edit.
311local_repository(
312 name = "sourceroot",
313 path = "%s",
314)
Liz Kammer8206d4f2021-03-03 16:40:52 -0500315
316local_repository(
317 name = "rules_cc",
318 path = "%s/build/bazel/rules_cc",
319)
Chris Parsons8ccdb632020-11-17 15:41:01 -0500320`
Liz Kammer8206d4f2021-03-03 16:40:52 -0500321 return []byte(fmt.Sprintf(formatString, context.workspaceDir, context.workspaceDir))
Chris Parsons8ccdb632020-11-17 15:41:01 -0500322}
323
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400324func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500325 // TODO(cparsons): Define configuration transitions programmatically based
326 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400327 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500328#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400329# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500330#####################################################
331
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400332def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500333 return {
Jingwen Chen91220d72021-03-24 02:18:33 -0400334 "//command_line_option:platforms": "@sourceroot//build/bazel/platforms:android_%s" % attr.arch,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500335 }
336
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400337_config_node_transition = transition(
338 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500339 inputs = [],
340 outputs = [
341 "//command_line_option:platforms",
342 ],
343)
344
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400345def _passthrough_rule_impl(ctx):
346 return [DefaultInfo(files = depset(ctx.files.deps))]
347
348config_node = rule(
349 implementation = _passthrough_rule_impl,
350 attrs = {
351 "arch" : attr.string(mandatory = True),
352 "deps" : attr.label_list(cfg = _config_node_transition),
353 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
354 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500355)
356
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400357
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500358# Rule representing the root of the build, to depend on all Bazel targets that
359# are required for the build. Building this target will build the entire Bazel
360# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400361mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400362 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500363 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400364 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500365 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400366)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500367
368def _phony_root_impl(ctx):
369 return []
370
371# Rule to depend on other targets but build nothing.
372# This is useful as follows: building a target of this rule will generate
373# symlink forests for all dependencies of the target, without executing any
374# actions of the build.
375phony_root = rule(
376 implementation = _phony_root_impl,
377 attrs = {"deps" : attr.label_list()},
378)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400379`
380 return []byte(contents)
381}
382
Chris Parsons8ccdb632020-11-17 15:41:01 -0500383// Returns a "canonicalized" corresponding to the given sourcetree-level label.
384// This abstraction is required because a sourcetree label such as //foo/bar:baz
385// must be referenced via the local repository prefix, such as
386// @sourceroot//foo/bar:baz.
387func canonicalizeLabel(label string) string {
388 if strings.HasPrefix(label, "//") {
389 return "@sourceroot" + label
390 } else {
391 return "@sourceroot//" + label
392 }
393}
394
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400395func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500396 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
397 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400398 formatString := `
399# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400400load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
401
402%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400403
404mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400405 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400406)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500407
408phony_root(name = "phonyroot",
409 deps = [":buildroot"],
410)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400411`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400412 configNodeFormatString := `
413config_node(name = "%s",
414 arch = "%s",
415 deps = [%s],
416)
417`
418
419 configNodesSection := ""
420
421 labelsByArch := map[string][]string{}
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400422 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500423 labelString := fmt.Sprintf("\"%s\"", canonicalizeLabel(val.label))
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400424 archString := getArchString(val)
425 labelsByArch[archString] = append(labelsByArch[archString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400426 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400427
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400428 configNodeLabels := []string{}
429 for archString, labels := range labelsByArch {
430 configNodeLabels = append(configNodeLabels, fmt.Sprintf("\":%s\"", archString))
431 labelsString := strings.Join(labels, ",\n ")
432 configNodesSection += fmt.Sprintf(configNodeFormatString, archString, archString, labelsString)
433 }
434
435 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(configNodeLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400436}
437
Chris Parsons944e7d02021-03-11 11:08:46 -0500438func indent(original string) string {
439 result := ""
440 for _, line := range strings.Split(original, "\n") {
441 result += " " + line + "\n"
442 }
443 return result
444}
445
Chris Parsons808d84c2021-03-09 20:43:32 -0500446// Returns the file contents of the buildroot.cquery file that should be used for the cquery
447// expression in order to obtain information about buildroot and its dependencies.
448// The contents of this file depend on the bazelContext's requests; requests are enumerated
449// and grouped by their request type. The data retrieved for each label depends on its
450// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400451func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Chris Parsons944e7d02021-03-11 11:08:46 -0500452 requestTypeToCqueryIdEntries := map[cquery.RequestType][]string{}
453 for val, _ := range context.requests {
454 cqueryId := getCqueryId(val)
455 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
456 requestTypeToCqueryIdEntries[val.requestType] =
457 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
458 }
459 labelRegistrationMapSection := ""
460 functionDefSection := ""
461 mainSwitchSection := ""
462
463 mapDeclarationFormatString := `
464%s = {
465 %s
466}
467`
468 functionDefFormatString := `
469def %s(target):
470%s
471`
472 mainSwitchSectionFormatString := `
473 if id_string in %s:
474 return id_string + ">>" + %s(target)
475`
476
Liz Kammer66ffdb72021-04-02 13:26:07 -0400477 for requestType, _ := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500478 labelMapName := requestType.Name() + "_Labels"
479 functionName := requestType.Name() + "_Fn"
480 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
481 labelMapName,
482 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
483 functionDefSection += fmt.Sprintf(functionDefFormatString,
484 functionName,
485 indent(requestType.StarlarkFunctionBody()))
486 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
487 labelMapName, functionName)
488 }
489
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400490 formatString := `
491# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400492
Chris Parsons944e7d02021-03-11 11:08:46 -0500493# Label Map Section
494%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500495
Chris Parsons944e7d02021-03-11 11:08:46 -0500496# Function Def Section
497%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500498
499def get_arch(target):
500 buildoptions = build_options(target)
501 platforms = build_options(target)["//command_line_option:platforms"]
502 if len(platforms) != 1:
503 # An individual configured target should have only one platform architecture.
504 # Note that it's fine for there to be multiple architectures for the same label,
505 # but each is its own configured target.
506 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
507 platform_name = build_options(target)["//command_line_option:platforms"][0].name
508 if platform_name == "host":
509 return "HOST"
Jingwen Chen91220d72021-03-24 02:18:33 -0400510 elif not platform_name.startswith("android_"):
511 fail("expected platform name of the form 'android_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500512 return "UNKNOWN"
Jingwen Chen91220d72021-03-24 02:18:33 -0400513 return platform_name[len("android_"):]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500514
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400515def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500516 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500517
518 # Main switch section
519 %s
520 # This target was not requested via cquery, and thus must be a dependency
521 # of a requested target.
522 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400523`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400524
Chris Parsons944e7d02021-03-11 11:08:46 -0500525 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
526 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400527}
528
Chris Parsons8ccdb632020-11-17 15:41:01 -0500529// Returns a workspace-relative path containing build-related metadata required
530// for interfacing with Bazel. Example: out/soong/bazel.
531func (context *bazelContext) intermediatesDir() string {
532 return filepath.Join(context.buildDir, "bazel")
533}
534
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400535// Issues commands to Bazel to receive results for all cquery requests
536// queued in the BazelContext.
537func (context *bazelContext) InvokeBazel() error {
538 context.results = make(map[cqueryKey]string)
539
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400540 var cqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500541 var cqueryErr string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400542 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500543
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500544 intermediatesDirPath := absolutePath(context.intermediatesDir())
545 if _, err := os.Stat(intermediatesDirPath); os.IsNotExist(err) {
546 err = os.Mkdir(intermediatesDirPath, 0777)
547 }
548
Chris Parsons8ccdb632020-11-17 15:41:01 -0500549 if err != nil {
550 return err
551 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400552 err = ioutil.WriteFile(
Chris Parsons8ccdb632020-11-17 15:41:01 -0500553 absolutePath(filepath.Join(context.intermediatesDir(), "main.bzl")),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400554 context.mainBzlFileContents(), 0666)
555 if err != nil {
556 return err
557 }
558 err = ioutil.WriteFile(
Chris Parsons8ccdb632020-11-17 15:41:01 -0500559 absolutePath(filepath.Join(context.intermediatesDir(), "BUILD.bazel")),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400560 context.mainBuildFileContents(), 0666)
561 if err != nil {
562 return err
563 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800564 cqueryFileRelpath := filepath.Join(context.intermediatesDir(), "buildroot.cquery")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400565 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800566 absolutePath(cqueryFileRelpath),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400567 context.cqueryStarlarkFileContents(), 0666)
568 if err != nil {
569 return err
570 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800571 workspaceFileRelpath := filepath.Join(context.intermediatesDir(), "WORKSPACE.bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500572 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800573 absolutePath(workspaceFileRelpath),
Chris Parsons8ccdb632020-11-17 15:41:01 -0500574 context.workspaceFileContents(), 0666)
575 if err != nil {
576 return err
577 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800578 buildrootLabel := "//:buildroot"
Chris Parsons808d84c2021-03-09 20:43:32 -0500579 cqueryOutput, cqueryErr, err = context.issueBazelCommand(bazel.CqueryBuildRootRunName, "cquery",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500580 []string{fmt.Sprintf("kind(rule, deps(%s))", buildrootLabel)},
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400581 "--output=starlark",
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800582 "--starlark:file="+cqueryFileRelpath)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500583 err = ioutil.WriteFile(
584 absolutePath(filepath.Join(context.intermediatesDir(), "cquery.out")),
585 []byte(cqueryOutput), 0666)
586 if err != nil {
587 return err
588 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400589
590 if err != nil {
591 return err
592 }
593
594 cqueryResults := map[string]string{}
595 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
596 if strings.Contains(outputLine, ">>") {
597 splitLine := strings.SplitN(outputLine, ">>", 2)
598 cqueryResults[splitLine[0]] = splitLine[1]
599 }
600 }
601
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400602 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500603 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400604 context.results[val] = string(cqueryResult)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400605 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500606 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
607 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400608 }
609 }
610
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500611 // Issue an aquery command to retrieve action information about the bazel build tree.
612 //
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400613 // TODO(cparsons): Use --target_pattern_file to avoid command line limits.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500614 var aqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500615 aqueryOutput, _, err = context.issueBazelCommand(bazel.AqueryBuildRootRunName, "aquery",
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800616 []string{fmt.Sprintf("deps(%s)", buildrootLabel),
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500617 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
618 // proto sources, which would add a number of unnecessary dependencies.
619 "--output=jsonproto"})
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400620
621 if err != nil {
622 return err
623 }
624
Chris Parsons4f069892021-01-15 12:22:41 -0500625 context.buildStatements, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
626 if err != nil {
627 return err
628 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500629
630 // Issue a build command of the phony root to generate symlink forests for dependencies of the
631 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
632 // but some of symlinks may be required to resolve source dependencies of the build.
Chris Parsons808d84c2021-03-09 20:43:32 -0500633 _, _, err = context.issueBazelCommand(bazel.BazelBuildPhonyRootRunName, "build",
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500634 []string{"//:phonyroot"})
635
636 if err != nil {
637 return err
638 }
639
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400640 // Clear requests.
641 context.requests = map[cqueryKey]bool{}
642 return nil
643}
Chris Parsonsa798d962020-10-12 23:44:08 -0400644
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500645func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
646 return context.buildStatements
647}
648
649func (context *bazelContext) OutputBase() string {
650 return context.outputBase
651}
652
Chris Parsonsa798d962020-10-12 23:44:08 -0400653// Singleton used for registering BUILD file ninja dependencies (needed
654// for correctness of builds which use Bazel.
655func BazelSingleton() Singleton {
656 return &bazelSingleton{}
657}
658
659type bazelSingleton struct{}
660
661func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500662 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
663 if !ctx.Config().BazelContext.BazelEnabled() {
664 return
665 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400666
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500667 // Add ninja file dependencies for files which all bazel invocations require.
668 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100669 filepath.Dir(bootstrap.CmdlineModuleListFile()), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500670 ctx.AddNinjaFileDeps(bazelBuildList)
671
672 data, err := ioutil.ReadFile(bazelBuildList)
673 if err != nil {
674 ctx.Errorf(err.Error())
675 }
676 files := strings.Split(strings.TrimSpace(string(data)), "\n")
677 for _, file := range files {
678 ctx.AddNinjaFileDeps(file)
679 }
680
681 // Register bazel-owned build statements (obtained from the aquery invocation).
682 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500683 if len(buildStatement.Command) < 1 {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000684 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500685 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500686 rule := NewRuleBuilder(pctx, ctx)
687 cmd := rule.Command()
688 cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ && %s",
689 ctx.Config().BazelContext.OutputBase(), buildStatement.Command))
690
691 for _, outputPath := range buildStatement.OutputPaths {
692 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400693 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500694 for _, inputPath := range buildStatement.InputPaths {
695 cmd.Implicit(PathForBazelOut(ctx, inputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400696 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500697
Liz Kammerde116852021-03-25 16:42:37 -0400698 if depfile := buildStatement.Depfile; depfile != nil {
699 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
700 }
701
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500702 // This is required to silence warnings pertaining to unexpected timestamps. Particularly,
703 // some Bazel builtins (such as files in the bazel_tools directory) have far-future
704 // timestamps. Without restat, Ninja would emit warnings that the input files of a
705 // build statement have later timestamps than the outputs.
706 rule.Restat()
707
Liz Kammer13548d72020-12-16 11:13:30 -0800708 rule.Build(fmt.Sprintf("bazel %d", index), buildStatement.Mnemonic)
Chris Parsonsa798d962020-10-12 23:44:08 -0400709 }
710}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500711
712func getCqueryId(key cqueryKey) string {
713 return canonicalizeLabel(key.label) + "|" + getArchString(key)
714}
715
716func getArchString(key cqueryKey) string {
717 arch := key.archType.Name
718 if len(arch) > 0 {
719 return arch
720 } else {
721 return "x86_64"
722 }
723}