blob: 7911632b644471ae6c3934bc616f5ea9e4cf1a1e [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 {
Liz Kammera92e8442021-04-07 20:25:21 -0400120 OutputBaseDir string
121
122 LabelToOutputFiles map[string][]string
123 LabelToOutputFilesAndCcObjectFiles map[string]cquery.GetOutputFilesAndCcObjectFiles_Result
124 LabelToCcStaticLibraryFiles map[string][]string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400125}
126
Chris Parsons944e7d02021-03-11 11:08:46 -0500127func (m MockBazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
Liz Kammera92e8442021-04-07 20:25:21 -0400128 result, ok := m.LabelToOutputFiles[label]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500129 return result, ok
130}
131
Chris Parsons944e7d02021-03-11 11:08:46 -0500132func (m MockBazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
Liz Kammera92e8442021-04-07 20:25:21 -0400133 result, ok := m.LabelToOutputFilesAndCcObjectFiles[label]
134 return result.OutputFiles, result.CcObjectFiles, ok
Chris Parsons808d84c2021-03-09 20:43:32 -0500135}
136
Liz Kammer3f9e1552021-04-02 18:47:09 -0400137func (m MockBazelContext) GetPrebuiltCcStaticLibraryFiles(label string, archType ArchType) ([]string, bool) {
Liz Kammera92e8442021-04-07 20:25:21 -0400138 result, ok := m.LabelToCcStaticLibraryFiles[label]
Liz Kammer3f9e1552021-04-02 18:47:09 -0400139 return result, ok
140}
141
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400142func (m MockBazelContext) InvokeBazel() error {
143 panic("unimplemented")
144}
145
146func (m MockBazelContext) BazelEnabled() bool {
147 return true
148}
149
Liz Kammera92e8442021-04-07 20:25:21 -0400150func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500151
152func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
153 return []bazel.BuildStatement{}
154}
155
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400156var _ BazelContext = MockBazelContext{}
157
Chris Parsons944e7d02021-03-11 11:08:46 -0500158func (bazelCtx *bazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
159 rawString, ok := bazelCtx.cquery(label, cquery.GetOutputFiles, archType)
160 var ret []string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400161 if ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500162 bazelOutput := strings.TrimSpace(rawString)
Liz Kammerf29df7c2021-04-02 13:37:39 -0400163 ret = cquery.GetOutputFiles.ParseResult(bazelOutput)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400164 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500165 return ret, ok
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400166}
167
Chris Parsons944e7d02021-03-11 11:08:46 -0500168func (bazelCtx *bazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
169 var outputFiles []string
Chris Parsons808d84c2021-03-09 20:43:32 -0500170 var ccObjects []string
171
Chris Parsons944e7d02021-03-11 11:08:46 -0500172 result, ok := bazelCtx.cquery(label, cquery.GetOutputFilesAndCcObjectFiles, archType)
Chris Parsons808d84c2021-03-09 20:43:32 -0500173 if ok {
174 bazelOutput := strings.TrimSpace(result)
Liz Kammerf29df7c2021-04-02 13:37:39 -0400175 returnResult := cquery.GetOutputFilesAndCcObjectFiles.ParseResult(bazelOutput)
Chris Parsons944e7d02021-03-11 11:08:46 -0500176 outputFiles = returnResult.OutputFiles
177 ccObjects = returnResult.CcObjectFiles
Chris Parsons808d84c2021-03-09 20:43:32 -0500178 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500179
180 return outputFiles, ccObjects, ok
Chris Parsons808d84c2021-03-09 20:43:32 -0500181}
182
Liz Kammer3f9e1552021-04-02 18:47:09 -0400183// GetPrebuiltCcStaticLibraryFiles returns a slice of prebuilt static libraries for the given
184// label/archType if there are query results; otherwise, it enqueues the query and returns false.
185func (bazelCtx *bazelContext) GetPrebuiltCcStaticLibraryFiles(label string, archType ArchType) ([]string, bool) {
186 result, ok := bazelCtx.cquery(label, cquery.GetPrebuiltCcStaticLibraryFiles, archType)
187 if !ok {
188 return nil, false
189 }
190
191 bazelOutput := strings.TrimSpace(result)
192 ret := cquery.GetPrebuiltCcStaticLibraryFiles.ParseResult(bazelOutput)
193 return ret, ok
194}
195
Chris Parsons944e7d02021-03-11 11:08:46 -0500196func (n noopBazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500197 panic("unimplemented")
198}
199
Chris Parsons944e7d02021-03-11 11:08:46 -0500200func (n noopBazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500201 panic("unimplemented")
202}
203
Liz Kammer3f9e1552021-04-02 18:47:09 -0400204func (n noopBazelContext) GetPrebuiltCcStaticLibraryFiles(label string, archType ArchType) ([]string, bool) {
205 panic("unimplemented")
206}
207
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400208func (n noopBazelContext) InvokeBazel() error {
209 panic("unimplemented")
210}
211
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500212func (m noopBazelContext) OutputBase() string {
213 return ""
214}
215
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400216func (n noopBazelContext) BazelEnabled() bool {
217 return false
218}
219
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500220func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
221 return []bazel.BuildStatement{}
222}
223
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400224func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons8b77a002020-10-27 18:59:25 -0400225 // TODO(cparsons): Assess USE_BAZEL=1 instead once "mixed Soong/Bazel builds"
226 // are production ready.
227 if c.Getenv("USE_BAZEL_ANALYSIS") != "1" {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400228 return noopBazelContext{}, nil
229 }
230
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400231 bazelCtx := bazelContext{buildDir: c.buildDir, requests: make(map[cqueryKey]bool)}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400232 missingEnvVars := []string{}
233 if len(c.Getenv("BAZEL_HOME")) > 1 {
234 bazelCtx.homeDir = c.Getenv("BAZEL_HOME")
235 } else {
236 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
237 }
238 if len(c.Getenv("BAZEL_PATH")) > 1 {
239 bazelCtx.bazelPath = c.Getenv("BAZEL_PATH")
240 } else {
241 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
242 }
243 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
244 bazelCtx.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
245 } else {
246 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
247 }
248 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
249 bazelCtx.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
250 } else {
251 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
252 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000253 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
254 bazelCtx.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
255 } else {
256 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
257 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400258 if len(missingEnvVars) > 0 {
259 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
260 } else {
261 return &bazelCtx, nil
262 }
263}
264
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000265func (context *bazelContext) BazelMetricsDir() string {
266 return context.metricsDir
267}
268
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400269func (context *bazelContext) BazelEnabled() bool {
270 return true
271}
272
273// Adds a cquery request to the Bazel request queue, to be later invoked, or
274// returns the result of the given request if the request was already made.
275// If the given request was already made (and the results are available), then
276// returns (result, true). If the request is queued but no results are available,
277// then returns ("", false).
Liz Kammerf29df7c2021-04-02 13:37:39 -0400278func (context *bazelContext) cquery(label string, requestType cqueryRequest,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500279 archType ArchType) (string, bool) {
280 key := cqueryKey{label, requestType, archType}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400281 if result, ok := context.results[key]; ok {
282 return result, true
283 } else {
284 context.requestMutex.Lock()
285 defer context.requestMutex.Unlock()
286 context.requests[key] = true
287 return "", false
288 }
289}
290
291func pwdPrefix() string {
292 // Darwin doesn't have /proc
293 if runtime.GOOS != "darwin" {
294 return "PWD=/proc/self/cwd"
295 }
296 return ""
297}
298
Chris Parsons808d84c2021-03-09 20:43:32 -0500299// Issues the given bazel command with given build label and additional flags.
300// Returns (stdout, stderr, error). The first and second return values are strings
301// containing the stdout and stderr of the run command, and an error is returned if
302// the invocation returned an error code.
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000303func (context *bazelContext) issueBazelCommand(runName bazel.RunName, command string, labels []string,
Chris Parsons808d84c2021-03-09 20:43:32 -0500304 extraFlags ...string) (string, string, error) {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400305
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500306 cmdFlags := []string{"--output_base=" + context.outputBase, command}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400307 cmdFlags = append(cmdFlags, labels...)
Chris Parsons8ccdb632020-11-17 15:41:01 -0500308 cmdFlags = append(cmdFlags, "--package_path=%workspace%/"+context.intermediatesDir())
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000309 cmdFlags = append(cmdFlags, "--profile="+shared.BazelMetricsFilename(context, runName))
Jingwen Chen91220d72021-03-24 02:18:33 -0400310
311 // Set default platforms to canonicalized values for mixed builds requests.
312 // If these are set in the bazelrc, they will have values that are
313 // non-canonicalized to @sourceroot labels, and thus be invalid when
314 // referenced from the buildroot.
315 //
316 // The actual platform values here may be overridden by configuration
317 // transitions from the buildroot.
Chris Parsonsee423b02021-02-08 23:04:59 -0500318 cmdFlags = append(cmdFlags,
Jingwen Chen91220d72021-03-24 02:18:33 -0400319 fmt.Sprintf("--platforms=%s", canonicalizeLabel("//build/bazel/platforms:android_x86_64")))
Chris Parsonsee423b02021-02-08 23:04:59 -0500320 cmdFlags = append(cmdFlags,
321 fmt.Sprintf("--extra_toolchains=%s", canonicalizeLabel("//prebuilts/clang/host/linux-x86:all")))
Jingwen Chen91220d72021-03-24 02:18:33 -0400322 // This should be parameterized on the host OS, but let's restrict to linux
323 // to keep things simple for now.
324 cmdFlags = append(cmdFlags,
325 fmt.Sprintf("--host_platform=%s", canonicalizeLabel("//build/bazel/platforms:linux_x86_64")))
326
Chris Parsons8d6e4332021-02-22 16:13:50 -0500327 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
328 cmdFlags = append(cmdFlags, "--experimental_repository_disable_download")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400329 cmdFlags = append(cmdFlags, extraFlags...)
330
331 bazelCmd := exec.Command(context.bazelPath, cmdFlags...)
332 bazelCmd.Dir = context.workspaceDir
Chris Parsons8d6e4332021-02-22 16:13:50 -0500333 bazelCmd.Env = append(os.Environ(), "HOME="+context.homeDir, pwdPrefix(),
334 // Disables local host detection of gcc; toolchain information is defined
335 // explicitly in BUILD files.
336 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
Colin Crossff0278b2020-10-09 19:24:15 -0700337 stderr := &bytes.Buffer{}
338 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400339
340 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500341 return "", string(stderr.Bytes()),
342 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400343 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500344 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400345 }
346}
347
Chris Parsons8ccdb632020-11-17 15:41:01 -0500348// Returns the string contents of a workspace file that should be output
349// adjacent to the main bzl file and build file.
350// This workspace file allows, via local_repository rule, sourcetree-level
351// BUILD targets to be referenced via @sourceroot.
352func (context *bazelContext) workspaceFileContents() []byte {
353 formatString := `
354# This file is generated by soong_build. Do not edit.
355local_repository(
356 name = "sourceroot",
357 path = "%s",
358)
Liz Kammer8206d4f2021-03-03 16:40:52 -0500359
360local_repository(
361 name = "rules_cc",
362 path = "%s/build/bazel/rules_cc",
363)
Chris Parsons8ccdb632020-11-17 15:41:01 -0500364`
Liz Kammer8206d4f2021-03-03 16:40:52 -0500365 return []byte(fmt.Sprintf(formatString, context.workspaceDir, context.workspaceDir))
Chris Parsons8ccdb632020-11-17 15:41:01 -0500366}
367
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400368func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500369 // TODO(cparsons): Define configuration transitions programmatically based
370 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400371 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500372#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400373# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500374#####################################################
375
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400376def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500377 return {
Jingwen Chen91220d72021-03-24 02:18:33 -0400378 "//command_line_option:platforms": "@sourceroot//build/bazel/platforms:android_%s" % attr.arch,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500379 }
380
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400381_config_node_transition = transition(
382 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500383 inputs = [],
384 outputs = [
385 "//command_line_option:platforms",
386 ],
387)
388
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400389def _passthrough_rule_impl(ctx):
390 return [DefaultInfo(files = depset(ctx.files.deps))]
391
392config_node = rule(
393 implementation = _passthrough_rule_impl,
394 attrs = {
395 "arch" : attr.string(mandatory = True),
396 "deps" : attr.label_list(cfg = _config_node_transition),
397 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
398 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500399)
400
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400401
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500402# Rule representing the root of the build, to depend on all Bazel targets that
403# are required for the build. Building this target will build the entire Bazel
404# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400405mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400406 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500407 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400408 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500409 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400410)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500411
412def _phony_root_impl(ctx):
413 return []
414
415# Rule to depend on other targets but build nothing.
416# This is useful as follows: building a target of this rule will generate
417# symlink forests for all dependencies of the target, without executing any
418# actions of the build.
419phony_root = rule(
420 implementation = _phony_root_impl,
421 attrs = {"deps" : attr.label_list()},
422)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400423`
424 return []byte(contents)
425}
426
Chris Parsons8ccdb632020-11-17 15:41:01 -0500427// Returns a "canonicalized" corresponding to the given sourcetree-level label.
428// This abstraction is required because a sourcetree label such as //foo/bar:baz
429// must be referenced via the local repository prefix, such as
430// @sourceroot//foo/bar:baz.
431func canonicalizeLabel(label string) string {
432 if strings.HasPrefix(label, "//") {
433 return "@sourceroot" + label
434 } else {
435 return "@sourceroot//" + label
436 }
437}
438
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400439func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500440 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
441 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400442 formatString := `
443# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400444load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
445
446%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400447
448mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400449 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400450)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500451
452phony_root(name = "phonyroot",
453 deps = [":buildroot"],
454)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400455`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400456 configNodeFormatString := `
457config_node(name = "%s",
458 arch = "%s",
459 deps = [%s],
460)
461`
462
463 configNodesSection := ""
464
465 labelsByArch := map[string][]string{}
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400466 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500467 labelString := fmt.Sprintf("\"%s\"", canonicalizeLabel(val.label))
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400468 archString := getArchString(val)
469 labelsByArch[archString] = append(labelsByArch[archString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400470 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400471
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400472 configNodeLabels := []string{}
473 for archString, labels := range labelsByArch {
474 configNodeLabels = append(configNodeLabels, fmt.Sprintf("\":%s\"", archString))
475 labelsString := strings.Join(labels, ",\n ")
476 configNodesSection += fmt.Sprintf(configNodeFormatString, archString, archString, labelsString)
477 }
478
479 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(configNodeLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400480}
481
Chris Parsons944e7d02021-03-11 11:08:46 -0500482func indent(original string) string {
483 result := ""
484 for _, line := range strings.Split(original, "\n") {
485 result += " " + line + "\n"
486 }
487 return result
488}
489
Chris Parsons808d84c2021-03-09 20:43:32 -0500490// Returns the file contents of the buildroot.cquery file that should be used for the cquery
491// expression in order to obtain information about buildroot and its dependencies.
492// The contents of this file depend on the bazelContext's requests; requests are enumerated
493// and grouped by their request type. The data retrieved for each label depends on its
494// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400495func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400496 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons944e7d02021-03-11 11:08:46 -0500497 for val, _ := range context.requests {
498 cqueryId := getCqueryId(val)
499 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
500 requestTypeToCqueryIdEntries[val.requestType] =
501 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
502 }
503 labelRegistrationMapSection := ""
504 functionDefSection := ""
505 mainSwitchSection := ""
506
507 mapDeclarationFormatString := `
508%s = {
509 %s
510}
511`
512 functionDefFormatString := `
513def %s(target):
514%s
515`
516 mainSwitchSectionFormatString := `
517 if id_string in %s:
518 return id_string + ">>" + %s(target)
519`
520
Liz Kammer66ffdb72021-04-02 13:26:07 -0400521 for requestType, _ := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500522 labelMapName := requestType.Name() + "_Labels"
523 functionName := requestType.Name() + "_Fn"
524 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
525 labelMapName,
526 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
527 functionDefSection += fmt.Sprintf(functionDefFormatString,
528 functionName,
529 indent(requestType.StarlarkFunctionBody()))
530 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
531 labelMapName, functionName)
532 }
533
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400534 formatString := `
535# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400536
Chris Parsons944e7d02021-03-11 11:08:46 -0500537# Label Map Section
538%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500539
Chris Parsons944e7d02021-03-11 11:08:46 -0500540# Function Def Section
541%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500542
543def get_arch(target):
544 buildoptions = build_options(target)
545 platforms = build_options(target)["//command_line_option:platforms"]
546 if len(platforms) != 1:
547 # An individual configured target should have only one platform architecture.
548 # Note that it's fine for there to be multiple architectures for the same label,
549 # but each is its own configured target.
550 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
551 platform_name = build_options(target)["//command_line_option:platforms"][0].name
552 if platform_name == "host":
553 return "HOST"
Jingwen Chen91220d72021-03-24 02:18:33 -0400554 elif not platform_name.startswith("android_"):
555 fail("expected platform name of the form 'android_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500556 return "UNKNOWN"
Jingwen Chen91220d72021-03-24 02:18:33 -0400557 return platform_name[len("android_"):]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500558
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400559def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500560 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500561
562 # Main switch section
563 %s
564 # This target was not requested via cquery, and thus must be a dependency
565 # of a requested target.
566 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400567`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400568
Chris Parsons944e7d02021-03-11 11:08:46 -0500569 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
570 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400571}
572
Chris Parsons8ccdb632020-11-17 15:41:01 -0500573// Returns a workspace-relative path containing build-related metadata required
574// for interfacing with Bazel. Example: out/soong/bazel.
575func (context *bazelContext) intermediatesDir() string {
576 return filepath.Join(context.buildDir, "bazel")
577}
578
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400579// Issues commands to Bazel to receive results for all cquery requests
580// queued in the BazelContext.
581func (context *bazelContext) InvokeBazel() error {
582 context.results = make(map[cqueryKey]string)
583
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400584 var cqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500585 var cqueryErr string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400586 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500587
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500588 intermediatesDirPath := absolutePath(context.intermediatesDir())
589 if _, err := os.Stat(intermediatesDirPath); os.IsNotExist(err) {
590 err = os.Mkdir(intermediatesDirPath, 0777)
591 }
592
Chris Parsons8ccdb632020-11-17 15:41:01 -0500593 if err != nil {
594 return err
595 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400596 err = ioutil.WriteFile(
Chris Parsons8ccdb632020-11-17 15:41:01 -0500597 absolutePath(filepath.Join(context.intermediatesDir(), "main.bzl")),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400598 context.mainBzlFileContents(), 0666)
599 if err != nil {
600 return err
601 }
602 err = ioutil.WriteFile(
Chris Parsons8ccdb632020-11-17 15:41:01 -0500603 absolutePath(filepath.Join(context.intermediatesDir(), "BUILD.bazel")),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400604 context.mainBuildFileContents(), 0666)
605 if err != nil {
606 return err
607 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800608 cqueryFileRelpath := filepath.Join(context.intermediatesDir(), "buildroot.cquery")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400609 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800610 absolutePath(cqueryFileRelpath),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400611 context.cqueryStarlarkFileContents(), 0666)
612 if err != nil {
613 return err
614 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800615 workspaceFileRelpath := filepath.Join(context.intermediatesDir(), "WORKSPACE.bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500616 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800617 absolutePath(workspaceFileRelpath),
Chris Parsons8ccdb632020-11-17 15:41:01 -0500618 context.workspaceFileContents(), 0666)
619 if err != nil {
620 return err
621 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800622 buildrootLabel := "//:buildroot"
Chris Parsons808d84c2021-03-09 20:43:32 -0500623 cqueryOutput, cqueryErr, err = context.issueBazelCommand(bazel.CqueryBuildRootRunName, "cquery",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500624 []string{fmt.Sprintf("kind(rule, deps(%s))", buildrootLabel)},
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400625 "--output=starlark",
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800626 "--starlark:file="+cqueryFileRelpath)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500627 err = ioutil.WriteFile(
628 absolutePath(filepath.Join(context.intermediatesDir(), "cquery.out")),
629 []byte(cqueryOutput), 0666)
630 if err != nil {
631 return err
632 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400633
634 if err != nil {
635 return err
636 }
637
638 cqueryResults := map[string]string{}
639 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
640 if strings.Contains(outputLine, ">>") {
641 splitLine := strings.SplitN(outputLine, ">>", 2)
642 cqueryResults[splitLine[0]] = splitLine[1]
643 }
644 }
645
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400646 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500647 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400648 context.results[val] = string(cqueryResult)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400649 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500650 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
651 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400652 }
653 }
654
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500655 // Issue an aquery command to retrieve action information about the bazel build tree.
656 //
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400657 // TODO(cparsons): Use --target_pattern_file to avoid command line limits.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500658 var aqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500659 aqueryOutput, _, err = context.issueBazelCommand(bazel.AqueryBuildRootRunName, "aquery",
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800660 []string{fmt.Sprintf("deps(%s)", buildrootLabel),
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500661 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
662 // proto sources, which would add a number of unnecessary dependencies.
663 "--output=jsonproto"})
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400664
665 if err != nil {
666 return err
667 }
668
Chris Parsons4f069892021-01-15 12:22:41 -0500669 context.buildStatements, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
670 if err != nil {
671 return err
672 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500673
674 // Issue a build command of the phony root to generate symlink forests for dependencies of the
675 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
676 // but some of symlinks may be required to resolve source dependencies of the build.
Chris Parsons808d84c2021-03-09 20:43:32 -0500677 _, _, err = context.issueBazelCommand(bazel.BazelBuildPhonyRootRunName, "build",
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500678 []string{"//:phonyroot"})
679
680 if err != nil {
681 return err
682 }
683
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400684 // Clear requests.
685 context.requests = map[cqueryKey]bool{}
686 return nil
687}
Chris Parsonsa798d962020-10-12 23:44:08 -0400688
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500689func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
690 return context.buildStatements
691}
692
693func (context *bazelContext) OutputBase() string {
694 return context.outputBase
695}
696
Chris Parsonsa798d962020-10-12 23:44:08 -0400697// Singleton used for registering BUILD file ninja dependencies (needed
698// for correctness of builds which use Bazel.
699func BazelSingleton() Singleton {
700 return &bazelSingleton{}
701}
702
703type bazelSingleton struct{}
704
705func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500706 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
707 if !ctx.Config().BazelContext.BazelEnabled() {
708 return
709 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400710
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500711 // Add ninja file dependencies for files which all bazel invocations require.
712 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100713 filepath.Dir(bootstrap.CmdlineModuleListFile()), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500714 ctx.AddNinjaFileDeps(bazelBuildList)
715
716 data, err := ioutil.ReadFile(bazelBuildList)
717 if err != nil {
718 ctx.Errorf(err.Error())
719 }
720 files := strings.Split(strings.TrimSpace(string(data)), "\n")
721 for _, file := range files {
722 ctx.AddNinjaFileDeps(file)
723 }
724
725 // Register bazel-owned build statements (obtained from the aquery invocation).
726 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500727 if len(buildStatement.Command) < 1 {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000728 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500729 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500730 rule := NewRuleBuilder(pctx, ctx)
731 cmd := rule.Command()
732 cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ && %s",
733 ctx.Config().BazelContext.OutputBase(), buildStatement.Command))
734
735 for _, outputPath := range buildStatement.OutputPaths {
736 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400737 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500738 for _, inputPath := range buildStatement.InputPaths {
739 cmd.Implicit(PathForBazelOut(ctx, inputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400740 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500741
Liz Kammerde116852021-03-25 16:42:37 -0400742 if depfile := buildStatement.Depfile; depfile != nil {
743 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
744 }
745
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500746 // This is required to silence warnings pertaining to unexpected timestamps. Particularly,
747 // some Bazel builtins (such as files in the bazel_tools directory) have far-future
748 // timestamps. Without restat, Ninja would emit warnings that the input files of a
749 // build statement have later timestamps than the outputs.
750 rule.Restat()
751
Liz Kammer13548d72020-12-16 11:13:30 -0800752 rule.Build(fmt.Sprintf("bazel %d", index), buildStatement.Mnemonic)
Chris Parsonsa798d962020-10-12 23:44:08 -0400753 }
754}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500755
756func getCqueryId(key cqueryKey) string {
757 return canonicalizeLabel(key.label) + "|" + getArchString(key)
758}
759
760func getArchString(key cqueryKey) string {
761 arch := key.archType.Name
762 if len(arch) > 0 {
763 return arch
764 } else {
765 return "x86_64"
766 }
767}