blob: 4598995f959b2bcc2547fc56d50625324b426803 [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())
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400350 bazelCmd.Env = append(os.Environ(), "HOME="+paths.homeDir, pwdPrefix(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500351 // Disables local host detection of gcc; toolchain information is defined
352 // explicitly in BUILD files.
353 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
Colin Crossff0278b2020-10-09 19:24:15 -0700354 stderr := &bytes.Buffer{}
355 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400356
357 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500358 return "", string(stderr.Bytes()),
359 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400360 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500361 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400362 }
363}
364
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400365func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500366 // TODO(cparsons): Define configuration transitions programmatically based
367 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400368 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500369#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400370# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500371#####################################################
372
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400373def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500374 return {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200375 "//command_line_option:platforms": "@//build/bazel/platforms:android_%s" % attr.arch,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500376 }
377
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400378_config_node_transition = transition(
379 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500380 inputs = [],
381 outputs = [
382 "//command_line_option:platforms",
383 ],
384)
385
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400386def _passthrough_rule_impl(ctx):
387 return [DefaultInfo(files = depset(ctx.files.deps))]
388
389config_node = rule(
390 implementation = _passthrough_rule_impl,
391 attrs = {
392 "arch" : attr.string(mandatory = True),
393 "deps" : attr.label_list(cfg = _config_node_transition),
394 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
395 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500396)
397
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400398
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500399# Rule representing the root of the build, to depend on all Bazel targets that
400# are required for the build. Building this target will build the entire Bazel
401# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400402mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400403 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500404 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400405 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500406 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400407)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500408
409def _phony_root_impl(ctx):
410 return []
411
412# Rule to depend on other targets but build nothing.
413# This is useful as follows: building a target of this rule will generate
414# symlink forests for all dependencies of the target, without executing any
415# actions of the build.
416phony_root = rule(
417 implementation = _phony_root_impl,
418 attrs = {"deps" : attr.label_list()},
419)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400420`
421 return []byte(contents)
422}
423
424func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500425 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
426 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400427 formatString := `
428# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400429load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
430
431%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400432
433mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400434 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400435)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500436
437phony_root(name = "phonyroot",
438 deps = [":buildroot"],
439)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400440`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400441 configNodeFormatString := `
442config_node(name = "%s",
443 arch = "%s",
444 deps = [%s],
445)
446`
447
448 configNodesSection := ""
449
450 labelsByArch := map[string][]string{}
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400451 for val, _ := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200452 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400453 archString := getArchString(val)
454 labelsByArch[archString] = append(labelsByArch[archString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400455 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400456
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400457 configNodeLabels := []string{}
458 for archString, labels := range labelsByArch {
459 configNodeLabels = append(configNodeLabels, fmt.Sprintf("\":%s\"", archString))
460 labelsString := strings.Join(labels, ",\n ")
461 configNodesSection += fmt.Sprintf(configNodeFormatString, archString, archString, labelsString)
462 }
463
464 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(configNodeLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400465}
466
Chris Parsons944e7d02021-03-11 11:08:46 -0500467func indent(original string) string {
468 result := ""
469 for _, line := range strings.Split(original, "\n") {
470 result += " " + line + "\n"
471 }
472 return result
473}
474
Chris Parsons808d84c2021-03-09 20:43:32 -0500475// Returns the file contents of the buildroot.cquery file that should be used for the cquery
476// expression in order to obtain information about buildroot and its dependencies.
477// The contents of this file depend on the bazelContext's requests; requests are enumerated
478// and grouped by their request type. The data retrieved for each label depends on its
479// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400480func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400481 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons944e7d02021-03-11 11:08:46 -0500482 for val, _ := range context.requests {
483 cqueryId := getCqueryId(val)
484 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
485 requestTypeToCqueryIdEntries[val.requestType] =
486 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
487 }
488 labelRegistrationMapSection := ""
489 functionDefSection := ""
490 mainSwitchSection := ""
491
492 mapDeclarationFormatString := `
493%s = {
494 %s
495}
496`
497 functionDefFormatString := `
498def %s(target):
499%s
500`
501 mainSwitchSectionFormatString := `
502 if id_string in %s:
503 return id_string + ">>" + %s(target)
504`
505
Liz Kammer66ffdb72021-04-02 13:26:07 -0400506 for requestType, _ := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500507 labelMapName := requestType.Name() + "_Labels"
508 functionName := requestType.Name() + "_Fn"
509 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
510 labelMapName,
511 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
512 functionDefSection += fmt.Sprintf(functionDefFormatString,
513 functionName,
514 indent(requestType.StarlarkFunctionBody()))
515 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
516 labelMapName, functionName)
517 }
518
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400519 formatString := `
520# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400521
Chris Parsons944e7d02021-03-11 11:08:46 -0500522# Label Map Section
523%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500524
Chris Parsons944e7d02021-03-11 11:08:46 -0500525# Function Def Section
526%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500527
528def get_arch(target):
529 buildoptions = build_options(target)
530 platforms = build_options(target)["//command_line_option:platforms"]
531 if len(platforms) != 1:
532 # An individual configured target should have only one platform architecture.
533 # Note that it's fine for there to be multiple architectures for the same label,
534 # but each is its own configured target.
535 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
536 platform_name = build_options(target)["//command_line_option:platforms"][0].name
537 if platform_name == "host":
538 return "HOST"
Jingwen Chen91220d72021-03-24 02:18:33 -0400539 elif not platform_name.startswith("android_"):
540 fail("expected platform name of the form 'android_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500541 return "UNKNOWN"
Jingwen Chen91220d72021-03-24 02:18:33 -0400542 return platform_name[len("android_"):]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500543
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400544def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500545 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500546
547 # Main switch section
548 %s
549 # This target was not requested via cquery, and thus must be a dependency
550 # of a requested target.
551 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400552`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400553
Chris Parsons944e7d02021-03-11 11:08:46 -0500554 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
555 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400556}
557
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200558// Returns a path containing build-related metadata required for interfacing
559// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400560func (p *bazelPaths) intermediatesDir() string {
561 return filepath.Join(p.buildDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500562}
563
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200564// Returns the path where the contents of the @soong_injection repository live.
565// It is used by Soong to tell Bazel things it cannot over the command line.
566func (p *bazelPaths) injectedFilesDir() string {
567 return filepath.Join(p.buildDir, "soong_injection")
568}
569
570// Returns the path of the synthetic Bazel workspace that contains a symlink
571// forest composed the whole source tree and BUILD files generated by bp2build.
572func (p *bazelPaths) syntheticWorkspaceDir() string {
573 return filepath.Join(p.buildDir, "workspace")
574}
575
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400576// Issues commands to Bazel to receive results for all cquery requests
577// queued in the BazelContext.
578func (context *bazelContext) InvokeBazel() error {
579 context.results = make(map[cqueryKey]string)
580
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400581 var cqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500582 var cqueryErr string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400583 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500584
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200585 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
586 if _, err := os.Stat(soongInjectionPath); os.IsNotExist(err) {
587 err = os.Mkdir(soongInjectionPath, 0777)
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500588 }
Chris Parsons8ccdb632020-11-17 15:41:01 -0500589 if err != nil {
590 return err
591 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200592
593 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666)
594 if err != nil {
595 return err
596 }
597
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400598 err = ioutil.WriteFile(
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200599 filepath.Join(soongInjectionPath, "main.bzl"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400600 context.mainBzlFileContents(), 0666)
601 if err != nil {
602 return err
603 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200604
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400605 err = ioutil.WriteFile(
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200606 filepath.Join(soongInjectionPath, "BUILD.bazel"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400607 context.mainBuildFileContents(), 0666)
608 if err != nil {
609 return err
610 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200611 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400612 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800613 absolutePath(cqueryFileRelpath),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400614 context.cqueryStarlarkFileContents(), 0666)
615 if err != nil {
616 return err
617 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200618 buildrootLabel := "@soong_injection//:buildroot"
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400619 cqueryOutput, cqueryErr, err = context.issueBazelCommand(
620 context.paths,
621 bazel.CqueryBuildRootRunName,
622 bazelCommand{"cquery", fmt.Sprintf("kind(rule, deps(%s))", buildrootLabel)},
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400623 "--output=starlark",
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200624 "--starlark:file="+absolutePath(cqueryFileRelpath))
625 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500626 []byte(cqueryOutput), 0666)
627 if err != nil {
628 return err
629 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400630
631 if err != nil {
632 return err
633 }
634
635 cqueryResults := map[string]string{}
636 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
637 if strings.Contains(outputLine, ">>") {
638 splitLine := strings.SplitN(outputLine, ">>", 2)
639 cqueryResults[splitLine[0]] = splitLine[1]
640 }
641 }
642
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400643 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500644 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400645 context.results[val] = string(cqueryResult)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400646 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500647 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
648 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400649 }
650 }
651
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500652 // Issue an aquery command to retrieve action information about the bazel build tree.
653 //
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400654 // TODO(cparsons): Use --target_pattern_file to avoid command line limits.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500655 var aqueryOutput string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400656 aqueryOutput, _, err = context.issueBazelCommand(
657 context.paths,
658 bazel.AqueryBuildRootRunName,
659 bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)},
660 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
661 // proto sources, which would add a number of unnecessary dependencies.
662 "--output=jsonproto")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400663
664 if err != nil {
665 return err
666 }
667
Chris Parsons4f069892021-01-15 12:22:41 -0500668 context.buildStatements, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
669 if err != nil {
670 return err
671 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500672
673 // Issue a build command of the phony root to generate symlink forests for dependencies of the
674 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
675 // but some of symlinks may be required to resolve source dependencies of the build.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400676 _, _, err = context.issueBazelCommand(
677 context.paths,
678 bazel.BazelBuildPhonyRootRunName,
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200679 bazelCommand{"build", "@soong_injection//:phonyroot"})
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500680
681 if err != nil {
682 return err
683 }
684
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400685 // Clear requests.
686 context.requests = map[cqueryKey]bool{}
687 return nil
688}
Chris Parsonsa798d962020-10-12 23:44:08 -0400689
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500690func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
691 return context.buildStatements
692}
693
694func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400695 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500696}
697
Chris Parsonsa798d962020-10-12 23:44:08 -0400698// Singleton used for registering BUILD file ninja dependencies (needed
699// for correctness of builds which use Bazel.
700func BazelSingleton() Singleton {
701 return &bazelSingleton{}
702}
703
704type bazelSingleton struct{}
705
706func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500707 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
708 if !ctx.Config().BazelContext.BazelEnabled() {
709 return
710 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400711
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500712 // Add ninja file dependencies for files which all bazel invocations require.
713 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200714 filepath.Dir(bootstrap.CmdlineArgs.ModuleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500715 ctx.AddNinjaFileDeps(bazelBuildList)
716
717 data, err := ioutil.ReadFile(bazelBuildList)
718 if err != nil {
719 ctx.Errorf(err.Error())
720 }
721 files := strings.Split(strings.TrimSpace(string(data)), "\n")
722 for _, file := range files {
723 ctx.AddNinjaFileDeps(file)
724 }
725
726 // Register bazel-owned build statements (obtained from the aquery invocation).
727 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500728 if len(buildStatement.Command) < 1 {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000729 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500730 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500731 rule := NewRuleBuilder(pctx, ctx)
732 cmd := rule.Command()
733 cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ && %s",
734 ctx.Config().BazelContext.OutputBase(), buildStatement.Command))
735
736 for _, outputPath := range buildStatement.OutputPaths {
737 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400738 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500739 for _, inputPath := range buildStatement.InputPaths {
740 cmd.Implicit(PathForBazelOut(ctx, inputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400741 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500742
Liz Kammerde116852021-03-25 16:42:37 -0400743 if depfile := buildStatement.Depfile; depfile != nil {
744 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
745 }
746
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500747 // This is required to silence warnings pertaining to unexpected timestamps. Particularly,
748 // some Bazel builtins (such as files in the bazel_tools directory) have far-future
749 // timestamps. Without restat, Ninja would emit warnings that the input files of a
750 // build statement have later timestamps than the outputs.
751 rule.Restat()
752
Liz Kammer13548d72020-12-16 11:13:30 -0800753 rule.Build(fmt.Sprintf("bazel %d", index), buildStatement.Mnemonic)
Chris Parsonsa798d962020-10-12 23:44:08 -0400754 }
755}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500756
757func getCqueryId(key cqueryKey) string {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200758 return key.label + "|" + getArchString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500759}
760
761func getArchString(key cqueryKey) string {
762 arch := key.archType.Name
763 if len(arch) > 0 {
764 return arch
765 } else {
766 return "x86_64"
767 }
768}