blob: 28c0e53079df723f9f00ec68efa2c7f960ba39a1 [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
Liz Kammer3f9e1552021-04-02 18:47:09 -040072 // GetPrebuiltCcStaticLibraryFiles returns paths to prebuilt cc static libraries, and whether the
73 // results were available
74 GetPrebuiltCcStaticLibraryFiles(label string, archType ArchType) ([]string, bool)
75
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040076 // ** End cquery methods
77
78 // Issues commands to Bazel to receive results for all cquery requests
79 // queued in the BazelContext.
80 InvokeBazel() error
81
82 // Returns true if bazel is enabled for the given configuration.
83 BazelEnabled() bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050084
85 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
86 OutputBase() string
87
88 // Returns build statements which should get registered to reflect Bazel's outputs.
89 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040090}
91
92// A context object which tracks queued requests that need to be made to Bazel,
93// and their results after the requests have been made.
94type bazelContext struct {
95 homeDir string
96 bazelPath string
97 outputBase string
98 workspaceDir string
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040099 buildDir string
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000100 metricsDir string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400101
102 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
103 requestMutex sync.Mutex // requests can be written in parallel
104
105 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500106
107 // Build statements which should get registered to reflect Bazel's outputs.
108 buildStatements []bazel.BuildStatement
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400109}
110
111var _ BazelContext = &bazelContext{}
112
113// A bazel context to use when Bazel is disabled.
114type noopBazelContext struct{}
115
116var _ BazelContext = noopBazelContext{}
117
118// A bazel context to use for tests.
119type MockBazelContext struct {
120 AllFiles map[string][]string
121}
122
Chris Parsons944e7d02021-03-11 11:08:46 -0500123func (m MockBazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500124 result, ok := m.AllFiles[label]
125 return result, ok
126}
127
Chris Parsons944e7d02021-03-11 11:08:46 -0500128func (m MockBazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500129 result, ok := m.AllFiles[label]
130 return result, result, ok
131}
132
Liz Kammer3f9e1552021-04-02 18:47:09 -0400133func (m MockBazelContext) GetPrebuiltCcStaticLibraryFiles(label string, archType ArchType) ([]string, bool) {
134 result, ok := m.AllFiles[label]
135 return result, ok
136}
137
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400138func (m MockBazelContext) InvokeBazel() error {
139 panic("unimplemented")
140}
141
142func (m MockBazelContext) BazelEnabled() bool {
143 return true
144}
145
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500146func (m MockBazelContext) OutputBase() string {
147 return "outputbase"
148}
149
150func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
151 return []bazel.BuildStatement{}
152}
153
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400154var _ BazelContext = MockBazelContext{}
155
Chris Parsons944e7d02021-03-11 11:08:46 -0500156func (bazelCtx *bazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
157 rawString, ok := bazelCtx.cquery(label, cquery.GetOutputFiles, archType)
158 var ret []string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400159 if ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500160 bazelOutput := strings.TrimSpace(rawString)
Liz Kammerf29df7c2021-04-02 13:37:39 -0400161 ret = cquery.GetOutputFiles.ParseResult(bazelOutput)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400162 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500163 return ret, ok
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400164}
165
Chris Parsons944e7d02021-03-11 11:08:46 -0500166func (bazelCtx *bazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
167 var outputFiles []string
Chris Parsons808d84c2021-03-09 20:43:32 -0500168 var ccObjects []string
169
Chris Parsons944e7d02021-03-11 11:08:46 -0500170 result, ok := bazelCtx.cquery(label, cquery.GetOutputFilesAndCcObjectFiles, archType)
Chris Parsons808d84c2021-03-09 20:43:32 -0500171 if ok {
172 bazelOutput := strings.TrimSpace(result)
Liz Kammerf29df7c2021-04-02 13:37:39 -0400173 returnResult := cquery.GetOutputFilesAndCcObjectFiles.ParseResult(bazelOutput)
Chris Parsons944e7d02021-03-11 11:08:46 -0500174 outputFiles = returnResult.OutputFiles
175 ccObjects = returnResult.CcObjectFiles
Chris Parsons808d84c2021-03-09 20:43:32 -0500176 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500177
178 return outputFiles, ccObjects, ok
Chris Parsons808d84c2021-03-09 20:43:32 -0500179}
180
Liz Kammer3f9e1552021-04-02 18:47:09 -0400181// GetPrebuiltCcStaticLibraryFiles returns a slice of prebuilt static libraries for the given
182// label/archType if there are query results; otherwise, it enqueues the query and returns false.
183func (bazelCtx *bazelContext) GetPrebuiltCcStaticLibraryFiles(label string, archType ArchType) ([]string, bool) {
184 result, ok := bazelCtx.cquery(label, cquery.GetPrebuiltCcStaticLibraryFiles, archType)
185 if !ok {
186 return nil, false
187 }
188
189 bazelOutput := strings.TrimSpace(result)
190 ret := cquery.GetPrebuiltCcStaticLibraryFiles.ParseResult(bazelOutput)
191 return ret, ok
192}
193
Chris Parsons944e7d02021-03-11 11:08:46 -0500194func (n noopBazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500195 panic("unimplemented")
196}
197
Chris Parsons944e7d02021-03-11 11:08:46 -0500198func (n noopBazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500199 panic("unimplemented")
200}
201
Liz Kammer3f9e1552021-04-02 18:47:09 -0400202func (n noopBazelContext) GetPrebuiltCcStaticLibraryFiles(label string, archType ArchType) ([]string, bool) {
203 panic("unimplemented")
204}
205
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400206func (n noopBazelContext) InvokeBazel() error {
207 panic("unimplemented")
208}
209
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500210func (m noopBazelContext) OutputBase() string {
211 return ""
212}
213
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400214func (n noopBazelContext) BazelEnabled() bool {
215 return false
216}
217
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500218func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
219 return []bazel.BuildStatement{}
220}
221
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400222func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons8b77a002020-10-27 18:59:25 -0400223 // TODO(cparsons): Assess USE_BAZEL=1 instead once "mixed Soong/Bazel builds"
224 // are production ready.
225 if c.Getenv("USE_BAZEL_ANALYSIS") != "1" {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400226 return noopBazelContext{}, nil
227 }
228
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400229 bazelCtx := bazelContext{buildDir: c.buildDir, requests: make(map[cqueryKey]bool)}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400230 missingEnvVars := []string{}
231 if len(c.Getenv("BAZEL_HOME")) > 1 {
232 bazelCtx.homeDir = c.Getenv("BAZEL_HOME")
233 } else {
234 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
235 }
236 if len(c.Getenv("BAZEL_PATH")) > 1 {
237 bazelCtx.bazelPath = c.Getenv("BAZEL_PATH")
238 } else {
239 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
240 }
241 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
242 bazelCtx.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
243 } else {
244 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
245 }
246 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
247 bazelCtx.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
248 } else {
249 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
250 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000251 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
252 bazelCtx.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
253 } else {
254 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
255 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400256 if len(missingEnvVars) > 0 {
257 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
258 } else {
259 return &bazelCtx, nil
260 }
261}
262
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000263func (context *bazelContext) BazelMetricsDir() string {
264 return context.metricsDir
265}
266
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400267func (context *bazelContext) BazelEnabled() bool {
268 return true
269}
270
271// Adds a cquery request to the Bazel request queue, to be later invoked, or
272// returns the result of the given request if the request was already made.
273// If the given request was already made (and the results are available), then
274// returns (result, true). If the request is queued but no results are available,
275// then returns ("", false).
Liz Kammerf29df7c2021-04-02 13:37:39 -0400276func (context *bazelContext) cquery(label string, requestType cqueryRequest,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500277 archType ArchType) (string, bool) {
278 key := cqueryKey{label, requestType, archType}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400279 if result, ok := context.results[key]; ok {
280 return result, true
281 } else {
282 context.requestMutex.Lock()
283 defer context.requestMutex.Unlock()
284 context.requests[key] = true
285 return "", false
286 }
287}
288
289func pwdPrefix() string {
290 // Darwin doesn't have /proc
291 if runtime.GOOS != "darwin" {
292 return "PWD=/proc/self/cwd"
293 }
294 return ""
295}
296
Chris Parsons808d84c2021-03-09 20:43:32 -0500297// Issues the given bazel command with given build label and additional flags.
298// Returns (stdout, stderr, error). The first and second return values are strings
299// containing the stdout and stderr of the run command, and an error is returned if
300// the invocation returned an error code.
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000301func (context *bazelContext) issueBazelCommand(runName bazel.RunName, command string, labels []string,
Chris Parsons808d84c2021-03-09 20:43:32 -0500302 extraFlags ...string) (string, string, error) {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400303
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500304 cmdFlags := []string{"--output_base=" + context.outputBase, command}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400305 cmdFlags = append(cmdFlags, labels...)
Chris Parsons8ccdb632020-11-17 15:41:01 -0500306 cmdFlags = append(cmdFlags, "--package_path=%workspace%/"+context.intermediatesDir())
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000307 cmdFlags = append(cmdFlags, "--profile="+shared.BazelMetricsFilename(context, runName))
Jingwen Chen91220d72021-03-24 02:18:33 -0400308
309 // Set default platforms to canonicalized values for mixed builds requests.
310 // If these are set in the bazelrc, they will have values that are
311 // non-canonicalized to @sourceroot labels, and thus be invalid when
312 // referenced from the buildroot.
313 //
314 // The actual platform values here may be overridden by configuration
315 // transitions from the buildroot.
Chris Parsonsee423b02021-02-08 23:04:59 -0500316 cmdFlags = append(cmdFlags,
Jingwen Chen91220d72021-03-24 02:18:33 -0400317 fmt.Sprintf("--platforms=%s", canonicalizeLabel("//build/bazel/platforms:android_x86_64")))
Chris Parsonsee423b02021-02-08 23:04:59 -0500318 cmdFlags = append(cmdFlags,
319 fmt.Sprintf("--extra_toolchains=%s", canonicalizeLabel("//prebuilts/clang/host/linux-x86:all")))
Jingwen Chen91220d72021-03-24 02:18:33 -0400320 // This should be parameterized on the host OS, but let's restrict to linux
321 // to keep things simple for now.
322 cmdFlags = append(cmdFlags,
323 fmt.Sprintf("--host_platform=%s", canonicalizeLabel("//build/bazel/platforms:linux_x86_64")))
324
Chris Parsons8d6e4332021-02-22 16:13:50 -0500325 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
326 cmdFlags = append(cmdFlags, "--experimental_repository_disable_download")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400327 cmdFlags = append(cmdFlags, extraFlags...)
328
329 bazelCmd := exec.Command(context.bazelPath, cmdFlags...)
330 bazelCmd.Dir = context.workspaceDir
Chris Parsons8d6e4332021-02-22 16:13:50 -0500331 bazelCmd.Env = append(os.Environ(), "HOME="+context.homeDir, pwdPrefix(),
332 // Disables local host detection of gcc; toolchain information is defined
333 // explicitly in BUILD files.
334 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
Colin Crossff0278b2020-10-09 19:24:15 -0700335 stderr := &bytes.Buffer{}
336 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400337
338 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500339 return "", string(stderr.Bytes()),
340 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400341 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500342 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400343 }
344}
345
Chris Parsons8ccdb632020-11-17 15:41:01 -0500346// Returns the string contents of a workspace file that should be output
347// adjacent to the main bzl file and build file.
348// This workspace file allows, via local_repository rule, sourcetree-level
349// BUILD targets to be referenced via @sourceroot.
350func (context *bazelContext) workspaceFileContents() []byte {
351 formatString := `
352# This file is generated by soong_build. Do not edit.
353local_repository(
354 name = "sourceroot",
355 path = "%s",
356)
Liz Kammer8206d4f2021-03-03 16:40:52 -0500357
358local_repository(
359 name = "rules_cc",
360 path = "%s/build/bazel/rules_cc",
361)
Chris Parsons8ccdb632020-11-17 15:41:01 -0500362`
Liz Kammer8206d4f2021-03-03 16:40:52 -0500363 return []byte(fmt.Sprintf(formatString, context.workspaceDir, context.workspaceDir))
Chris Parsons8ccdb632020-11-17 15:41:01 -0500364}
365
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400366func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500367 // TODO(cparsons): Define configuration transitions programmatically based
368 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400369 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500370#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400371# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500372#####################################################
373
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400374def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500375 return {
Jingwen Chen91220d72021-03-24 02:18:33 -0400376 "//command_line_option:platforms": "@sourceroot//build/bazel/platforms:android_%s" % attr.arch,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500377 }
378
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400379_config_node_transition = transition(
380 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500381 inputs = [],
382 outputs = [
383 "//command_line_option:platforms",
384 ],
385)
386
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400387def _passthrough_rule_impl(ctx):
388 return [DefaultInfo(files = depset(ctx.files.deps))]
389
390config_node = rule(
391 implementation = _passthrough_rule_impl,
392 attrs = {
393 "arch" : attr.string(mandatory = True),
394 "deps" : attr.label_list(cfg = _config_node_transition),
395 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
396 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500397)
398
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400399
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500400# Rule representing the root of the build, to depend on all Bazel targets that
401# are required for the build. Building this target will build the entire Bazel
402# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400403mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400404 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500405 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400406 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500407 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400408)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500409
410def _phony_root_impl(ctx):
411 return []
412
413# Rule to depend on other targets but build nothing.
414# This is useful as follows: building a target of this rule will generate
415# symlink forests for all dependencies of the target, without executing any
416# actions of the build.
417phony_root = rule(
418 implementation = _phony_root_impl,
419 attrs = {"deps" : attr.label_list()},
420)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400421`
422 return []byte(contents)
423}
424
Chris Parsons8ccdb632020-11-17 15:41:01 -0500425// Returns a "canonicalized" corresponding to the given sourcetree-level label.
426// This abstraction is required because a sourcetree label such as //foo/bar:baz
427// must be referenced via the local repository prefix, such as
428// @sourceroot//foo/bar:baz.
429func canonicalizeLabel(label string) string {
430 if strings.HasPrefix(label, "//") {
431 return "@sourceroot" + label
432 } else {
433 return "@sourceroot//" + label
434 }
435}
436
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400437func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500438 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
439 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400440 formatString := `
441# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400442load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
443
444%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400445
446mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400447 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400448)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500449
450phony_root(name = "phonyroot",
451 deps = [":buildroot"],
452)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400453`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400454 configNodeFormatString := `
455config_node(name = "%s",
456 arch = "%s",
457 deps = [%s],
458)
459`
460
461 configNodesSection := ""
462
463 labelsByArch := map[string][]string{}
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400464 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500465 labelString := fmt.Sprintf("\"%s\"", canonicalizeLabel(val.label))
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400466 archString := getArchString(val)
467 labelsByArch[archString] = append(labelsByArch[archString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400468 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400469
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400470 configNodeLabels := []string{}
471 for archString, labels := range labelsByArch {
472 configNodeLabels = append(configNodeLabels, fmt.Sprintf("\":%s\"", archString))
473 labelsString := strings.Join(labels, ",\n ")
474 configNodesSection += fmt.Sprintf(configNodeFormatString, archString, archString, labelsString)
475 }
476
477 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(configNodeLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400478}
479
Chris Parsons944e7d02021-03-11 11:08:46 -0500480func indent(original string) string {
481 result := ""
482 for _, line := range strings.Split(original, "\n") {
483 result += " " + line + "\n"
484 }
485 return result
486}
487
Chris Parsons808d84c2021-03-09 20:43:32 -0500488// Returns the file contents of the buildroot.cquery file that should be used for the cquery
489// expression in order to obtain information about buildroot and its dependencies.
490// The contents of this file depend on the bazelContext's requests; requests are enumerated
491// and grouped by their request type. The data retrieved for each label depends on its
492// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400493func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400494 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons944e7d02021-03-11 11:08:46 -0500495 for val, _ := range context.requests {
496 cqueryId := getCqueryId(val)
497 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
498 requestTypeToCqueryIdEntries[val.requestType] =
499 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
500 }
501 labelRegistrationMapSection := ""
502 functionDefSection := ""
503 mainSwitchSection := ""
504
505 mapDeclarationFormatString := `
506%s = {
507 %s
508}
509`
510 functionDefFormatString := `
511def %s(target):
512%s
513`
514 mainSwitchSectionFormatString := `
515 if id_string in %s:
516 return id_string + ">>" + %s(target)
517`
518
Liz Kammer66ffdb72021-04-02 13:26:07 -0400519 for requestType, _ := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500520 labelMapName := requestType.Name() + "_Labels"
521 functionName := requestType.Name() + "_Fn"
522 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
523 labelMapName,
524 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
525 functionDefSection += fmt.Sprintf(functionDefFormatString,
526 functionName,
527 indent(requestType.StarlarkFunctionBody()))
528 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
529 labelMapName, functionName)
530 }
531
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400532 formatString := `
533# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400534
Chris Parsons944e7d02021-03-11 11:08:46 -0500535# Label Map Section
536%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500537
Chris Parsons944e7d02021-03-11 11:08:46 -0500538# Function Def Section
539%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500540
541def get_arch(target):
542 buildoptions = build_options(target)
543 platforms = build_options(target)["//command_line_option:platforms"]
544 if len(platforms) != 1:
545 # An individual configured target should have only one platform architecture.
546 # Note that it's fine for there to be multiple architectures for the same label,
547 # but each is its own configured target.
548 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
549 platform_name = build_options(target)["//command_line_option:platforms"][0].name
550 if platform_name == "host":
551 return "HOST"
Jingwen Chen91220d72021-03-24 02:18:33 -0400552 elif not platform_name.startswith("android_"):
553 fail("expected platform name of the form 'android_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500554 return "UNKNOWN"
Jingwen Chen91220d72021-03-24 02:18:33 -0400555 return platform_name[len("android_"):]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500556
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400557def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500558 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500559
560 # Main switch section
561 %s
562 # This target was not requested via cquery, and thus must be a dependency
563 # of a requested target.
564 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400565`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400566
Chris Parsons944e7d02021-03-11 11:08:46 -0500567 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
568 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400569}
570
Chris Parsons8ccdb632020-11-17 15:41:01 -0500571// Returns a workspace-relative path containing build-related metadata required
572// for interfacing with Bazel. Example: out/soong/bazel.
573func (context *bazelContext) intermediatesDir() string {
574 return filepath.Join(context.buildDir, "bazel")
575}
576
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400577// Issues commands to Bazel to receive results for all cquery requests
578// queued in the BazelContext.
579func (context *bazelContext) InvokeBazel() error {
580 context.results = make(map[cqueryKey]string)
581
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400582 var cqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500583 var cqueryErr string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400584 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500585
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500586 intermediatesDirPath := absolutePath(context.intermediatesDir())
587 if _, err := os.Stat(intermediatesDirPath); os.IsNotExist(err) {
588 err = os.Mkdir(intermediatesDirPath, 0777)
589 }
590
Chris Parsons8ccdb632020-11-17 15:41:01 -0500591 if err != nil {
592 return err
593 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400594 err = ioutil.WriteFile(
Chris Parsons8ccdb632020-11-17 15:41:01 -0500595 absolutePath(filepath.Join(context.intermediatesDir(), "main.bzl")),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400596 context.mainBzlFileContents(), 0666)
597 if err != nil {
598 return err
599 }
600 err = ioutil.WriteFile(
Chris Parsons8ccdb632020-11-17 15:41:01 -0500601 absolutePath(filepath.Join(context.intermediatesDir(), "BUILD.bazel")),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400602 context.mainBuildFileContents(), 0666)
603 if err != nil {
604 return err
605 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800606 cqueryFileRelpath := filepath.Join(context.intermediatesDir(), "buildroot.cquery")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400607 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800608 absolutePath(cqueryFileRelpath),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400609 context.cqueryStarlarkFileContents(), 0666)
610 if err != nil {
611 return err
612 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800613 workspaceFileRelpath := filepath.Join(context.intermediatesDir(), "WORKSPACE.bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500614 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800615 absolutePath(workspaceFileRelpath),
Chris Parsons8ccdb632020-11-17 15:41:01 -0500616 context.workspaceFileContents(), 0666)
617 if err != nil {
618 return err
619 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800620 buildrootLabel := "//:buildroot"
Chris Parsons808d84c2021-03-09 20:43:32 -0500621 cqueryOutput, cqueryErr, err = context.issueBazelCommand(bazel.CqueryBuildRootRunName, "cquery",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500622 []string{fmt.Sprintf("kind(rule, deps(%s))", buildrootLabel)},
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400623 "--output=starlark",
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800624 "--starlark:file="+cqueryFileRelpath)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500625 err = ioutil.WriteFile(
626 absolutePath(filepath.Join(context.intermediatesDir(), "cquery.out")),
627 []byte(cqueryOutput), 0666)
628 if err != nil {
629 return err
630 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400631
632 if err != nil {
633 return err
634 }
635
636 cqueryResults := map[string]string{}
637 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
638 if strings.Contains(outputLine, ">>") {
639 splitLine := strings.SplitN(outputLine, ">>", 2)
640 cqueryResults[splitLine[0]] = splitLine[1]
641 }
642 }
643
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400644 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500645 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400646 context.results[val] = string(cqueryResult)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400647 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500648 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
649 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400650 }
651 }
652
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500653 // Issue an aquery command to retrieve action information about the bazel build tree.
654 //
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400655 // TODO(cparsons): Use --target_pattern_file to avoid command line limits.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500656 var aqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500657 aqueryOutput, _, err = context.issueBazelCommand(bazel.AqueryBuildRootRunName, "aquery",
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800658 []string{fmt.Sprintf("deps(%s)", buildrootLabel),
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500659 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
660 // proto sources, which would add a number of unnecessary dependencies.
661 "--output=jsonproto"})
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400662
663 if err != nil {
664 return err
665 }
666
Chris Parsons4f069892021-01-15 12:22:41 -0500667 context.buildStatements, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
668 if err != nil {
669 return err
670 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500671
672 // Issue a build command of the phony root to generate symlink forests for dependencies of the
673 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
674 // but some of symlinks may be required to resolve source dependencies of the build.
Chris Parsons808d84c2021-03-09 20:43:32 -0500675 _, _, err = context.issueBazelCommand(bazel.BazelBuildPhonyRootRunName, "build",
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500676 []string{"//:phonyroot"})
677
678 if err != nil {
679 return err
680 }
681
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400682 // Clear requests.
683 context.requests = map[cqueryKey]bool{}
684 return nil
685}
Chris Parsonsa798d962020-10-12 23:44:08 -0400686
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500687func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
688 return context.buildStatements
689}
690
691func (context *bazelContext) OutputBase() string {
692 return context.outputBase
693}
694
Chris Parsonsa798d962020-10-12 23:44:08 -0400695// Singleton used for registering BUILD file ninja dependencies (needed
696// for correctness of builds which use Bazel.
697func BazelSingleton() Singleton {
698 return &bazelSingleton{}
699}
700
701type bazelSingleton struct{}
702
703func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500704 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
705 if !ctx.Config().BazelContext.BazelEnabled() {
706 return
707 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400708
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500709 // Add ninja file dependencies for files which all bazel invocations require.
710 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100711 filepath.Dir(bootstrap.CmdlineModuleListFile()), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500712 ctx.AddNinjaFileDeps(bazelBuildList)
713
714 data, err := ioutil.ReadFile(bazelBuildList)
715 if err != nil {
716 ctx.Errorf(err.Error())
717 }
718 files := strings.Split(strings.TrimSpace(string(data)), "\n")
719 for _, file := range files {
720 ctx.AddNinjaFileDeps(file)
721 }
722
723 // Register bazel-owned build statements (obtained from the aquery invocation).
724 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500725 if len(buildStatement.Command) < 1 {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000726 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500727 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500728 rule := NewRuleBuilder(pctx, ctx)
729 cmd := rule.Command()
730 cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ && %s",
731 ctx.Config().BazelContext.OutputBase(), buildStatement.Command))
732
733 for _, outputPath := range buildStatement.OutputPaths {
734 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400735 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500736 for _, inputPath := range buildStatement.InputPaths {
737 cmd.Implicit(PathForBazelOut(ctx, inputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400738 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500739
Liz Kammerde116852021-03-25 16:42:37 -0400740 if depfile := buildStatement.Depfile; depfile != nil {
741 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
742 }
743
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500744 // This is required to silence warnings pertaining to unexpected timestamps. Particularly,
745 // some Bazel builtins (such as files in the bazel_tools directory) have far-future
746 // timestamps. Without restat, Ninja would emit warnings that the input files of a
747 // build statement have later timestamps than the outputs.
748 rule.Restat()
749
Liz Kammer13548d72020-12-16 11:13:30 -0800750 rule.Build(fmt.Sprintf("bazel %d", index), buildStatement.Mnemonic)
Chris Parsonsa798d962020-10-12 23:44:08 -0400751 }
752}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500753
754func getCqueryId(key cqueryKey) string {
755 return canonicalizeLabel(key.label) + "|" + getArchString(key)
756}
757
758func getArchString(key cqueryKey) string {
759 arch := key.archType.Name
760 if len(arch) > 0 {
761 return arch
762 } else {
763 return "x86_64"
764 }
765}