blob: 8d561d2775ddb9cfb66b4b71cc01cd242b8ae131 [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).
Liz Kammerfe23bf32021-04-09 16:17:05 -040070 GetCcInfo(label string, archType ArchType) (cquery.CcInfo, bool, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -040071
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040072 // ** End cquery methods
73
74 // Issues commands to Bazel to receive results for all cquery requests
75 // queued in the BazelContext.
76 InvokeBazel() error
77
78 // Returns true if bazel is enabled for the given configuration.
79 BazelEnabled() bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050080
81 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
82 OutputBase() string
83
84 // Returns build statements which should get registered to reflect Bazel's outputs.
85 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040086}
87
Liz Kammer8d62a4f2021-04-08 09:47:28 -040088type bazelRunner interface {
89 issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) (string, string, error)
90}
91
92type bazelPaths struct {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040093 homeDir string
94 bazelPath string
95 outputBase string
96 workspaceDir string
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040097 buildDir string
Patrice Arruda05ab2d02020-12-12 06:24:26 +000098 metricsDir string
Liz Kammer8d62a4f2021-04-08 09:47:28 -040099}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400100
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400101// A context object which tracks queued requests that need to be made to Bazel,
102// and their results after the requests have been made.
103type bazelContext struct {
104 bazelRunner
105 paths *bazelPaths
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400106 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
107 requestMutex sync.Mutex // requests can be written in parallel
108
109 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500110
111 // Build statements which should get registered to reflect Bazel's outputs.
112 buildStatements []bazel.BuildStatement
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400113}
114
115var _ BazelContext = &bazelContext{}
116
117// A bazel context to use when Bazel is disabled.
118type noopBazelContext struct{}
119
120var _ BazelContext = noopBazelContext{}
121
122// A bazel context to use for tests.
123type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400124 OutputBaseDir string
125
Liz Kammerb71794d2021-04-09 14:07:00 -0400126 LabelToOutputFiles map[string][]string
127 LabelToCcInfo map[string]cquery.CcInfo
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400128}
129
Chris Parsons944e7d02021-03-11 11:08:46 -0500130func (m MockBazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
Liz Kammera92e8442021-04-07 20:25:21 -0400131 result, ok := m.LabelToOutputFiles[label]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500132 return result, ok
133}
134
Liz Kammerfe23bf32021-04-09 16:17:05 -0400135func (m MockBazelContext) GetCcInfo(label string, archType ArchType) (cquery.CcInfo, bool, error) {
Liz Kammerb71794d2021-04-09 14:07:00 -0400136 result, ok := m.LabelToCcInfo[label]
Liz Kammerfe23bf32021-04-09 16:17:05 -0400137 return result, ok, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400138}
139
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400140func (m MockBazelContext) InvokeBazel() error {
141 panic("unimplemented")
142}
143
144func (m MockBazelContext) BazelEnabled() bool {
145 return true
146}
147
Liz Kammera92e8442021-04-07 20:25:21 -0400148func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500149
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
Liz Kammerfe23bf32021-04-09 16:17:05 -0400166func (bazelCtx *bazelContext) GetCcInfo(label string, archType ArchType) (cquery.CcInfo, bool, error) {
Liz Kammerb71794d2021-04-09 14:07:00 -0400167 result, ok := bazelCtx.cquery(label, cquery.GetCcInfo, archType)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400168 if !ok {
Liz Kammerfe23bf32021-04-09 16:17:05 -0400169 return cquery.CcInfo{}, ok, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400170 }
171
172 bazelOutput := strings.TrimSpace(result)
Liz Kammerfe23bf32021-04-09 16:17:05 -0400173 ret, err := cquery.GetCcInfo.ParseResult(bazelOutput)
174 return ret, ok, err
Liz Kammer3f9e1552021-04-02 18:47:09 -0400175}
176
Chris Parsons944e7d02021-03-11 11:08:46 -0500177func (n noopBazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500178 panic("unimplemented")
179}
180
Liz Kammerfe23bf32021-04-09 16:17:05 -0400181func (n noopBazelContext) GetCcInfo(label string, archType ArchType) (cquery.CcInfo, bool, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500182 panic("unimplemented")
183}
184
Liz Kammer3f9e1552021-04-02 18:47:09 -0400185func (n noopBazelContext) GetPrebuiltCcStaticLibraryFiles(label string, archType ArchType) ([]string, bool) {
186 panic("unimplemented")
187}
188
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400189func (n noopBazelContext) InvokeBazel() error {
190 panic("unimplemented")
191}
192
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500193func (m noopBazelContext) OutputBase() string {
194 return ""
195}
196
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400197func (n noopBazelContext) BazelEnabled() bool {
198 return false
199}
200
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500201func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
202 return []bazel.BuildStatement{}
203}
204
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400205func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons8b77a002020-10-27 18:59:25 -0400206 // TODO(cparsons): Assess USE_BAZEL=1 instead once "mixed Soong/Bazel builds"
207 // are production ready.
208 if c.Getenv("USE_BAZEL_ANALYSIS") != "1" {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400209 return noopBazelContext{}, nil
210 }
211
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400212 p, err := bazelPathsFromConfig(c)
213 if err != nil {
214 return nil, err
215 }
216 return &bazelContext{
217 bazelRunner: &builtinBazelRunner{},
218 paths: p,
219 requests: make(map[cqueryKey]bool),
220 }, nil
221}
222
223func bazelPathsFromConfig(c *config) (*bazelPaths, error) {
224 p := bazelPaths{
225 buildDir: c.buildDir,
226 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400227 missingEnvVars := []string{}
228 if len(c.Getenv("BAZEL_HOME")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400229 p.homeDir = c.Getenv("BAZEL_HOME")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400230 } else {
231 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
232 }
233 if len(c.Getenv("BAZEL_PATH")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400234 p.bazelPath = c.Getenv("BAZEL_PATH")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400235 } else {
236 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
237 }
238 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400239 p.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400240 } else {
241 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
242 }
243 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400244 p.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400245 } else {
246 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
247 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000248 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400249 p.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000250 } else {
251 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
252 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400253 if len(missingEnvVars) > 0 {
254 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
255 } else {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400256 return &p, nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400257 }
258}
259
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400260func (p *bazelPaths) BazelMetricsDir() string {
261 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000262}
263
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400264func (context *bazelContext) BazelEnabled() bool {
265 return true
266}
267
268// Adds a cquery request to the Bazel request queue, to be later invoked, or
269// returns the result of the given request if the request was already made.
270// If the given request was already made (and the results are available), then
271// returns (result, true). If the request is queued but no results are available,
272// then returns ("", false).
Liz Kammerf29df7c2021-04-02 13:37:39 -0400273func (context *bazelContext) cquery(label string, requestType cqueryRequest,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500274 archType ArchType) (string, bool) {
275 key := cqueryKey{label, requestType, archType}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400276 if result, ok := context.results[key]; ok {
277 return result, true
278 } else {
279 context.requestMutex.Lock()
280 defer context.requestMutex.Unlock()
281 context.requests[key] = true
282 return "", false
283 }
284}
285
286func pwdPrefix() string {
287 // Darwin doesn't have /proc
288 if runtime.GOOS != "darwin" {
289 return "PWD=/proc/self/cwd"
290 }
291 return ""
292}
293
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400294type bazelCommand struct {
295 command string
296 // query or label
297 expression string
298}
299
300type mockBazelRunner struct {
301 bazelCommandResults map[bazelCommand]string
302 commands []bazelCommand
303}
304
305func (r *mockBazelRunner) issueBazelCommand(paths *bazelPaths,
306 runName bazel.RunName,
307 command bazelCommand,
308 extraFlags ...string) (string, string, error) {
309 r.commands = append(r.commands, command)
310 if ret, ok := r.bazelCommandResults[command]; ok {
311 return ret, "", nil
312 }
313 return "", "", nil
314}
315
316type builtinBazelRunner struct{}
317
Chris Parsons808d84c2021-03-09 20:43:32 -0500318// Issues the given bazel command with given build label and additional flags.
319// Returns (stdout, stderr, error). The first and second return values are strings
320// containing the stdout and stderr of the run command, and an error is returned if
321// the invocation returned an error code.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400322func (r *builtinBazelRunner) issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Chris Parsons808d84c2021-03-09 20:43:32 -0500323 extraFlags ...string) (string, string, error) {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400324 cmdFlags := []string{"--output_base=" + paths.outputBase, command.command}
325 cmdFlags = append(cmdFlags, command.expression)
326 cmdFlags = append(cmdFlags, "--package_path=%workspace%/"+paths.intermediatesDir())
327 cmdFlags = append(cmdFlags, "--profile="+shared.BazelMetricsFilename(paths, runName))
Jingwen Chen91220d72021-03-24 02:18:33 -0400328
329 // Set default platforms to canonicalized values for mixed builds requests.
330 // If these are set in the bazelrc, they will have values that are
331 // non-canonicalized to @sourceroot labels, and thus be invalid when
332 // referenced from the buildroot.
333 //
334 // The actual platform values here may be overridden by configuration
335 // transitions from the buildroot.
Chris Parsonsee423b02021-02-08 23:04:59 -0500336 cmdFlags = append(cmdFlags,
Jingwen Chen91220d72021-03-24 02:18:33 -0400337 fmt.Sprintf("--platforms=%s", canonicalizeLabel("//build/bazel/platforms:android_x86_64")))
Chris Parsonsee423b02021-02-08 23:04:59 -0500338 cmdFlags = append(cmdFlags,
339 fmt.Sprintf("--extra_toolchains=%s", canonicalizeLabel("//prebuilts/clang/host/linux-x86:all")))
Jingwen Chen91220d72021-03-24 02:18:33 -0400340 // This should be parameterized on the host OS, but let's restrict to linux
341 // to keep things simple for now.
342 cmdFlags = append(cmdFlags,
343 fmt.Sprintf("--host_platform=%s", canonicalizeLabel("//build/bazel/platforms:linux_x86_64")))
344
Chris Parsons8d6e4332021-02-22 16:13:50 -0500345 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
346 cmdFlags = append(cmdFlags, "--experimental_repository_disable_download")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400347 cmdFlags = append(cmdFlags, extraFlags...)
348
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400349 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
350 bazelCmd.Dir = paths.workspaceDir
351 bazelCmd.Env = append(os.Environ(), "HOME="+paths.homeDir, pwdPrefix(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500352 // Disables local host detection of gcc; toolchain information is defined
353 // explicitly in BUILD files.
354 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
Colin Crossff0278b2020-10-09 19:24:15 -0700355 stderr := &bytes.Buffer{}
356 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400357
358 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500359 return "", string(stderr.Bytes()),
360 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400361 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500362 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400363 }
364}
365
Chris Parsons8ccdb632020-11-17 15:41:01 -0500366// Returns the string contents of a workspace file that should be output
367// adjacent to the main bzl file and build file.
368// This workspace file allows, via local_repository rule, sourcetree-level
369// BUILD targets to be referenced via @sourceroot.
370func (context *bazelContext) workspaceFileContents() []byte {
371 formatString := `
372# This file is generated by soong_build. Do not edit.
373local_repository(
374 name = "sourceroot",
Jingwen Chen63930982021-03-24 10:04:33 -0400375 path = "%[1]s",
Chris Parsons8ccdb632020-11-17 15:41:01 -0500376)
Liz Kammer8206d4f2021-03-03 16:40:52 -0500377
378local_repository(
379 name = "rules_cc",
Jingwen Chen63930982021-03-24 10:04:33 -0400380 path = "%[1]s/build/bazel/rules_cc",
381)
382
383local_repository(
384 name = "bazel_skylib",
385 path = "%[1]s/build/bazel/bazel_skylib",
Liz Kammer8206d4f2021-03-03 16:40:52 -0500386)
Chris Parsons8ccdb632020-11-17 15:41:01 -0500387`
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400388 return []byte(fmt.Sprintf(formatString, context.paths.workspaceDir))
Chris Parsons8ccdb632020-11-17 15:41:01 -0500389}
390
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400391func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500392 // TODO(cparsons): Define configuration transitions programmatically based
393 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400394 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500395#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400396# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500397#####################################################
398
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400399def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500400 return {
Jingwen Chen91220d72021-03-24 02:18:33 -0400401 "//command_line_option:platforms": "@sourceroot//build/bazel/platforms:android_%s" % attr.arch,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500402 }
403
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400404_config_node_transition = transition(
405 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500406 inputs = [],
407 outputs = [
408 "//command_line_option:platforms",
409 ],
410)
411
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400412def _passthrough_rule_impl(ctx):
413 return [DefaultInfo(files = depset(ctx.files.deps))]
414
415config_node = rule(
416 implementation = _passthrough_rule_impl,
417 attrs = {
418 "arch" : attr.string(mandatory = True),
419 "deps" : attr.label_list(cfg = _config_node_transition),
420 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
421 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500422)
423
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400424
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500425# Rule representing the root of the build, to depend on all Bazel targets that
426# are required for the build. Building this target will build the entire Bazel
427# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400428mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400429 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500430 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400431 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500432 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400433)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500434
435def _phony_root_impl(ctx):
436 return []
437
438# Rule to depend on other targets but build nothing.
439# This is useful as follows: building a target of this rule will generate
440# symlink forests for all dependencies of the target, without executing any
441# actions of the build.
442phony_root = rule(
443 implementation = _phony_root_impl,
444 attrs = {"deps" : attr.label_list()},
445)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400446`
447 return []byte(contents)
448}
449
Chris Parsons8ccdb632020-11-17 15:41:01 -0500450// Returns a "canonicalized" corresponding to the given sourcetree-level label.
451// This abstraction is required because a sourcetree label such as //foo/bar:baz
452// must be referenced via the local repository prefix, such as
453// @sourceroot//foo/bar:baz.
454func canonicalizeLabel(label string) string {
455 if strings.HasPrefix(label, "//") {
456 return "@sourceroot" + label
457 } else {
458 return "@sourceroot//" + label
459 }
460}
461
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400462func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500463 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
464 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400465 formatString := `
466# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400467load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
468
469%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400470
471mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400472 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400473)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500474
475phony_root(name = "phonyroot",
476 deps = [":buildroot"],
477)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400478`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400479 configNodeFormatString := `
480config_node(name = "%s",
481 arch = "%s",
482 deps = [%s],
483)
484`
485
486 configNodesSection := ""
487
488 labelsByArch := map[string][]string{}
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400489 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500490 labelString := fmt.Sprintf("\"%s\"", canonicalizeLabel(val.label))
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400491 archString := getArchString(val)
492 labelsByArch[archString] = append(labelsByArch[archString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400493 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400494
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400495 configNodeLabels := []string{}
496 for archString, labels := range labelsByArch {
497 configNodeLabels = append(configNodeLabels, fmt.Sprintf("\":%s\"", archString))
498 labelsString := strings.Join(labels, ",\n ")
499 configNodesSection += fmt.Sprintf(configNodeFormatString, archString, archString, labelsString)
500 }
501
502 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(configNodeLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400503}
504
Chris Parsons944e7d02021-03-11 11:08:46 -0500505func indent(original string) string {
506 result := ""
507 for _, line := range strings.Split(original, "\n") {
508 result += " " + line + "\n"
509 }
510 return result
511}
512
Chris Parsons808d84c2021-03-09 20:43:32 -0500513// Returns the file contents of the buildroot.cquery file that should be used for the cquery
514// expression in order to obtain information about buildroot and its dependencies.
515// The contents of this file depend on the bazelContext's requests; requests are enumerated
516// and grouped by their request type. The data retrieved for each label depends on its
517// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400518func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400519 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons944e7d02021-03-11 11:08:46 -0500520 for val, _ := range context.requests {
521 cqueryId := getCqueryId(val)
522 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
523 requestTypeToCqueryIdEntries[val.requestType] =
524 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
525 }
526 labelRegistrationMapSection := ""
527 functionDefSection := ""
528 mainSwitchSection := ""
529
530 mapDeclarationFormatString := `
531%s = {
532 %s
533}
534`
535 functionDefFormatString := `
536def %s(target):
537%s
538`
539 mainSwitchSectionFormatString := `
540 if id_string in %s:
541 return id_string + ">>" + %s(target)
542`
543
Liz Kammer66ffdb72021-04-02 13:26:07 -0400544 for requestType, _ := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500545 labelMapName := requestType.Name() + "_Labels"
546 functionName := requestType.Name() + "_Fn"
547 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
548 labelMapName,
549 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
550 functionDefSection += fmt.Sprintf(functionDefFormatString,
551 functionName,
552 indent(requestType.StarlarkFunctionBody()))
553 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
554 labelMapName, functionName)
555 }
556
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400557 formatString := `
558# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400559
Chris Parsons944e7d02021-03-11 11:08:46 -0500560# Label Map Section
561%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500562
Chris Parsons944e7d02021-03-11 11:08:46 -0500563# Function Def Section
564%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500565
566def get_arch(target):
567 buildoptions = build_options(target)
568 platforms = build_options(target)["//command_line_option:platforms"]
569 if len(platforms) != 1:
570 # An individual configured target should have only one platform architecture.
571 # Note that it's fine for there to be multiple architectures for the same label,
572 # but each is its own configured target.
573 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
574 platform_name = build_options(target)["//command_line_option:platforms"][0].name
575 if platform_name == "host":
576 return "HOST"
Jingwen Chen91220d72021-03-24 02:18:33 -0400577 elif not platform_name.startswith("android_"):
578 fail("expected platform name of the form 'android_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500579 return "UNKNOWN"
Jingwen Chen91220d72021-03-24 02:18:33 -0400580 return platform_name[len("android_"):]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500581
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400582def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500583 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500584
585 # Main switch section
586 %s
587 # This target was not requested via cquery, and thus must be a dependency
588 # of a requested target.
589 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400590`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400591
Chris Parsons944e7d02021-03-11 11:08:46 -0500592 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
593 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400594}
595
Chris Parsons8ccdb632020-11-17 15:41:01 -0500596// Returns a workspace-relative path containing build-related metadata required
597// for interfacing with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400598func (p *bazelPaths) intermediatesDir() string {
599 return filepath.Join(p.buildDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500600}
601
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400602// Issues commands to Bazel to receive results for all cquery requests
603// queued in the BazelContext.
604func (context *bazelContext) InvokeBazel() error {
605 context.results = make(map[cqueryKey]string)
606
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400607 var cqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500608 var cqueryErr string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400609 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500610
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400611 intermediatesDirPath := absolutePath(context.paths.intermediatesDir())
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500612 if _, err := os.Stat(intermediatesDirPath); os.IsNotExist(err) {
613 err = os.Mkdir(intermediatesDirPath, 0777)
614 }
615
Chris Parsons8ccdb632020-11-17 15:41:01 -0500616 if err != nil {
617 return err
618 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400619 err = ioutil.WriteFile(
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400620 filepath.Join(intermediatesDirPath, "main.bzl"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400621 context.mainBzlFileContents(), 0666)
622 if err != nil {
623 return err
624 }
625 err = ioutil.WriteFile(
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400626 filepath.Join(intermediatesDirPath, "BUILD.bazel"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400627 context.mainBuildFileContents(), 0666)
628 if err != nil {
629 return err
630 }
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400631 cqueryFileRelpath := filepath.Join(context.paths.intermediatesDir(), "buildroot.cquery")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400632 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800633 absolutePath(cqueryFileRelpath),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400634 context.cqueryStarlarkFileContents(), 0666)
635 if err != nil {
636 return err
637 }
Chris Parsons8ccdb632020-11-17 15:41:01 -0500638 err = ioutil.WriteFile(
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400639 filepath.Join(intermediatesDirPath, "WORKSPACE.bazel"),
Chris Parsons8ccdb632020-11-17 15:41:01 -0500640 context.workspaceFileContents(), 0666)
641 if err != nil {
642 return err
643 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800644 buildrootLabel := "//:buildroot"
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400645 cqueryOutput, cqueryErr, err = context.issueBazelCommand(
646 context.paths,
647 bazel.CqueryBuildRootRunName,
648 bazelCommand{"cquery", fmt.Sprintf("kind(rule, deps(%s))", buildrootLabel)},
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400649 "--output=starlark",
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800650 "--starlark:file="+cqueryFileRelpath)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400651 err = ioutil.WriteFile(filepath.Join(intermediatesDirPath, "cquery.out"),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500652 []byte(cqueryOutput), 0666)
653 if err != nil {
654 return err
655 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400656
657 if err != nil {
658 return err
659 }
660
661 cqueryResults := map[string]string{}
662 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
663 if strings.Contains(outputLine, ">>") {
664 splitLine := strings.SplitN(outputLine, ">>", 2)
665 cqueryResults[splitLine[0]] = splitLine[1]
666 }
667 }
668
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400669 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500670 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400671 context.results[val] = string(cqueryResult)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400672 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500673 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
674 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400675 }
676 }
677
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500678 // Issue an aquery command to retrieve action information about the bazel build tree.
679 //
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400680 // TODO(cparsons): Use --target_pattern_file to avoid command line limits.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500681 var aqueryOutput string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400682 aqueryOutput, _, err = context.issueBazelCommand(
683 context.paths,
684 bazel.AqueryBuildRootRunName,
685 bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)},
686 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
687 // proto sources, which would add a number of unnecessary dependencies.
688 "--output=jsonproto")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400689
690 if err != nil {
691 return err
692 }
693
Chris Parsons4f069892021-01-15 12:22:41 -0500694 context.buildStatements, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
695 if err != nil {
696 return err
697 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500698
699 // Issue a build command of the phony root to generate symlink forests for dependencies of the
700 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
701 // but some of symlinks may be required to resolve source dependencies of the build.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400702 _, _, err = context.issueBazelCommand(
703 context.paths,
704 bazel.BazelBuildPhonyRootRunName,
705 bazelCommand{"build", "//:phonyroot"})
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500706
707 if err != nil {
708 return err
709 }
710
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400711 // Clear requests.
712 context.requests = map[cqueryKey]bool{}
713 return nil
714}
Chris Parsonsa798d962020-10-12 23:44:08 -0400715
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500716func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
717 return context.buildStatements
718}
719
720func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400721 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500722}
723
Chris Parsonsa798d962020-10-12 23:44:08 -0400724// Singleton used for registering BUILD file ninja dependencies (needed
725// for correctness of builds which use Bazel.
726func BazelSingleton() Singleton {
727 return &bazelSingleton{}
728}
729
730type bazelSingleton struct{}
731
732func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500733 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
734 if !ctx.Config().BazelContext.BazelEnabled() {
735 return
736 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400737
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500738 // Add ninja file dependencies for files which all bazel invocations require.
739 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200740 filepath.Dir(bootstrap.CmdlineArgs.ModuleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500741 ctx.AddNinjaFileDeps(bazelBuildList)
742
743 data, err := ioutil.ReadFile(bazelBuildList)
744 if err != nil {
745 ctx.Errorf(err.Error())
746 }
747 files := strings.Split(strings.TrimSpace(string(data)), "\n")
748 for _, file := range files {
749 ctx.AddNinjaFileDeps(file)
750 }
751
752 // Register bazel-owned build statements (obtained from the aquery invocation).
753 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500754 if len(buildStatement.Command) < 1 {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000755 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500756 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500757 rule := NewRuleBuilder(pctx, ctx)
758 cmd := rule.Command()
759 cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ && %s",
760 ctx.Config().BazelContext.OutputBase(), buildStatement.Command))
761
762 for _, outputPath := range buildStatement.OutputPaths {
763 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400764 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500765 for _, inputPath := range buildStatement.InputPaths {
766 cmd.Implicit(PathForBazelOut(ctx, inputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400767 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500768
Liz Kammerde116852021-03-25 16:42:37 -0400769 if depfile := buildStatement.Depfile; depfile != nil {
770 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
771 }
772
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500773 // This is required to silence warnings pertaining to unexpected timestamps. Particularly,
774 // some Bazel builtins (such as files in the bazel_tools directory) have far-future
775 // timestamps. Without restat, Ninja would emit warnings that the input files of a
776 // build statement have later timestamps than the outputs.
777 rule.Restat()
778
Liz Kammer13548d72020-12-16 11:13:30 -0800779 rule.Build(fmt.Sprintf("bazel %d", index), buildStatement.Mnemonic)
Chris Parsonsa798d962020-10-12 23:44:08 -0400780 }
781}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500782
783func getCqueryId(key cqueryKey) string {
784 return canonicalizeLabel(key.label) + "|" + getArchString(key)
785}
786
787func getArchString(key cqueryKey) string {
788 arch := key.archType.Name
789 if len(arch) > 0 {
790 return arch
791 } else {
792 return "x86_64"
793 }
794}