blob: 5a73666b1ba07f46a88066d771998d324bb94503 [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
Liz Kammerf29df7c2021-04-02 13:37:39 -040037type cqueryRequest interface {
38 // Name returns a string name for this request type. Such request type names must be unique,
39 // and must only consist of alphanumeric characters.
40 Name() string
41
42 // StarlarkFunctionBody returns a starlark function body to process this request type.
43 // The returned string is the body of a Starlark function which obtains
44 // all request-relevant information about a target and returns a string containing
45 // this information.
46 // The function should have the following properties:
47 // - `target` is the only parameter to this function (a configured target).
48 // - The return value must be a string.
49 // - The function body should not be indented outside of its own scope.
50 StarlarkFunctionBody() string
51}
52
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040053// Map key to describe bazel cquery requests.
54type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040055 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -040056 requestType cqueryRequest
Chris Parsons8d6e4332021-02-22 16:13:50 -050057 archType ArchType
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040058}
59
60type BazelContext interface {
61 // The below methods involve queuing cquery requests to be later invoked
62 // by bazel. If any of these methods return (_, false), then the request
63 // has been queued to be run later.
64
65 // Returns result files built by building the given bazel target label.
Chris Parsons944e7d02021-03-11 11:08:46 -050066 GetOutputFiles(label string, archType ArchType) ([]string, bool)
Chris Parsons8d6e4332021-02-22 16:13:50 -050067
Chris Parsons944e7d02021-03-11 11:08:46 -050068 // TODO(cparsons): Other cquery-related methods should be added here.
69 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
70 GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool)
Chris Parsons808d84c2021-03-09 20:43:32 -050071
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040072 // ** End cquery methods
73
74 // Issues commands to Bazel to receive results for all cquery requests
75 // queued in the BazelContext.
76 InvokeBazel() error
77
78 // Returns true if bazel is enabled for the given configuration.
79 BazelEnabled() bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050080
81 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
82 OutputBase() string
83
84 // Returns build statements which should get registered to reflect Bazel's outputs.
85 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040086}
87
88// A context object which tracks queued requests that need to be made to Bazel,
89// and their results after the requests have been made.
90type bazelContext struct {
91 homeDir string
92 bazelPath string
93 outputBase string
94 workspaceDir string
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040095 buildDir string
Patrice Arruda05ab2d02020-12-12 06:24:26 +000096 metricsDir string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040097
98 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
99 requestMutex sync.Mutex // requests can be written in parallel
100
101 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500102
103 // Build statements which should get registered to reflect Bazel's outputs.
104 buildStatements []bazel.BuildStatement
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400105}
106
107var _ BazelContext = &bazelContext{}
108
109// A bazel context to use when Bazel is disabled.
110type noopBazelContext struct{}
111
112var _ BazelContext = noopBazelContext{}
113
114// A bazel context to use for tests.
115type MockBazelContext struct {
116 AllFiles map[string][]string
117}
118
Chris Parsons944e7d02021-03-11 11:08:46 -0500119func (m MockBazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500120 result, ok := m.AllFiles[label]
121 return result, ok
122}
123
Chris Parsons944e7d02021-03-11 11:08:46 -0500124func (m MockBazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500125 result, ok := m.AllFiles[label]
126 return result, result, ok
127}
128
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400129func (m MockBazelContext) InvokeBazel() error {
130 panic("unimplemented")
131}
132
133func (m MockBazelContext) BazelEnabled() bool {
134 return true
135}
136
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500137func (m MockBazelContext) OutputBase() string {
138 return "outputbase"
139}
140
141func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
142 return []bazel.BuildStatement{}
143}
144
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400145var _ BazelContext = MockBazelContext{}
146
Chris Parsons944e7d02021-03-11 11:08:46 -0500147func (bazelCtx *bazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
148 rawString, ok := bazelCtx.cquery(label, cquery.GetOutputFiles, archType)
149 var ret []string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400150 if ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500151 bazelOutput := strings.TrimSpace(rawString)
Liz Kammerf29df7c2021-04-02 13:37:39 -0400152 ret = cquery.GetOutputFiles.ParseResult(bazelOutput)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400153 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500154 return ret, ok
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400155}
156
Chris Parsons944e7d02021-03-11 11:08:46 -0500157func (bazelCtx *bazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
158 var outputFiles []string
Chris Parsons808d84c2021-03-09 20:43:32 -0500159 var ccObjects []string
160
Chris Parsons944e7d02021-03-11 11:08:46 -0500161 result, ok := bazelCtx.cquery(label, cquery.GetOutputFilesAndCcObjectFiles, archType)
Chris Parsons808d84c2021-03-09 20:43:32 -0500162 if ok {
163 bazelOutput := strings.TrimSpace(result)
Liz Kammerf29df7c2021-04-02 13:37:39 -0400164 returnResult := cquery.GetOutputFilesAndCcObjectFiles.ParseResult(bazelOutput)
Chris Parsons944e7d02021-03-11 11:08:46 -0500165 outputFiles = returnResult.OutputFiles
166 ccObjects = returnResult.CcObjectFiles
Chris Parsons808d84c2021-03-09 20:43:32 -0500167 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500168
169 return outputFiles, ccObjects, ok
Chris Parsons808d84c2021-03-09 20:43:32 -0500170}
171
Chris Parsons944e7d02021-03-11 11:08:46 -0500172func (n noopBazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500173 panic("unimplemented")
174}
175
Chris Parsons944e7d02021-03-11 11:08:46 -0500176func (n noopBazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500177 panic("unimplemented")
178}
179
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400180func (n noopBazelContext) InvokeBazel() error {
181 panic("unimplemented")
182}
183
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500184func (m noopBazelContext) OutputBase() string {
185 return ""
186}
187
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400188func (n noopBazelContext) BazelEnabled() bool {
189 return false
190}
191
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500192func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
193 return []bazel.BuildStatement{}
194}
195
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400196func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons8b77a002020-10-27 18:59:25 -0400197 // TODO(cparsons): Assess USE_BAZEL=1 instead once "mixed Soong/Bazel builds"
198 // are production ready.
199 if c.Getenv("USE_BAZEL_ANALYSIS") != "1" {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400200 return noopBazelContext{}, nil
201 }
202
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400203 bazelCtx := bazelContext{buildDir: c.buildDir, requests: make(map[cqueryKey]bool)}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400204 missingEnvVars := []string{}
205 if len(c.Getenv("BAZEL_HOME")) > 1 {
206 bazelCtx.homeDir = c.Getenv("BAZEL_HOME")
207 } else {
208 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
209 }
210 if len(c.Getenv("BAZEL_PATH")) > 1 {
211 bazelCtx.bazelPath = c.Getenv("BAZEL_PATH")
212 } else {
213 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
214 }
215 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
216 bazelCtx.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
217 } else {
218 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
219 }
220 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
221 bazelCtx.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
222 } else {
223 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
224 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000225 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
226 bazelCtx.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
227 } else {
228 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
229 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400230 if len(missingEnvVars) > 0 {
231 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
232 } else {
233 return &bazelCtx, nil
234 }
235}
236
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000237func (context *bazelContext) BazelMetricsDir() string {
238 return context.metricsDir
239}
240
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400241func (context *bazelContext) BazelEnabled() bool {
242 return true
243}
244
245// Adds a cquery request to the Bazel request queue, to be later invoked, or
246// returns the result of the given request if the request was already made.
247// If the given request was already made (and the results are available), then
248// returns (result, true). If the request is queued but no results are available,
249// then returns ("", false).
Liz Kammerf29df7c2021-04-02 13:37:39 -0400250func (context *bazelContext) cquery(label string, requestType cqueryRequest,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500251 archType ArchType) (string, bool) {
252 key := cqueryKey{label, requestType, archType}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400253 if result, ok := context.results[key]; ok {
254 return result, true
255 } else {
256 context.requestMutex.Lock()
257 defer context.requestMutex.Unlock()
258 context.requests[key] = true
259 return "", false
260 }
261}
262
263func pwdPrefix() string {
264 // Darwin doesn't have /proc
265 if runtime.GOOS != "darwin" {
266 return "PWD=/proc/self/cwd"
267 }
268 return ""
269}
270
Chris Parsons808d84c2021-03-09 20:43:32 -0500271// Issues the given bazel command with given build label and additional flags.
272// Returns (stdout, stderr, error). The first and second return values are strings
273// containing the stdout and stderr of the run command, and an error is returned if
274// the invocation returned an error code.
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000275func (context *bazelContext) issueBazelCommand(runName bazel.RunName, command string, labels []string,
Chris Parsons808d84c2021-03-09 20:43:32 -0500276 extraFlags ...string) (string, string, error) {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400277
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500278 cmdFlags := []string{"--output_base=" + context.outputBase, command}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400279 cmdFlags = append(cmdFlags, labels...)
Chris Parsons8ccdb632020-11-17 15:41:01 -0500280 cmdFlags = append(cmdFlags, "--package_path=%workspace%/"+context.intermediatesDir())
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000281 cmdFlags = append(cmdFlags, "--profile="+shared.BazelMetricsFilename(context, runName))
Jingwen Chen91220d72021-03-24 02:18:33 -0400282
283 // Set default platforms to canonicalized values for mixed builds requests.
284 // If these are set in the bazelrc, they will have values that are
285 // non-canonicalized to @sourceroot labels, and thus be invalid when
286 // referenced from the buildroot.
287 //
288 // The actual platform values here may be overridden by configuration
289 // transitions from the buildroot.
Chris Parsonsee423b02021-02-08 23:04:59 -0500290 cmdFlags = append(cmdFlags,
Jingwen Chen91220d72021-03-24 02:18:33 -0400291 fmt.Sprintf("--platforms=%s", canonicalizeLabel("//build/bazel/platforms:android_x86_64")))
Chris Parsonsee423b02021-02-08 23:04:59 -0500292 cmdFlags = append(cmdFlags,
293 fmt.Sprintf("--extra_toolchains=%s", canonicalizeLabel("//prebuilts/clang/host/linux-x86:all")))
Jingwen Chen91220d72021-03-24 02:18:33 -0400294 // This should be parameterized on the host OS, but let's restrict to linux
295 // to keep things simple for now.
296 cmdFlags = append(cmdFlags,
297 fmt.Sprintf("--host_platform=%s", canonicalizeLabel("//build/bazel/platforms:linux_x86_64")))
298
Chris Parsons8d6e4332021-02-22 16:13:50 -0500299 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
300 cmdFlags = append(cmdFlags, "--experimental_repository_disable_download")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400301 cmdFlags = append(cmdFlags, extraFlags...)
302
303 bazelCmd := exec.Command(context.bazelPath, cmdFlags...)
304 bazelCmd.Dir = context.workspaceDir
Chris Parsons8d6e4332021-02-22 16:13:50 -0500305 bazelCmd.Env = append(os.Environ(), "HOME="+context.homeDir, pwdPrefix(),
306 // Disables local host detection of gcc; toolchain information is defined
307 // explicitly in BUILD files.
308 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
Colin Crossff0278b2020-10-09 19:24:15 -0700309 stderr := &bytes.Buffer{}
310 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400311
312 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500313 return "", string(stderr.Bytes()),
314 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400315 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500316 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400317 }
318}
319
Chris Parsons8ccdb632020-11-17 15:41:01 -0500320// Returns the string contents of a workspace file that should be output
321// adjacent to the main bzl file and build file.
322// This workspace file allows, via local_repository rule, sourcetree-level
323// BUILD targets to be referenced via @sourceroot.
324func (context *bazelContext) workspaceFileContents() []byte {
325 formatString := `
326# This file is generated by soong_build. Do not edit.
327local_repository(
328 name = "sourceroot",
Jingwen Chen63930982021-03-24 10:04:33 -0400329 path = "%[1]s",
Chris Parsons8ccdb632020-11-17 15:41:01 -0500330)
Liz Kammer8206d4f2021-03-03 16:40:52 -0500331
332local_repository(
333 name = "rules_cc",
Jingwen Chen63930982021-03-24 10:04:33 -0400334 path = "%[1]s/build/bazel/rules_cc",
335)
336
337local_repository(
338 name = "bazel_skylib",
339 path = "%[1]s/build/bazel/bazel_skylib",
Liz Kammer8206d4f2021-03-03 16:40:52 -0500340)
Chris Parsons8ccdb632020-11-17 15:41:01 -0500341`
Jingwen Chen63930982021-03-24 10:04:33 -0400342 return []byte(fmt.Sprintf(formatString, context.workspaceDir))
Chris Parsons8ccdb632020-11-17 15:41:01 -0500343}
344
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400345func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500346 // TODO(cparsons): Define configuration transitions programmatically based
347 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400348 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500349#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400350# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500351#####################################################
352
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400353def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500354 return {
Jingwen Chen91220d72021-03-24 02:18:33 -0400355 "//command_line_option:platforms": "@sourceroot//build/bazel/platforms:android_%s" % attr.arch,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500356 }
357
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400358_config_node_transition = transition(
359 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500360 inputs = [],
361 outputs = [
362 "//command_line_option:platforms",
363 ],
364)
365
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400366def _passthrough_rule_impl(ctx):
367 return [DefaultInfo(files = depset(ctx.files.deps))]
368
369config_node = rule(
370 implementation = _passthrough_rule_impl,
371 attrs = {
372 "arch" : attr.string(mandatory = True),
373 "deps" : attr.label_list(cfg = _config_node_transition),
374 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
375 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500376)
377
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400378
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500379# Rule representing the root of the build, to depend on all Bazel targets that
380# are required for the build. Building this target will build the entire Bazel
381# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400382mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400383 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500384 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400385 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500386 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400387)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500388
389def _phony_root_impl(ctx):
390 return []
391
392# Rule to depend on other targets but build nothing.
393# This is useful as follows: building a target of this rule will generate
394# symlink forests for all dependencies of the target, without executing any
395# actions of the build.
396phony_root = rule(
397 implementation = _phony_root_impl,
398 attrs = {"deps" : attr.label_list()},
399)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400400`
401 return []byte(contents)
402}
403
Chris Parsons8ccdb632020-11-17 15:41:01 -0500404// Returns a "canonicalized" corresponding to the given sourcetree-level label.
405// This abstraction is required because a sourcetree label such as //foo/bar:baz
406// must be referenced via the local repository prefix, such as
407// @sourceroot//foo/bar:baz.
408func canonicalizeLabel(label string) string {
409 if strings.HasPrefix(label, "//") {
410 return "@sourceroot" + label
411 } else {
412 return "@sourceroot//" + label
413 }
414}
415
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400416func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500417 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
418 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400419 formatString := `
420# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400421load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
422
423%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400424
425mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400426 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400427)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500428
429phony_root(name = "phonyroot",
430 deps = [":buildroot"],
431)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400432`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400433 configNodeFormatString := `
434config_node(name = "%s",
435 arch = "%s",
436 deps = [%s],
437)
438`
439
440 configNodesSection := ""
441
442 labelsByArch := map[string][]string{}
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400443 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500444 labelString := fmt.Sprintf("\"%s\"", canonicalizeLabel(val.label))
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400445 archString := getArchString(val)
446 labelsByArch[archString] = append(labelsByArch[archString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400447 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400448
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400449 configNodeLabels := []string{}
450 for archString, labels := range labelsByArch {
451 configNodeLabels = append(configNodeLabels, fmt.Sprintf("\":%s\"", archString))
452 labelsString := strings.Join(labels, ",\n ")
453 configNodesSection += fmt.Sprintf(configNodeFormatString, archString, archString, labelsString)
454 }
455
456 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(configNodeLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400457}
458
Chris Parsons944e7d02021-03-11 11:08:46 -0500459func indent(original string) string {
460 result := ""
461 for _, line := range strings.Split(original, "\n") {
462 result += " " + line + "\n"
463 }
464 return result
465}
466
Chris Parsons808d84c2021-03-09 20:43:32 -0500467// Returns the file contents of the buildroot.cquery file that should be used for the cquery
468// expression in order to obtain information about buildroot and its dependencies.
469// The contents of this file depend on the bazelContext's requests; requests are enumerated
470// and grouped by their request type. The data retrieved for each label depends on its
471// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400472func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400473 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons944e7d02021-03-11 11:08:46 -0500474 for val, _ := range context.requests {
475 cqueryId := getCqueryId(val)
476 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
477 requestTypeToCqueryIdEntries[val.requestType] =
478 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
479 }
480 labelRegistrationMapSection := ""
481 functionDefSection := ""
482 mainSwitchSection := ""
483
484 mapDeclarationFormatString := `
485%s = {
486 %s
487}
488`
489 functionDefFormatString := `
490def %s(target):
491%s
492`
493 mainSwitchSectionFormatString := `
494 if id_string in %s:
495 return id_string + ">>" + %s(target)
496`
497
Liz Kammer66ffdb72021-04-02 13:26:07 -0400498 for requestType, _ := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500499 labelMapName := requestType.Name() + "_Labels"
500 functionName := requestType.Name() + "_Fn"
501 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
502 labelMapName,
503 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
504 functionDefSection += fmt.Sprintf(functionDefFormatString,
505 functionName,
506 indent(requestType.StarlarkFunctionBody()))
507 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
508 labelMapName, functionName)
509 }
510
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400511 formatString := `
512# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400513
Chris Parsons944e7d02021-03-11 11:08:46 -0500514# Label Map Section
515%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500516
Chris Parsons944e7d02021-03-11 11:08:46 -0500517# Function Def Section
518%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500519
520def get_arch(target):
521 buildoptions = build_options(target)
522 platforms = build_options(target)["//command_line_option:platforms"]
523 if len(platforms) != 1:
524 # An individual configured target should have only one platform architecture.
525 # Note that it's fine for there to be multiple architectures for the same label,
526 # but each is its own configured target.
527 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
528 platform_name = build_options(target)["//command_line_option:platforms"][0].name
529 if platform_name == "host":
530 return "HOST"
Jingwen Chen91220d72021-03-24 02:18:33 -0400531 elif not platform_name.startswith("android_"):
532 fail("expected platform name of the form 'android_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500533 return "UNKNOWN"
Jingwen Chen91220d72021-03-24 02:18:33 -0400534 return platform_name[len("android_"):]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500535
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400536def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500537 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500538
539 # Main switch section
540 %s
541 # This target was not requested via cquery, and thus must be a dependency
542 # of a requested target.
543 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400544`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400545
Chris Parsons944e7d02021-03-11 11:08:46 -0500546 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
547 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400548}
549
Chris Parsons8ccdb632020-11-17 15:41:01 -0500550// Returns a workspace-relative path containing build-related metadata required
551// for interfacing with Bazel. Example: out/soong/bazel.
552func (context *bazelContext) intermediatesDir() string {
553 return filepath.Join(context.buildDir, "bazel")
554}
555
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400556// Issues commands to Bazel to receive results for all cquery requests
557// queued in the BazelContext.
558func (context *bazelContext) InvokeBazel() error {
559 context.results = make(map[cqueryKey]string)
560
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400561 var cqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500562 var cqueryErr string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400563 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500564
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500565 intermediatesDirPath := absolutePath(context.intermediatesDir())
566 if _, err := os.Stat(intermediatesDirPath); os.IsNotExist(err) {
567 err = os.Mkdir(intermediatesDirPath, 0777)
568 }
569
Chris Parsons8ccdb632020-11-17 15:41:01 -0500570 if err != nil {
571 return err
572 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400573 err = ioutil.WriteFile(
Chris Parsons8ccdb632020-11-17 15:41:01 -0500574 absolutePath(filepath.Join(context.intermediatesDir(), "main.bzl")),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400575 context.mainBzlFileContents(), 0666)
576 if err != nil {
577 return err
578 }
579 err = ioutil.WriteFile(
Chris Parsons8ccdb632020-11-17 15:41:01 -0500580 absolutePath(filepath.Join(context.intermediatesDir(), "BUILD.bazel")),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400581 context.mainBuildFileContents(), 0666)
582 if err != nil {
583 return err
584 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800585 cqueryFileRelpath := filepath.Join(context.intermediatesDir(), "buildroot.cquery")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400586 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800587 absolutePath(cqueryFileRelpath),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400588 context.cqueryStarlarkFileContents(), 0666)
589 if err != nil {
590 return err
591 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800592 workspaceFileRelpath := filepath.Join(context.intermediatesDir(), "WORKSPACE.bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500593 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800594 absolutePath(workspaceFileRelpath),
Chris Parsons8ccdb632020-11-17 15:41:01 -0500595 context.workspaceFileContents(), 0666)
596 if err != nil {
597 return err
598 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800599 buildrootLabel := "//:buildroot"
Chris Parsons808d84c2021-03-09 20:43:32 -0500600 cqueryOutput, cqueryErr, err = context.issueBazelCommand(bazel.CqueryBuildRootRunName, "cquery",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500601 []string{fmt.Sprintf("kind(rule, deps(%s))", buildrootLabel)},
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400602 "--output=starlark",
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800603 "--starlark:file="+cqueryFileRelpath)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500604 err = ioutil.WriteFile(
605 absolutePath(filepath.Join(context.intermediatesDir(), "cquery.out")),
606 []byte(cqueryOutput), 0666)
607 if err != nil {
608 return err
609 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400610
611 if err != nil {
612 return err
613 }
614
615 cqueryResults := map[string]string{}
616 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
617 if strings.Contains(outputLine, ">>") {
618 splitLine := strings.SplitN(outputLine, ">>", 2)
619 cqueryResults[splitLine[0]] = splitLine[1]
620 }
621 }
622
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400623 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500624 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400625 context.results[val] = string(cqueryResult)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400626 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500627 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
628 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400629 }
630 }
631
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500632 // Issue an aquery command to retrieve action information about the bazel build tree.
633 //
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400634 // TODO(cparsons): Use --target_pattern_file to avoid command line limits.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500635 var aqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500636 aqueryOutput, _, err = context.issueBazelCommand(bazel.AqueryBuildRootRunName, "aquery",
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800637 []string{fmt.Sprintf("deps(%s)", buildrootLabel),
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500638 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
639 // proto sources, which would add a number of unnecessary dependencies.
640 "--output=jsonproto"})
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400641
642 if err != nil {
643 return err
644 }
645
Chris Parsons4f069892021-01-15 12:22:41 -0500646 context.buildStatements, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
647 if err != nil {
648 return err
649 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500650
651 // Issue a build command of the phony root to generate symlink forests for dependencies of the
652 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
653 // but some of symlinks may be required to resolve source dependencies of the build.
Chris Parsons808d84c2021-03-09 20:43:32 -0500654 _, _, err = context.issueBazelCommand(bazel.BazelBuildPhonyRootRunName, "build",
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500655 []string{"//:phonyroot"})
656
657 if err != nil {
658 return err
659 }
660
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400661 // Clear requests.
662 context.requests = map[cqueryKey]bool{}
663 return nil
664}
Chris Parsonsa798d962020-10-12 23:44:08 -0400665
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500666func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
667 return context.buildStatements
668}
669
670func (context *bazelContext) OutputBase() string {
671 return context.outputBase
672}
673
Chris Parsonsa798d962020-10-12 23:44:08 -0400674// Singleton used for registering BUILD file ninja dependencies (needed
675// for correctness of builds which use Bazel.
676func BazelSingleton() Singleton {
677 return &bazelSingleton{}
678}
679
680type bazelSingleton struct{}
681
682func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500683 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
684 if !ctx.Config().BazelContext.BazelEnabled() {
685 return
686 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400687
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500688 // Add ninja file dependencies for files which all bazel invocations require.
689 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100690 filepath.Dir(bootstrap.CmdlineModuleListFile()), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500691 ctx.AddNinjaFileDeps(bazelBuildList)
692
693 data, err := ioutil.ReadFile(bazelBuildList)
694 if err != nil {
695 ctx.Errorf(err.Error())
696 }
697 files := strings.Split(strings.TrimSpace(string(data)), "\n")
698 for _, file := range files {
699 ctx.AddNinjaFileDeps(file)
700 }
701
702 // Register bazel-owned build statements (obtained from the aquery invocation).
703 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500704 if len(buildStatement.Command) < 1 {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000705 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500706 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500707 rule := NewRuleBuilder(pctx, ctx)
708 cmd := rule.Command()
709 cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ && %s",
710 ctx.Config().BazelContext.OutputBase(), buildStatement.Command))
711
712 for _, outputPath := range buildStatement.OutputPaths {
713 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400714 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500715 for _, inputPath := range buildStatement.InputPaths {
716 cmd.Implicit(PathForBazelOut(ctx, inputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400717 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500718
Liz Kammerde116852021-03-25 16:42:37 -0400719 if depfile := buildStatement.Depfile; depfile != nil {
720 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
721 }
722
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500723 // This is required to silence warnings pertaining to unexpected timestamps. Particularly,
724 // some Bazel builtins (such as files in the bazel_tools directory) have far-future
725 // timestamps. Without restat, Ninja would emit warnings that the input files of a
726 // build statement have later timestamps than the outputs.
727 rule.Restat()
728
Liz Kammer13548d72020-12-16 11:13:30 -0800729 rule.Build(fmt.Sprintf("bazel %d", index), buildStatement.Mnemonic)
Chris Parsonsa798d962020-10-12 23:44:08 -0400730 }
731}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500732
733func getCqueryId(key cqueryKey) string {
734 return canonicalizeLabel(key.label) + "|" + getArchString(key)
735}
736
737func getArchString(key cqueryKey) string {
738 arch := key.archType.Name
739 if len(arch) > 0 {
740 return arch
741 } else {
742 return "x86_64"
743 }
744}