blob: 8cddbb2a336b539d8decac06394a8533ba5d8cad [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) {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200324 cmdFlags := []string{"--output_base=" + absolutePath(paths.outputBase), command.command}
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400325 cmdFlags = append(cmdFlags, command.expression)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400326 cmdFlags = append(cmdFlags, "--profile="+shared.BazelMetricsFilename(paths, runName))
Jingwen Chen91220d72021-03-24 02:18:33 -0400327
328 // Set default platforms to canonicalized values for mixed builds requests.
329 // If these are set in the bazelrc, they will have values that are
330 // non-canonicalized to @sourceroot labels, and thus be invalid when
331 // referenced from the buildroot.
332 //
333 // The actual platform values here may be overridden by configuration
334 // transitions from the buildroot.
Chris Parsonsee423b02021-02-08 23:04:59 -0500335 cmdFlags = append(cmdFlags,
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200336 fmt.Sprintf("--platforms=%s", "//build/bazel/platforms:android_x86_64"))
Chris Parsonsee423b02021-02-08 23:04:59 -0500337 cmdFlags = append(cmdFlags,
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200338 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"))
Jingwen Chen91220d72021-03-24 02:18:33 -0400339 // This should be parameterized on the host OS, but let's restrict to linux
340 // to keep things simple for now.
341 cmdFlags = append(cmdFlags,
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200342 fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"))
Jingwen Chen91220d72021-03-24 02:18:33 -0400343
Chris Parsons8d6e4332021-02-22 16:13:50 -0500344 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
345 cmdFlags = append(cmdFlags, "--experimental_repository_disable_download")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400346 cmdFlags = append(cmdFlags, extraFlags...)
347
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400348 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200349 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200350 bazelCmd.Env = append(os.Environ(),
351 "HOME="+paths.homeDir,
352 pwdPrefix(),
353 "BUILD_DIR="+absolutePath(paths.buildDir),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500354 // Disables local host detection of gcc; toolchain information is defined
355 // explicitly in BUILD files.
356 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
Colin Crossff0278b2020-10-09 19:24:15 -0700357 stderr := &bytes.Buffer{}
358 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400359
360 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500361 return "", string(stderr.Bytes()),
362 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400363 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500364 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400365 }
366}
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 {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200378 "//command_line_option:platforms": "@//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
427func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500428 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
429 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400430 formatString := `
431# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400432load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
433
434%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400435
436mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400437 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400438)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500439
440phony_root(name = "phonyroot",
441 deps = [":buildroot"],
442)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400443`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400444 configNodeFormatString := `
445config_node(name = "%s",
446 arch = "%s",
447 deps = [%s],
448)
449`
450
451 configNodesSection := ""
452
453 labelsByArch := map[string][]string{}
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400454 for val, _ := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200455 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400456 archString := getArchString(val)
457 labelsByArch[archString] = append(labelsByArch[archString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400458 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400459
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400460 configNodeLabels := []string{}
461 for archString, labels := range labelsByArch {
462 configNodeLabels = append(configNodeLabels, fmt.Sprintf("\":%s\"", archString))
463 labelsString := strings.Join(labels, ",\n ")
464 configNodesSection += fmt.Sprintf(configNodeFormatString, archString, archString, labelsString)
465 }
466
467 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(configNodeLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400468}
469
Chris Parsons944e7d02021-03-11 11:08:46 -0500470func indent(original string) string {
471 result := ""
472 for _, line := range strings.Split(original, "\n") {
473 result += " " + line + "\n"
474 }
475 return result
476}
477
Chris Parsons808d84c2021-03-09 20:43:32 -0500478// Returns the file contents of the buildroot.cquery file that should be used for the cquery
479// expression in order to obtain information about buildroot and its dependencies.
480// The contents of this file depend on the bazelContext's requests; requests are enumerated
481// and grouped by their request type. The data retrieved for each label depends on its
482// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400483func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400484 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons944e7d02021-03-11 11:08:46 -0500485 for val, _ := range context.requests {
486 cqueryId := getCqueryId(val)
487 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
488 requestTypeToCqueryIdEntries[val.requestType] =
489 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
490 }
491 labelRegistrationMapSection := ""
492 functionDefSection := ""
493 mainSwitchSection := ""
494
495 mapDeclarationFormatString := `
496%s = {
497 %s
498}
499`
500 functionDefFormatString := `
501def %s(target):
502%s
503`
504 mainSwitchSectionFormatString := `
505 if id_string in %s:
506 return id_string + ">>" + %s(target)
507`
508
Liz Kammer66ffdb72021-04-02 13:26:07 -0400509 for requestType, _ := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500510 labelMapName := requestType.Name() + "_Labels"
511 functionName := requestType.Name() + "_Fn"
512 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
513 labelMapName,
514 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
515 functionDefSection += fmt.Sprintf(functionDefFormatString,
516 functionName,
517 indent(requestType.StarlarkFunctionBody()))
518 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
519 labelMapName, functionName)
520 }
521
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400522 formatString := `
523# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400524
Chris Parsons944e7d02021-03-11 11:08:46 -0500525# Label Map Section
526%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500527
Chris Parsons944e7d02021-03-11 11:08:46 -0500528# Function Def Section
529%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500530
531def get_arch(target):
532 buildoptions = build_options(target)
533 platforms = build_options(target)["//command_line_option:platforms"]
534 if len(platforms) != 1:
535 # An individual configured target should have only one platform architecture.
536 # Note that it's fine for there to be multiple architectures for the same label,
537 # but each is its own configured target.
538 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
539 platform_name = build_options(target)["//command_line_option:platforms"][0].name
540 if platform_name == "host":
541 return "HOST"
Jingwen Chen91220d72021-03-24 02:18:33 -0400542 elif not platform_name.startswith("android_"):
543 fail("expected platform name of the form 'android_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500544 return "UNKNOWN"
Jingwen Chen91220d72021-03-24 02:18:33 -0400545 return platform_name[len("android_"):]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500546
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400547def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500548 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500549
550 # Main switch section
551 %s
552 # This target was not requested via cquery, and thus must be a dependency
553 # of a requested target.
554 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400555`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400556
Chris Parsons944e7d02021-03-11 11:08:46 -0500557 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
558 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400559}
560
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200561// Returns a path containing build-related metadata required for interfacing
562// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400563func (p *bazelPaths) intermediatesDir() string {
564 return filepath.Join(p.buildDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500565}
566
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200567// Returns the path where the contents of the @soong_injection repository live.
568// It is used by Soong to tell Bazel things it cannot over the command line.
569func (p *bazelPaths) injectedFilesDir() string {
570 return filepath.Join(p.buildDir, "soong_injection")
571}
572
573// Returns the path of the synthetic Bazel workspace that contains a symlink
574// forest composed the whole source tree and BUILD files generated by bp2build.
575func (p *bazelPaths) syntheticWorkspaceDir() string {
576 return filepath.Join(p.buildDir, "workspace")
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
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200588 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200589 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
590 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
591 err = os.MkdirAll(mixedBuildsPath, 0777)
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500592 }
Chris Parsons8ccdb632020-11-17 15:41:01 -0500593 if err != nil {
594 return err
595 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200596
597 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666)
598 if err != nil {
599 return err
600 }
601
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400602 err = ioutil.WriteFile(
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200603 filepath.Join(mixedBuildsPath, "main.bzl"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400604 context.mainBzlFileContents(), 0666)
605 if err != nil {
606 return err
607 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200608
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400609 err = ioutil.WriteFile(
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200610 filepath.Join(mixedBuildsPath, "BUILD.bazel"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400611 context.mainBuildFileContents(), 0666)
612 if err != nil {
613 return err
614 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200615 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400616 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800617 absolutePath(cqueryFileRelpath),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400618 context.cqueryStarlarkFileContents(), 0666)
619 if err != nil {
620 return err
621 }
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200622 buildrootLabel := "@soong_injection//mixed_builds:buildroot"
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400623 cqueryOutput, cqueryErr, err = context.issueBazelCommand(
624 context.paths,
625 bazel.CqueryBuildRootRunName,
626 bazelCommand{"cquery", fmt.Sprintf("kind(rule, deps(%s))", buildrootLabel)},
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400627 "--output=starlark",
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200628 "--starlark:file="+absolutePath(cqueryFileRelpath))
629 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500630 []byte(cqueryOutput), 0666)
631 if err != nil {
632 return err
633 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400634
635 if err != nil {
636 return err
637 }
638
639 cqueryResults := map[string]string{}
640 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
641 if strings.Contains(outputLine, ">>") {
642 splitLine := strings.SplitN(outputLine, ">>", 2)
643 cqueryResults[splitLine[0]] = splitLine[1]
644 }
645 }
646
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400647 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500648 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400649 context.results[val] = string(cqueryResult)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400650 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500651 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
652 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400653 }
654 }
655
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500656 // Issue an aquery command to retrieve action information about the bazel build tree.
657 //
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400658 // TODO(cparsons): Use --target_pattern_file to avoid command line limits.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500659 var aqueryOutput string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400660 aqueryOutput, _, err = context.issueBazelCommand(
661 context.paths,
662 bazel.AqueryBuildRootRunName,
663 bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)},
664 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
665 // proto sources, which would add a number of unnecessary dependencies.
666 "--output=jsonproto")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400667
668 if err != nil {
669 return err
670 }
671
Chris Parsons4f069892021-01-15 12:22:41 -0500672 context.buildStatements, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
673 if err != nil {
674 return err
675 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500676
677 // Issue a build command of the phony root to generate symlink forests for dependencies of the
678 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
679 // but some of symlinks may be required to resolve source dependencies of the build.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400680 _, _, err = context.issueBazelCommand(
681 context.paths,
682 bazel.BazelBuildPhonyRootRunName,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200683 bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"})
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500684
685 if err != nil {
686 return err
687 }
688
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400689 // Clear requests.
690 context.requests = map[cqueryKey]bool{}
691 return nil
692}
Chris Parsonsa798d962020-10-12 23:44:08 -0400693
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500694func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
695 return context.buildStatements
696}
697
698func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400699 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500700}
701
Chris Parsonsa798d962020-10-12 23:44:08 -0400702// Singleton used for registering BUILD file ninja dependencies (needed
703// for correctness of builds which use Bazel.
704func BazelSingleton() Singleton {
705 return &bazelSingleton{}
706}
707
708type bazelSingleton struct{}
709
710func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500711 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
712 if !ctx.Config().BazelContext.BazelEnabled() {
713 return
714 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400715
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500716 // Add ninja file dependencies for files which all bazel invocations require.
717 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200718 filepath.Dir(bootstrap.CmdlineArgs.ModuleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500719 ctx.AddNinjaFileDeps(bazelBuildList)
720
721 data, err := ioutil.ReadFile(bazelBuildList)
722 if err != nil {
723 ctx.Errorf(err.Error())
724 }
725 files := strings.Split(strings.TrimSpace(string(data)), "\n")
726 for _, file := range files {
727 ctx.AddNinjaFileDeps(file)
728 }
729
730 // Register bazel-owned build statements (obtained from the aquery invocation).
731 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500732 if len(buildStatement.Command) < 1 {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000733 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500734 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500735 rule := NewRuleBuilder(pctx, ctx)
736 cmd := rule.Command()
737 cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ && %s",
738 ctx.Config().BazelContext.OutputBase(), buildStatement.Command))
739
740 for _, outputPath := range buildStatement.OutputPaths {
741 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400742 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500743 for _, inputPath := range buildStatement.InputPaths {
744 cmd.Implicit(PathForBazelOut(ctx, inputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400745 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500746
Liz Kammerde116852021-03-25 16:42:37 -0400747 if depfile := buildStatement.Depfile; depfile != nil {
748 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
749 }
750
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500751 // This is required to silence warnings pertaining to unexpected timestamps. Particularly,
752 // some Bazel builtins (such as files in the bazel_tools directory) have far-future
753 // timestamps. Without restat, Ninja would emit warnings that the input files of a
754 // build statement have later timestamps than the outputs.
755 rule.Restat()
756
Liz Kammer13548d72020-12-16 11:13:30 -0800757 rule.Build(fmt.Sprintf("bazel %d", index), buildStatement.Mnemonic)
Chris Parsonsa798d962020-10-12 23:44:08 -0400758 }
759}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500760
761func getCqueryId(key cqueryKey) string {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200762 return key.label + "|" + getArchString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500763}
764
765func getArchString(key cqueryKey) string {
766 arch := key.archType.Name
767 if len(arch) > 0 {
768 return arch
769 } else {
770 return "x86_64"
771 }
772}