blob: c6364af8add1ffeda5f1136f3e25bf1de6a2aa72 [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.
Jingwen Chen442b1a42021-06-17 07:02:15 +0000208 if !c.IsEnvTrue("USE_BAZEL_ANALYSIS") {
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,
Jingwen Chen6333b0e2021-05-20 01:38:47 +0000336 fmt.Sprintf("--platforms=%s", "//build/bazel/platforms:android_arm"))
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),
Jingwen Chen8c523582021-06-01 11:19:53 +0000354 // Make OUT_DIR absolute here so tools/bazel.sh uses the correct
355 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
356 "OUT_DIR="+absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500357 // Disables local host detection of gcc; toolchain information is defined
358 // explicitly in BUILD files.
359 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
Colin Crossff0278b2020-10-09 19:24:15 -0700360 stderr := &bytes.Buffer{}
361 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400362
363 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons808d84c2021-03-09 20:43:32 -0500364 return "", string(stderr.Bytes()),
365 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400366 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500367 return string(output), string(stderr.Bytes()), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400368 }
369}
370
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400371func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500372 // TODO(cparsons): Define configuration transitions programmatically based
373 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400374 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500375#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400376# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500377#####################################################
378
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400379def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500380 return {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200381 "//command_line_option:platforms": "@//build/bazel/platforms:android_%s" % attr.arch,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500382 }
383
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400384_config_node_transition = transition(
385 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500386 inputs = [],
387 outputs = [
388 "//command_line_option:platforms",
389 ],
390)
391
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400392def _passthrough_rule_impl(ctx):
393 return [DefaultInfo(files = depset(ctx.files.deps))]
394
395config_node = rule(
396 implementation = _passthrough_rule_impl,
397 attrs = {
398 "arch" : attr.string(mandatory = True),
399 "deps" : attr.label_list(cfg = _config_node_transition),
400 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
401 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500402)
403
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400404
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500405# Rule representing the root of the build, to depend on all Bazel targets that
406# are required for the build. Building this target will build the entire Bazel
407# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400408mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400409 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500410 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400411 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500412 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400413)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500414
415def _phony_root_impl(ctx):
416 return []
417
418# Rule to depend on other targets but build nothing.
419# This is useful as follows: building a target of this rule will generate
420# symlink forests for all dependencies of the target, without executing any
421# actions of the build.
422phony_root = rule(
423 implementation = _phony_root_impl,
424 attrs = {"deps" : attr.label_list()},
425)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400426`
427 return []byte(contents)
428}
429
430func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500431 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
432 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400433 formatString := `
434# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400435load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
436
437%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400438
439mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400440 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400441)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500442
443phony_root(name = "phonyroot",
444 deps = [":buildroot"],
445)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400446`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400447 configNodeFormatString := `
448config_node(name = "%s",
449 arch = "%s",
450 deps = [%s],
451)
452`
453
454 configNodesSection := ""
455
456 labelsByArch := map[string][]string{}
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400457 for val, _ := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200458 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400459 archString := getArchString(val)
460 labelsByArch[archString] = append(labelsByArch[archString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400461 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400462
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400463 configNodeLabels := []string{}
464 for archString, labels := range labelsByArch {
465 configNodeLabels = append(configNodeLabels, fmt.Sprintf("\":%s\"", archString))
466 labelsString := strings.Join(labels, ",\n ")
467 configNodesSection += fmt.Sprintf(configNodeFormatString, archString, archString, labelsString)
468 }
469
470 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(configNodeLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400471}
472
Chris Parsons944e7d02021-03-11 11:08:46 -0500473func indent(original string) string {
474 result := ""
475 for _, line := range strings.Split(original, "\n") {
476 result += " " + line + "\n"
477 }
478 return result
479}
480
Chris Parsons808d84c2021-03-09 20:43:32 -0500481// Returns the file contents of the buildroot.cquery file that should be used for the cquery
482// expression in order to obtain information about buildroot and its dependencies.
483// The contents of this file depend on the bazelContext's requests; requests are enumerated
484// and grouped by their request type. The data retrieved for each label depends on its
485// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400486func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400487 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons944e7d02021-03-11 11:08:46 -0500488 for val, _ := range context.requests {
489 cqueryId := getCqueryId(val)
490 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
491 requestTypeToCqueryIdEntries[val.requestType] =
492 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
493 }
494 labelRegistrationMapSection := ""
495 functionDefSection := ""
496 mainSwitchSection := ""
497
498 mapDeclarationFormatString := `
499%s = {
500 %s
501}
502`
503 functionDefFormatString := `
504def %s(target):
505%s
506`
507 mainSwitchSectionFormatString := `
508 if id_string in %s:
509 return id_string + ">>" + %s(target)
510`
511
Liz Kammer66ffdb72021-04-02 13:26:07 -0400512 for requestType, _ := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500513 labelMapName := requestType.Name() + "_Labels"
514 functionName := requestType.Name() + "_Fn"
515 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
516 labelMapName,
517 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
518 functionDefSection += fmt.Sprintf(functionDefFormatString,
519 functionName,
520 indent(requestType.StarlarkFunctionBody()))
521 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
522 labelMapName, functionName)
523 }
524
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400525 formatString := `
526# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400527
Chris Parsons944e7d02021-03-11 11:08:46 -0500528# Label Map Section
529%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500530
Chris Parsons944e7d02021-03-11 11:08:46 -0500531# Function Def Section
532%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500533
534def get_arch(target):
535 buildoptions = build_options(target)
536 platforms = build_options(target)["//command_line_option:platforms"]
537 if len(platforms) != 1:
538 # An individual configured target should have only one platform architecture.
539 # Note that it's fine for there to be multiple architectures for the same label,
540 # but each is its own configured target.
541 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
542 platform_name = build_options(target)["//command_line_option:platforms"][0].name
543 if platform_name == "host":
544 return "HOST"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400545 elif platform_name.startswith("android_"):
546 return platform_name[len("android_"):]
547 elif platform_name.startswith("linux_"):
548 return platform_name[len("linux_"):]
549 else:
550 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500551 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500552
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400553def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500554 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500555
556 # Main switch section
557 %s
558 # This target was not requested via cquery, and thus must be a dependency
559 # of a requested target.
560 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400561`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400562
Chris Parsons944e7d02021-03-11 11:08:46 -0500563 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
564 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400565}
566
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200567// Returns a path containing build-related metadata required for interfacing
568// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400569func (p *bazelPaths) intermediatesDir() string {
570 return filepath.Join(p.buildDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500571}
572
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200573// Returns the path where the contents of the @soong_injection repository live.
574// It is used by Soong to tell Bazel things it cannot over the command line.
575func (p *bazelPaths) injectedFilesDir() string {
Liz Kammer09f947d2021-05-12 14:51:49 -0400576 return filepath.Join(p.buildDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200577}
578
579// Returns the path of the synthetic Bazel workspace that contains a symlink
580// forest composed the whole source tree and BUILD files generated by bp2build.
581func (p *bazelPaths) syntheticWorkspaceDir() string {
582 return filepath.Join(p.buildDir, "workspace")
583}
584
Jingwen Chen8c523582021-06-01 11:19:53 +0000585// Returns the path to the top level out dir ($OUT_DIR).
586func (p *bazelPaths) outDir() string {
587 return filepath.Dir(p.buildDir)
588}
589
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400590// Issues commands to Bazel to receive results for all cquery requests
591// queued in the BazelContext.
592func (context *bazelContext) InvokeBazel() error {
593 context.results = make(map[cqueryKey]string)
594
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400595 var cqueryOutput string
Chris Parsons808d84c2021-03-09 20:43:32 -0500596 var cqueryErr string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400597 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500598
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200599 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200600 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
601 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
602 err = os.MkdirAll(mixedBuildsPath, 0777)
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500603 }
Chris Parsons8ccdb632020-11-17 15:41:01 -0500604 if err != nil {
605 return err
606 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200607
608 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666)
609 if err != nil {
610 return err
611 }
612
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400613 err = ioutil.WriteFile(
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200614 filepath.Join(mixedBuildsPath, "main.bzl"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400615 context.mainBzlFileContents(), 0666)
616 if err != nil {
617 return err
618 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200619
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400620 err = ioutil.WriteFile(
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200621 filepath.Join(mixedBuildsPath, "BUILD.bazel"),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400622 context.mainBuildFileContents(), 0666)
623 if err != nil {
624 return err
625 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200626 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400627 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800628 absolutePath(cqueryFileRelpath),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400629 context.cqueryStarlarkFileContents(), 0666)
630 if err != nil {
631 return err
632 }
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200633 buildrootLabel := "@soong_injection//mixed_builds:buildroot"
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400634 cqueryOutput, cqueryErr, err = context.issueBazelCommand(
635 context.paths,
636 bazel.CqueryBuildRootRunName,
637 bazelCommand{"cquery", fmt.Sprintf("kind(rule, deps(%s))", buildrootLabel)},
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400638 "--output=starlark",
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200639 "--starlark:file="+absolutePath(cqueryFileRelpath))
640 err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500641 []byte(cqueryOutput), 0666)
642 if err != nil {
643 return err
644 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400645
646 if err != nil {
647 return err
648 }
649
650 cqueryResults := map[string]string{}
651 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
652 if strings.Contains(outputLine, ">>") {
653 splitLine := strings.SplitN(outputLine, ">>", 2)
654 cqueryResults[splitLine[0]] = splitLine[1]
655 }
656 }
657
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400658 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500659 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400660 context.results[val] = string(cqueryResult)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400661 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500662 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
663 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400664 }
665 }
666
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500667 // Issue an aquery command to retrieve action information about the bazel build tree.
668 //
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400669 // TODO(cparsons): Use --target_pattern_file to avoid command line limits.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500670 var aqueryOutput string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400671 aqueryOutput, _, err = context.issueBazelCommand(
672 context.paths,
673 bazel.AqueryBuildRootRunName,
674 bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)},
675 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
676 // proto sources, which would add a number of unnecessary dependencies.
677 "--output=jsonproto")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400678
679 if err != nil {
680 return err
681 }
682
Chris Parsons4f069892021-01-15 12:22:41 -0500683 context.buildStatements, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
684 if err != nil {
685 return err
686 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500687
688 // Issue a build command of the phony root to generate symlink forests for dependencies of the
689 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
690 // but some of symlinks may be required to resolve source dependencies of the build.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400691 _, _, err = context.issueBazelCommand(
692 context.paths,
693 bazel.BazelBuildPhonyRootRunName,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200694 bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"})
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500695
696 if err != nil {
697 return err
698 }
699
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400700 // Clear requests.
701 context.requests = map[cqueryKey]bool{}
702 return nil
703}
Chris Parsonsa798d962020-10-12 23:44:08 -0400704
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500705func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
706 return context.buildStatements
707}
708
709func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400710 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500711}
712
Chris Parsonsa798d962020-10-12 23:44:08 -0400713// Singleton used for registering BUILD file ninja dependencies (needed
714// for correctness of builds which use Bazel.
715func BazelSingleton() Singleton {
716 return &bazelSingleton{}
717}
718
719type bazelSingleton struct{}
720
721func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500722 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
723 if !ctx.Config().BazelContext.BazelEnabled() {
724 return
725 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400726
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500727 // Add ninja file dependencies for files which all bazel invocations require.
728 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200729 filepath.Dir(bootstrap.CmdlineArgs.ModuleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500730 ctx.AddNinjaFileDeps(bazelBuildList)
731
732 data, err := ioutil.ReadFile(bazelBuildList)
733 if err != nil {
734 ctx.Errorf(err.Error())
735 }
736 files := strings.Split(strings.TrimSpace(string(data)), "\n")
737 for _, file := range files {
738 ctx.AddNinjaFileDeps(file)
739 }
740
741 // Register bazel-owned build statements (obtained from the aquery invocation).
742 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500743 if len(buildStatement.Command) < 1 {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +0000744 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500745 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500746 rule := NewRuleBuilder(pctx, ctx)
747 cmd := rule.Command()
Chris Parsons94a0bba2021-06-04 15:03:47 -0400748
749 // cd into Bazel's execution root, which is the action cwd.
750 cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ && ", ctx.Config().BazelContext.OutputBase()))
751
752 for _, pair := range buildStatement.Env {
753 // Set per-action env variables, if any.
754 cmd.Flag(pair.Key + "=" + pair.Value)
755 }
756
757 // The actual Bazel action.
758 cmd.Text(" " + buildStatement.Command)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500759
760 for _, outputPath := range buildStatement.OutputPaths {
761 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400762 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500763 for _, inputPath := range buildStatement.InputPaths {
764 cmd.Implicit(PathForBazelOut(ctx, inputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400765 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500766
Liz Kammerde116852021-03-25 16:42:37 -0400767 if depfile := buildStatement.Depfile; depfile != nil {
768 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
769 }
770
Liz Kammerc49e6822021-06-08 15:04:11 -0400771 for _, symlinkPath := range buildStatement.SymlinkPaths {
772 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
773 }
774
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500775 // This is required to silence warnings pertaining to unexpected timestamps. Particularly,
776 // some Bazel builtins (such as files in the bazel_tools directory) have far-future
777 // timestamps. Without restat, Ninja would emit warnings that the input files of a
778 // build statement have later timestamps than the outputs.
779 rule.Restat()
780
Liz Kammer13548d72020-12-16 11:13:30 -0800781 rule.Build(fmt.Sprintf("bazel %d", index), buildStatement.Mnemonic)
Chris Parsonsa798d962020-10-12 23:44:08 -0400782 }
783}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500784
785func getCqueryId(key cqueryKey) string {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200786 return key.label + "|" + getArchString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500787}
788
789func getArchString(key cqueryKey) string {
790 arch := key.archType.Name
791 if len(arch) > 0 {
792 return arch
793 } else {
794 return "x86_64"
795 }
796}