blob: 65115d1c31b18db7522a56b4df416a3cad228c4f [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))
Jingwen Chen91220d72021-03-24 02:18:33 -0400273
274 // Set default platforms to canonicalized values for mixed builds requests.
275 // If these are set in the bazelrc, they will have values that are
276 // non-canonicalized to @sourceroot labels, and thus be invalid when
277 // referenced from the buildroot.
278 //
279 // The actual platform values here may be overridden by configuration
280 // transitions from the buildroot.
Chris Parsonsee423b02021-02-08 23:04:59 -0500281 cmdFlags = append(cmdFlags,
Jingwen Chen91220d72021-03-24 02:18:33 -0400282 fmt.Sprintf("--platforms=%s", canonicalizeLabel("//build/bazel/platforms:android_x86_64")))
Chris Parsonsee423b02021-02-08 23:04:59 -0500283 cmdFlags = append(cmdFlags,
284 fmt.Sprintf("--extra_toolchains=%s", canonicalizeLabel("//prebuilts/clang/host/linux-x86:all")))
Jingwen Chen91220d72021-03-24 02:18:33 -0400285 // This should be parameterized on the host OS, but let's restrict to linux
286 // to keep things simple for now.
287 cmdFlags = append(cmdFlags,
288 fmt.Sprintf("--host_platform=%s", canonicalizeLabel("//build/bazel/platforms:linux_x86_64")))
289
Chris Parsons8d6e4332021-02-22 16:13:50 -0500290 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
291 cmdFlags = append(cmdFlags, "--experimental_repository_disable_download")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400292 cmdFlags = append(cmdFlags, extraFlags...)
293
294 bazelCmd := exec.Command(context.bazelPath, cmdFlags...)
295 bazelCmd.Dir = context.workspaceDir
Chris Parsons8d6e4332021-02-22 16:13:50 -0500296 bazelCmd.Env = append(os.Environ(), "HOME="+context.homeDir, pwdPrefix(),
297 // Disables local host detection of gcc; toolchain information is defined
298 // explicitly in BUILD files.
299 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
Colin Crossff0278b2020-10-09 19:24:15 -0700300 stderr := &bytes.Buffer{}
301 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400302
303 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500304 return "", string(stderr.Bytes()),
305 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400306 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500307 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400308 }
309}
310
Chris Parsons8ccdb632020-11-17 15:41:01 -0500311// Returns the string contents of a workspace file that should be output
312// adjacent to the main bzl file and build file.
313// This workspace file allows, via local_repository rule, sourcetree-level
314// BUILD targets to be referenced via @sourceroot.
315func (context *bazelContext) workspaceFileContents() []byte {
316 formatString := `
317# This file is generated by soong_build. Do not edit.
318local_repository(
319 name = "sourceroot",
320 path = "%s",
321)
Liz Kammer8206d4f2021-03-03 16:40:52 -0500322
323local_repository(
324 name = "rules_cc",
325 path = "%s/build/bazel/rules_cc",
326)
Chris Parsons8ccdb632020-11-17 15:41:01 -0500327`
Liz Kammer8206d4f2021-03-03 16:40:52 -0500328 return []byte(fmt.Sprintf(formatString, context.workspaceDir, context.workspaceDir))
Chris Parsons8ccdb632020-11-17 15:41:01 -0500329}
330
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400331func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500332 // TODO(cparsons): Define configuration transitions programmatically based
333 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400334 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500335#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400336# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500337#####################################################
338
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400339def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500340 return {
Jingwen Chen91220d72021-03-24 02:18:33 -0400341 "//command_line_option:platforms": "@sourceroot//build/bazel/platforms:android_%s" % attr.arch,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500342 }
343
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400344_config_node_transition = transition(
345 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500346 inputs = [],
347 outputs = [
348 "//command_line_option:platforms",
349 ],
350)
351
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400352def _passthrough_rule_impl(ctx):
353 return [DefaultInfo(files = depset(ctx.files.deps))]
354
355config_node = rule(
356 implementation = _passthrough_rule_impl,
357 attrs = {
358 "arch" : attr.string(mandatory = True),
359 "deps" : attr.label_list(cfg = _config_node_transition),
360 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
361 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500362)
363
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400364
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500365# Rule representing the root of the build, to depend on all Bazel targets that
366# are required for the build. Building this target will build the entire Bazel
367# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400368mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400369 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500370 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400371 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500372 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400373)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500374
375def _phony_root_impl(ctx):
376 return []
377
378# Rule to depend on other targets but build nothing.
379# This is useful as follows: building a target of this rule will generate
380# symlink forests for all dependencies of the target, without executing any
381# actions of the build.
382phony_root = rule(
383 implementation = _phony_root_impl,
384 attrs = {"deps" : attr.label_list()},
385)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400386`
387 return []byte(contents)
388}
389
Chris Parsons8ccdb632020-11-17 15:41:01 -0500390// Returns a "canonicalized" corresponding to the given sourcetree-level label.
391// This abstraction is required because a sourcetree label such as //foo/bar:baz
392// must be referenced via the local repository prefix, such as
393// @sourceroot//foo/bar:baz.
394func canonicalizeLabel(label string) string {
395 if strings.HasPrefix(label, "//") {
396 return "@sourceroot" + label
397 } else {
398 return "@sourceroot//" + label
399 }
400}
401
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400402func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500403 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
404 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400405 formatString := `
406# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400407load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
408
409%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400410
411mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400412 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400413)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500414
415phony_root(name = "phonyroot",
416 deps = [":buildroot"],
417)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400418`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400419 configNodeFormatString := `
420config_node(name = "%s",
421 arch = "%s",
422 deps = [%s],
423)
424`
425
426 configNodesSection := ""
427
428 labelsByArch := map[string][]string{}
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400429 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500430 labelString := fmt.Sprintf("\"%s\"", canonicalizeLabel(val.label))
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400431 archString := getArchString(val)
432 labelsByArch[archString] = append(labelsByArch[archString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400433 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400434
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400435 configNodeLabels := []string{}
436 for archString, labels := range labelsByArch {
437 configNodeLabels = append(configNodeLabels, fmt.Sprintf("\":%s\"", archString))
438 labelsString := strings.Join(labels, ",\n ")
439 configNodesSection += fmt.Sprintf(configNodeFormatString, archString, archString, labelsString)
440 }
441
442 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(configNodeLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400443}
444
Chris Parsons944e7d02021-03-11 11:08:46 -0500445func indent(original string) string {
446 result := ""
447 for _, line := range strings.Split(original, "\n") {
448 result += " " + line + "\n"
449 }
450 return result
451}
452
Chris Parsons808d84c2021-03-09 20:43:32 -0500453// Returns the file contents of the buildroot.cquery file that should be used for the cquery
454// expression in order to obtain information about buildroot and its dependencies.
455// The contents of this file depend on the bazelContext's requests; requests are enumerated
456// and grouped by their request type. The data retrieved for each label depends on its
457// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400458func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Chris Parsons944e7d02021-03-11 11:08:46 -0500459 requestTypeToCqueryIdEntries := map[cquery.RequestType][]string{}
460 for val, _ := range context.requests {
461 cqueryId := getCqueryId(val)
462 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
463 requestTypeToCqueryIdEntries[val.requestType] =
464 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
465 }
466 labelRegistrationMapSection := ""
467 functionDefSection := ""
468 mainSwitchSection := ""
469
470 mapDeclarationFormatString := `
471%s = {
472 %s
473}
474`
475 functionDefFormatString := `
476def %s(target):
477%s
478`
479 mainSwitchSectionFormatString := `
480 if id_string in %s:
481 return id_string + ">>" + %s(target)
482`
483
484 for _, requestType := range cquery.RequestTypes {
485 labelMapName := requestType.Name() + "_Labels"
486 functionName := requestType.Name() + "_Fn"
487 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
488 labelMapName,
489 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
490 functionDefSection += fmt.Sprintf(functionDefFormatString,
491 functionName,
492 indent(requestType.StarlarkFunctionBody()))
493 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
494 labelMapName, functionName)
495 }
496
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400497 formatString := `
498# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400499
Chris Parsons944e7d02021-03-11 11:08:46 -0500500# Label Map Section
501%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500502
Chris Parsons944e7d02021-03-11 11:08:46 -0500503# Function Def Section
504%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500505
506def get_arch(target):
507 buildoptions = build_options(target)
508 platforms = build_options(target)["//command_line_option:platforms"]
509 if len(platforms) != 1:
510 # An individual configured target should have only one platform architecture.
511 # Note that it's fine for there to be multiple architectures for the same label,
512 # but each is its own configured target.
513 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
514 platform_name = build_options(target)["//command_line_option:platforms"][0].name
515 if platform_name == "host":
516 return "HOST"
Jingwen Chen91220d72021-03-24 02:18:33 -0400517 elif not platform_name.startswith("android_"):
518 fail("expected platform name of the form 'android_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500519 return "UNKNOWN"
Jingwen Chen91220d72021-03-24 02:18:33 -0400520 return platform_name[len("android_"):]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500521
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400522def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500523 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500524
525 # Main switch section
526 %s
527 # This target was not requested via cquery, and thus must be a dependency
528 # of a requested target.
529 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400530`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400531
Chris Parsons944e7d02021-03-11 11:08:46 -0500532 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
533 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400534}
535
Chris Parsons8ccdb632020-11-17 15:41:01 -0500536// Returns a workspace-relative path containing build-related metadata required
537// for interfacing with Bazel. Example: out/soong/bazel.
538func (context *bazelContext) intermediatesDir() string {
539 return filepath.Join(context.buildDir, "bazel")
540}
541
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400542// Issues commands to Bazel to receive results for all cquery requests
543// queued in the BazelContext.
544func (context *bazelContext) InvokeBazel() error {
545 context.results = make(map[cqueryKey]string)
546
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400547 var cqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500548 var cqueryErr string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400549 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500550
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500551 intermediatesDirPath := absolutePath(context.intermediatesDir())
552 if _, err := os.Stat(intermediatesDirPath); os.IsNotExist(err) {
553 err = os.Mkdir(intermediatesDirPath, 0777)
554 }
555
Chris Parsons8ccdb632020-11-17 15:41:01 -0500556 if err != nil {
557 return err
558 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400559 err = ioutil.WriteFile(
Chris Parsons8ccdb632020-11-17 15:41:01 -0500560 absolutePath(filepath.Join(context.intermediatesDir(), "main.bzl")),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400561 context.mainBzlFileContents(), 0666)
562 if err != nil {
563 return err
564 }
565 err = ioutil.WriteFile(
Chris Parsons8ccdb632020-11-17 15:41:01 -0500566 absolutePath(filepath.Join(context.intermediatesDir(), "BUILD.bazel")),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400567 context.mainBuildFileContents(), 0666)
568 if err != nil {
569 return err
570 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800571 cqueryFileRelpath := filepath.Join(context.intermediatesDir(), "buildroot.cquery")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400572 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800573 absolutePath(cqueryFileRelpath),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400574 context.cqueryStarlarkFileContents(), 0666)
575 if err != nil {
576 return err
577 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800578 workspaceFileRelpath := filepath.Join(context.intermediatesDir(), "WORKSPACE.bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500579 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800580 absolutePath(workspaceFileRelpath),
Chris Parsons8ccdb632020-11-17 15:41:01 -0500581 context.workspaceFileContents(), 0666)
582 if err != nil {
583 return err
584 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800585 buildrootLabel := "//:buildroot"
Chris Parsons808d84c2021-03-09 20:43:32 -0500586 cqueryOutput, cqueryErr, err = context.issueBazelCommand(bazel.CqueryBuildRootRunName, "cquery",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500587 []string{fmt.Sprintf("kind(rule, deps(%s))", buildrootLabel)},
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400588 "--output=starlark",
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800589 "--starlark:file="+cqueryFileRelpath)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500590 err = ioutil.WriteFile(
591 absolutePath(filepath.Join(context.intermediatesDir(), "cquery.out")),
592 []byte(cqueryOutput), 0666)
593 if err != nil {
594 return err
595 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400596
597 if err != nil {
598 return err
599 }
600
601 cqueryResults := map[string]string{}
602 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
603 if strings.Contains(outputLine, ">>") {
604 splitLine := strings.SplitN(outputLine, ">>", 2)
605 cqueryResults[splitLine[0]] = splitLine[1]
606 }
607 }
608
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400609 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500610 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400611 context.results[val] = string(cqueryResult)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400612 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500613 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
614 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400615 }
616 }
617
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500618 // Issue an aquery command to retrieve action information about the bazel build tree.
619 //
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400620 // TODO(cparsons): Use --target_pattern_file to avoid command line limits.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500621 var aqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500622 aqueryOutput, _, err = context.issueBazelCommand(bazel.AqueryBuildRootRunName, "aquery",
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800623 []string{fmt.Sprintf("deps(%s)", buildrootLabel),
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500624 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
625 // proto sources, which would add a number of unnecessary dependencies.
626 "--output=jsonproto"})
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400627
628 if err != nil {
629 return err
630 }
631
Chris Parsons4f069892021-01-15 12:22:41 -0500632 context.buildStatements, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
633 if err != nil {
634 return err
635 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500636
637 // Issue a build command of the phony root to generate symlink forests for dependencies of the
638 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
639 // but some of symlinks may be required to resolve source dependencies of the build.
Chris Parsons808d84c2021-03-09 20:43:32 -0500640 _, _, err = context.issueBazelCommand(bazel.BazelBuildPhonyRootRunName, "build",
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500641 []string{"//:phonyroot"})
642
643 if err != nil {
644 return err
645 }
646
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400647 // Clear requests.
648 context.requests = map[cqueryKey]bool{}
649 return nil
650}
Chris Parsonsa798d962020-10-12 23:44:08 -0400651
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500652func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
653 return context.buildStatements
654}
655
656func (context *bazelContext) OutputBase() string {
657 return context.outputBase
658}
659
Chris Parsonsa798d962020-10-12 23:44:08 -0400660// Singleton used for registering BUILD file ninja dependencies (needed
661// for correctness of builds which use Bazel.
662func BazelSingleton() Singleton {
663 return &bazelSingleton{}
664}
665
666type bazelSingleton struct{}
667
668func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500669 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
670 if !ctx.Config().BazelContext.BazelEnabled() {
671 return
672 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400673
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500674 // Add ninja file dependencies for files which all bazel invocations require.
675 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100676 filepath.Dir(bootstrap.CmdlineModuleListFile()), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500677 ctx.AddNinjaFileDeps(bazelBuildList)
678
679 data, err := ioutil.ReadFile(bazelBuildList)
680 if err != nil {
681 ctx.Errorf(err.Error())
682 }
683 files := strings.Split(strings.TrimSpace(string(data)), "\n")
684 for _, file := range files {
685 ctx.AddNinjaFileDeps(file)
686 }
687
688 // Register bazel-owned build statements (obtained from the aquery invocation).
689 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500690 if len(buildStatement.Command) < 1 {
691 panic(fmt.Sprintf("unhandled build statement: %s", buildStatement))
692 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500693 rule := NewRuleBuilder(pctx, ctx)
694 cmd := rule.Command()
695 cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ && %s",
696 ctx.Config().BazelContext.OutputBase(), buildStatement.Command))
697
698 for _, outputPath := range buildStatement.OutputPaths {
699 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400700 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500701 for _, inputPath := range buildStatement.InputPaths {
702 cmd.Implicit(PathForBazelOut(ctx, inputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400703 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500704
705 // This is required to silence warnings pertaining to unexpected timestamps. Particularly,
706 // some Bazel builtins (such as files in the bazel_tools directory) have far-future
707 // timestamps. Without restat, Ninja would emit warnings that the input files of a
708 // build statement have later timestamps than the outputs.
709 rule.Restat()
710
Liz Kammer13548d72020-12-16 11:13:30 -0800711 rule.Build(fmt.Sprintf("bazel %d", index), buildStatement.Mnemonic)
Chris Parsonsa798d962020-10-12 23:44:08 -0400712 }
713}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500714
715func getCqueryId(key cqueryKey) string {
716 return canonicalizeLabel(key.label) + "|" + getArchString(key)
717}
718
719func getArchString(key cqueryKey) string {
720 arch := key.archType.Name
721 if len(arch) > 0 {
722 return arch
723 } else {
724 return "x86_64"
725 }
726}