blob: 415f00e8ec11057b2c408fa3c72a256f3b117d5f [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 Parsonsdbcb1ff2020-12-10 17:19:18 -050029 "github.com/google/blueprint/bootstrap"
30
Patrice Arruda05ab2d02020-12-12 06:24:26 +000031 "android/soong/bazel"
32 "android/soong/shared"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040033)
34
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040035type CqueryRequestType int
36
37const (
38 getAllFiles CqueryRequestType = iota
Chris Parsons8d6e4332021-02-22 16:13:50 -050039 getCcObjectFiles
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040040)
41
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040042// Map key to describe bazel cquery requests.
43type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040044 label string
45 requestType CqueryRequestType
Chris Parsons8d6e4332021-02-22 16:13:50 -050046 archType ArchType
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040047}
48
49type BazelContext interface {
50 // The below methods involve queuing cquery requests to be later invoked
51 // by bazel. If any of these methods return (_, false), then the request
52 // has been queued to be run later.
53
54 // Returns result files built by building the given bazel target label.
Chris Parsons8d6e4332021-02-22 16:13:50 -050055 GetAllFiles(label string, archType ArchType) ([]string, bool)
56
57 // Returns object files produced by compiling the given cc-related target.
58 // Retrieves these files from Bazel's CcInfo provider.
59 GetCcObjectFiles(label string, archType ArchType) ([]string, bool)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040060
61 // TODO(cparsons): Other cquery-related methods should be added here.
62 // ** End cquery methods
63
64 // Issues commands to Bazel to receive results for all cquery requests
65 // queued in the BazelContext.
66 InvokeBazel() error
67
68 // Returns true if bazel is enabled for the given configuration.
69 BazelEnabled() bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050070
71 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
72 OutputBase() string
73
74 // Returns build statements which should get registered to reflect Bazel's outputs.
75 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040076}
77
78// A context object which tracks queued requests that need to be made to Bazel,
79// and their results after the requests have been made.
80type bazelContext struct {
81 homeDir string
82 bazelPath string
83 outputBase string
84 workspaceDir string
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040085 buildDir string
Patrice Arruda05ab2d02020-12-12 06:24:26 +000086 metricsDir string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040087
88 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
89 requestMutex sync.Mutex // requests can be written in parallel
90
91 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -050092
93 // Build statements which should get registered to reflect Bazel's outputs.
94 buildStatements []bazel.BuildStatement
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040095}
96
97var _ BazelContext = &bazelContext{}
98
99// A bazel context to use when Bazel is disabled.
100type noopBazelContext struct{}
101
102var _ BazelContext = noopBazelContext{}
103
104// A bazel context to use for tests.
105type MockBazelContext struct {
106 AllFiles map[string][]string
107}
108
Chris Parsons8d6e4332021-02-22 16:13:50 -0500109func (m MockBazelContext) GetAllFiles(label string, archType ArchType) ([]string, bool) {
110 result, ok := m.AllFiles[label]
111 return result, ok
112}
113
114func (m MockBazelContext) GetCcObjectFiles(label string, archType ArchType) ([]string, bool) {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400115 result, ok := m.AllFiles[label]
116 return result, ok
117}
118
119func (m MockBazelContext) InvokeBazel() error {
120 panic("unimplemented")
121}
122
123func (m MockBazelContext) BazelEnabled() bool {
124 return true
125}
126
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500127func (m MockBazelContext) OutputBase() string {
128 return "outputbase"
129}
130
131func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
132 return []bazel.BuildStatement{}
133}
134
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400135var _ BazelContext = MockBazelContext{}
136
Chris Parsons8d6e4332021-02-22 16:13:50 -0500137func (bazelCtx *bazelContext) GetAllFiles(label string, archType ArchType) ([]string, bool) {
138 result, ok := bazelCtx.cquery(label, getAllFiles, archType)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400139 if ok {
140 bazelOutput := strings.TrimSpace(result)
141 return strings.Split(bazelOutput, ", "), true
142 } else {
143 return nil, false
144 }
145}
146
Chris Parsons8d6e4332021-02-22 16:13:50 -0500147func (bazelCtx *bazelContext) GetCcObjectFiles(label string, archType ArchType) ([]string, bool) {
148 result, ok := bazelCtx.cquery(label, getCcObjectFiles, archType)
149 if ok {
150 bazelOutput := strings.TrimSpace(result)
151 return strings.Split(bazelOutput, ", "), true
152 } else {
153 return nil, false
154 }
155}
156
157func (n noopBazelContext) GetAllFiles(label string, archType ArchType) ([]string, bool) {
158 panic("unimplemented")
159}
160
161func (n noopBazelContext) GetCcObjectFiles(label string, archType ArchType) ([]string, bool) {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400162 panic("unimplemented")
163}
164
165func (n noopBazelContext) InvokeBazel() error {
166 panic("unimplemented")
167}
168
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500169func (m noopBazelContext) OutputBase() string {
170 return ""
171}
172
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400173func (n noopBazelContext) BazelEnabled() bool {
174 return false
175}
176
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500177func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
178 return []bazel.BuildStatement{}
179}
180
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400181func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons8b77a002020-10-27 18:59:25 -0400182 // TODO(cparsons): Assess USE_BAZEL=1 instead once "mixed Soong/Bazel builds"
183 // are production ready.
184 if c.Getenv("USE_BAZEL_ANALYSIS") != "1" {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400185 return noopBazelContext{}, nil
186 }
187
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400188 bazelCtx := bazelContext{buildDir: c.buildDir, requests: make(map[cqueryKey]bool)}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400189 missingEnvVars := []string{}
190 if len(c.Getenv("BAZEL_HOME")) > 1 {
191 bazelCtx.homeDir = c.Getenv("BAZEL_HOME")
192 } else {
193 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
194 }
195 if len(c.Getenv("BAZEL_PATH")) > 1 {
196 bazelCtx.bazelPath = c.Getenv("BAZEL_PATH")
197 } else {
198 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
199 }
200 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
201 bazelCtx.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
202 } else {
203 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
204 }
205 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
206 bazelCtx.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
207 } else {
208 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
209 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000210 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
211 bazelCtx.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
212 } else {
213 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
214 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400215 if len(missingEnvVars) > 0 {
216 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
217 } else {
218 return &bazelCtx, nil
219 }
220}
221
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000222func (context *bazelContext) BazelMetricsDir() string {
223 return context.metricsDir
224}
225
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400226func (context *bazelContext) BazelEnabled() bool {
227 return true
228}
229
230// Adds a cquery request to the Bazel request queue, to be later invoked, or
231// returns the result of the given request if the request was already made.
232// If the given request was already made (and the results are available), then
233// returns (result, true). If the request is queued but no results are available,
234// then returns ("", false).
Chris Parsons8d6e4332021-02-22 16:13:50 -0500235func (context *bazelContext) cquery(label string, requestType CqueryRequestType,
236 archType ArchType) (string, bool) {
237 key := cqueryKey{label, requestType, archType}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400238 if result, ok := context.results[key]; ok {
239 return result, true
240 } else {
241 context.requestMutex.Lock()
242 defer context.requestMutex.Unlock()
243 context.requests[key] = true
244 return "", false
245 }
246}
247
248func pwdPrefix() string {
249 // Darwin doesn't have /proc
250 if runtime.GOOS != "darwin" {
251 return "PWD=/proc/self/cwd"
252 }
253 return ""
254}
255
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000256func (context *bazelContext) issueBazelCommand(runName bazel.RunName, command string, labels []string,
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400257 extraFlags ...string) (string, error) {
258
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500259 cmdFlags := []string{"--output_base=" + context.outputBase, command}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400260 cmdFlags = append(cmdFlags, labels...)
Chris Parsons8ccdb632020-11-17 15:41:01 -0500261 cmdFlags = append(cmdFlags, "--package_path=%workspace%/"+context.intermediatesDir())
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000262 cmdFlags = append(cmdFlags, "--profile="+shared.BazelMetricsFilename(context, runName))
Chris Parsonsee423b02021-02-08 23:04:59 -0500263 // Set default platforms to canonicalized values for mixed builds requests. If these are set
264 // in the bazelrc, they will have values that are non-canonicalized, and thus be invalid.
265 // The actual platform values here may be overridden by configuration transitions from the buildroot.
266 cmdFlags = append(cmdFlags,
267 fmt.Sprintf("--platforms=%s", canonicalizeLabel("//build/bazel/platforms:generic_x86_64")))
268 cmdFlags = append(cmdFlags,
269 fmt.Sprintf("--extra_toolchains=%s", canonicalizeLabel("//prebuilts/clang/host/linux-x86:all")))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500270 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
271 cmdFlags = append(cmdFlags, "--experimental_repository_disable_download")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400272 cmdFlags = append(cmdFlags, extraFlags...)
273
274 bazelCmd := exec.Command(context.bazelPath, cmdFlags...)
275 bazelCmd.Dir = context.workspaceDir
Chris Parsons8d6e4332021-02-22 16:13:50 -0500276 bazelCmd.Env = append(os.Environ(), "HOME="+context.homeDir, pwdPrefix(),
277 // Disables local host detection of gcc; toolchain information is defined
278 // explicitly in BUILD files.
279 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
Colin Crossff0278b2020-10-09 19:24:15 -0700280 stderr := &bytes.Buffer{}
281 bazelCmd.Stderr = stderr
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400282
283 if output, err := bazelCmd.Output(); err != nil {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500284 return "", fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400285 } else {
286 return string(output), nil
287 }
288}
289
Chris Parsons8ccdb632020-11-17 15:41:01 -0500290// Returns the string contents of a workspace file that should be output
291// adjacent to the main bzl file and build file.
292// This workspace file allows, via local_repository rule, sourcetree-level
293// BUILD targets to be referenced via @sourceroot.
294func (context *bazelContext) workspaceFileContents() []byte {
295 formatString := `
296# This file is generated by soong_build. Do not edit.
297local_repository(
298 name = "sourceroot",
299 path = "%s",
300)
301`
302 return []byte(fmt.Sprintf(formatString, context.workspaceDir))
303}
304
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400305func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500306 // TODO(cparsons): Define configuration transitions programmatically based
307 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400308 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500309#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400310# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500311#####################################################
312
Chris Parsons8d6e4332021-02-22 16:13:50 -0500313def _x86_64_transition_impl(settings, attr):
314 return {
315 "//command_line_option:platforms": "@sourceroot//build/bazel/platforms:generic_x86_64",
316 }
317
318def _x86_transition_impl(settings, attr):
319 return {
320 "//command_line_option:platforms": "@sourceroot//build/bazel/platforms:generic_x86",
321 }
322
323def _arm64_transition_impl(settings, attr):
324 return {
325 "//command_line_option:platforms": "@sourceroot//build/bazel/platforms:generic_arm64",
326 }
327
328def _arm_transition_impl(settings, attr):
329 return {
330 "//command_line_option:platforms": "@sourceroot//build/bazel/platforms:generic_arm",
331 }
332
333x86_64_transition = transition(
334 implementation = _x86_64_transition_impl,
335 inputs = [],
336 outputs = [
337 "//command_line_option:platforms",
338 ],
339)
340
341x86_transition = transition(
342 implementation = _x86_transition_impl,
343 inputs = [],
344 outputs = [
345 "//command_line_option:platforms",
346 ],
347)
348
349arm64_transition = transition(
350 implementation = _arm64_transition_impl,
351 inputs = [],
352 outputs = [
353 "//command_line_option:platforms",
354 ],
355)
356
357arm_transition = transition(
358 implementation = _arm_transition_impl,
359 inputs = [],
360 outputs = [
361 "//command_line_option:platforms",
362 ],
363)
364
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400365def _mixed_build_root_impl(ctx):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500366 all_files = ctx.files.deps_x86_64 + ctx.files.deps_x86 + ctx.files.deps_arm64 + ctx.files.deps_arm
367 return [DefaultInfo(files = depset(all_files))]
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400368
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500369# Rule representing the root of the build, to depend on all Bazel targets that
370# are required for the build. Building this target will build the entire Bazel
371# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400372mixed_build_root = rule(
373 implementation = _mixed_build_root_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500374 attrs = {
375 "deps_x86_64" : attr.label_list(cfg = x86_64_transition),
376 "deps_x86" : attr.label_list(cfg = x86_transition),
377 "deps_arm64" : attr.label_list(cfg = arm64_transition),
378 "deps_arm" : attr.label_list(cfg = arm_transition),
379 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
380 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400381)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500382
383def _phony_root_impl(ctx):
384 return []
385
386# Rule to depend on other targets but build nothing.
387# This is useful as follows: building a target of this rule will generate
388# symlink forests for all dependencies of the target, without executing any
389# actions of the build.
390phony_root = rule(
391 implementation = _phony_root_impl,
392 attrs = {"deps" : attr.label_list()},
393)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400394`
395 return []byte(contents)
396}
397
Chris Parsons8ccdb632020-11-17 15:41:01 -0500398// Returns a "canonicalized" corresponding to the given sourcetree-level label.
399// This abstraction is required because a sourcetree label such as //foo/bar:baz
400// must be referenced via the local repository prefix, such as
401// @sourceroot//foo/bar:baz.
402func canonicalizeLabel(label string) string {
403 if strings.HasPrefix(label, "//") {
404 return "@sourceroot" + label
405 } else {
406 return "@sourceroot//" + label
407 }
408}
409
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400410func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500411 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
412 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400413 formatString := `
414# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500415load(":main.bzl", "mixed_build_root", "phony_root")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400416
417mixed_build_root(name = "buildroot",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500418 deps_x86_64 = [%s],
419 deps_x86 = [%s],
420 deps_arm64 = [%s],
421 deps_arm = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400422)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500423
424phony_root(name = "phonyroot",
425 deps = [":buildroot"],
426)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400427`
Chris Parsons8d6e4332021-02-22 16:13:50 -0500428 var deps_x86_64 []string = nil
429 var deps_x86 []string = nil
430 var deps_arm64 []string = nil
431 var deps_arm []string = nil
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400432 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500433 labelString := fmt.Sprintf("\"%s\"", canonicalizeLabel(val.label))
434 switch getArchString(val) {
435 case "x86_64":
436 deps_x86_64 = append(deps_x86_64, labelString)
437 case "x86":
438 deps_x86 = append(deps_x86, labelString)
439 case "arm64":
440 deps_arm64 = append(deps_arm64, labelString)
441 case "arm":
442 deps_arm = append(deps_arm, labelString)
443 default:
444 panic(fmt.Sprintf("unhandled architecture %s for %s", getArchString(val), val))
445 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400446 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400447
Chris Parsons8d6e4332021-02-22 16:13:50 -0500448 return []byte(fmt.Sprintf(formatString,
449 strings.Join(deps_x86_64, ",\n "),
450 strings.Join(deps_x86, ",\n "),
451 strings.Join(deps_arm64, ",\n "),
452 strings.Join(deps_arm, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400453}
454
455func (context *bazelContext) cqueryStarlarkFileContents() []byte {
456 formatString := `
457# This file is generated by soong_build. Do not edit.
458getAllFilesLabels = {
459 %s
460}
461
Chris Parsons8d6e4332021-02-22 16:13:50 -0500462getCcObjectFilesLabels = {
463 %s
464}
465
466def get_cc_object_files(target):
467 result = []
468 linker_inputs = providers(target)["CcInfo"].linking_context.linker_inputs.to_list()
469
470 for linker_input in linker_inputs:
471 for library in linker_input.libraries:
472 for object in library.objects:
473 result += [object.path]
474 return result
475
476def get_arch(target):
477 buildoptions = build_options(target)
478 platforms = build_options(target)["//command_line_option:platforms"]
479 if len(platforms) != 1:
480 # An individual configured target should have only one platform architecture.
481 # Note that it's fine for there to be multiple architectures for the same label,
482 # but each is its own configured target.
483 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
484 platform_name = build_options(target)["//command_line_option:platforms"][0].name
485 if platform_name == "host":
486 return "HOST"
487 elif not platform_name.startswith("generic_"):
488 fail("expected platform name of the form 'generic_<arch>', but was " + str(platforms))
489 return "UNKNOWN"
490 return platform_name[len("generic_"):]
491
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400492def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500493 id_string = str(target.label) + "|" + get_arch(target)
494 if id_string in getAllFilesLabels:
495 return id_string + ">>" + ', '.join([f.path for f in target.files.to_list()])
496 elif id_string in getCcObjectFilesLabels:
497 return id_string + ">>" + ', '.join(get_cc_object_files(target))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400498 else:
499 # This target was not requested via cquery, and thus must be a dependency
500 # of a requested target.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500501 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400502`
Chris Parsons8d6e4332021-02-22 16:13:50 -0500503 var getAllFilesDeps []string = nil
504 var getCcObjectFilesDeps []string = nil
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400505
Chris Parsons8d6e4332021-02-22 16:13:50 -0500506 for val, _ := range context.requests {
507 labelWithArch := getCqueryId(val)
508 mapEntryString := fmt.Sprintf("%q : True", labelWithArch)
509 switch val.requestType {
510 case getAllFiles:
511 getAllFilesDeps = append(getAllFilesDeps, mapEntryString)
512 case getCcObjectFiles:
513 getCcObjectFilesDeps = append(getCcObjectFilesDeps, mapEntryString)
514 }
515 }
516 getAllFilesDepsString := strings.Join(getAllFilesDeps, ",\n ")
517 getCcObjectFilesDepsString := strings.Join(getCcObjectFilesDeps, ",\n ")
518
519 return []byte(fmt.Sprintf(formatString, getAllFilesDepsString, getCcObjectFilesDepsString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400520}
521
Chris Parsons8ccdb632020-11-17 15:41:01 -0500522// Returns a workspace-relative path containing build-related metadata required
523// for interfacing with Bazel. Example: out/soong/bazel.
524func (context *bazelContext) intermediatesDir() string {
525 return filepath.Join(context.buildDir, "bazel")
526}
527
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400528// Issues commands to Bazel to receive results for all cquery requests
529// queued in the BazelContext.
530func (context *bazelContext) InvokeBazel() error {
531 context.results = make(map[cqueryKey]string)
532
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400533 var cqueryOutput string
534 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500535
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500536 intermediatesDirPath := absolutePath(context.intermediatesDir())
537 if _, err := os.Stat(intermediatesDirPath); os.IsNotExist(err) {
538 err = os.Mkdir(intermediatesDirPath, 0777)
539 }
540
Chris Parsons8ccdb632020-11-17 15:41:01 -0500541 if err != nil {
542 return err
543 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400544 err = ioutil.WriteFile(
Chris Parsons8ccdb632020-11-17 15:41:01 -0500545 absolutePath(filepath.Join(context.intermediatesDir(), "main.bzl")),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400546 context.mainBzlFileContents(), 0666)
547 if err != nil {
548 return err
549 }
550 err = ioutil.WriteFile(
Chris Parsons8ccdb632020-11-17 15:41:01 -0500551 absolutePath(filepath.Join(context.intermediatesDir(), "BUILD.bazel")),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400552 context.mainBuildFileContents(), 0666)
553 if err != nil {
554 return err
555 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800556 cqueryFileRelpath := filepath.Join(context.intermediatesDir(), "buildroot.cquery")
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400557 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800558 absolutePath(cqueryFileRelpath),
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400559 context.cqueryStarlarkFileContents(), 0666)
560 if err != nil {
561 return err
562 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800563 workspaceFileRelpath := filepath.Join(context.intermediatesDir(), "WORKSPACE.bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500564 err = ioutil.WriteFile(
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800565 absolutePath(workspaceFileRelpath),
Chris Parsons8ccdb632020-11-17 15:41:01 -0500566 context.workspaceFileContents(), 0666)
567 if err != nil {
568 return err
569 }
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800570 buildrootLabel := "//:buildroot"
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000571 cqueryOutput, err = context.issueBazelCommand(bazel.CqueryBuildRootRunName, "cquery",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500572 []string{fmt.Sprintf("kind(rule, deps(%s))", buildrootLabel)},
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400573 "--output=starlark",
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800574 "--starlark:file="+cqueryFileRelpath)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500575 err = ioutil.WriteFile(
576 absolutePath(filepath.Join(context.intermediatesDir(), "cquery.out")),
577 []byte(cqueryOutput), 0666)
578 if err != nil {
579 return err
580 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400581
582 if err != nil {
583 return err
584 }
585
586 cqueryResults := map[string]string{}
587 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
588 if strings.Contains(outputLine, ">>") {
589 splitLine := strings.SplitN(outputLine, ">>", 2)
590 cqueryResults[splitLine[0]] = splitLine[1]
591 }
592 }
593
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400594 for val, _ := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500595 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400596 context.results[val] = string(cqueryResult)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400597 } else {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500598 return fmt.Errorf("missing result for bazel target %s. query output: [%s]", getCqueryId(val), cqueryOutput)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400599 }
600 }
601
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500602 // Issue an aquery command to retrieve action information about the bazel build tree.
603 //
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400604 // TODO(cparsons): Use --target_pattern_file to avoid command line limits.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500605 var aqueryOutput string
606 aqueryOutput, err = context.issueBazelCommand(bazel.AqueryBuildRootRunName, "aquery",
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800607 []string{fmt.Sprintf("deps(%s)", buildrootLabel),
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500608 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
609 // proto sources, which would add a number of unnecessary dependencies.
610 "--output=jsonproto"})
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400611
612 if err != nil {
613 return err
614 }
615
Chris Parsons4f069892021-01-15 12:22:41 -0500616 context.buildStatements, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
617 if err != nil {
618 return err
619 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500620
621 // Issue a build command of the phony root to generate symlink forests for dependencies of the
622 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
623 // but some of symlinks may be required to resolve source dependencies of the build.
624 _, err = context.issueBazelCommand(bazel.BazelBuildPhonyRootRunName, "build",
625 []string{"//:phonyroot"})
626
627 if err != nil {
628 return err
629 }
630
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400631 // Clear requests.
632 context.requests = map[cqueryKey]bool{}
633 return nil
634}
Chris Parsonsa798d962020-10-12 23:44:08 -0400635
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500636func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
637 return context.buildStatements
638}
639
640func (context *bazelContext) OutputBase() string {
641 return context.outputBase
642}
643
Chris Parsonsa798d962020-10-12 23:44:08 -0400644// Singleton used for registering BUILD file ninja dependencies (needed
645// for correctness of builds which use Bazel.
646func BazelSingleton() Singleton {
647 return &bazelSingleton{}
648}
649
650type bazelSingleton struct{}
651
652func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500653 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
654 if !ctx.Config().BazelContext.BazelEnabled() {
655 return
656 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400657
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500658 // Add ninja file dependencies for files which all bazel invocations require.
659 bazelBuildList := absolutePath(filepath.Join(
660 filepath.Dir(bootstrap.ModuleListFile), "bazel.list"))
661 ctx.AddNinjaFileDeps(bazelBuildList)
662
663 data, err := ioutil.ReadFile(bazelBuildList)
664 if err != nil {
665 ctx.Errorf(err.Error())
666 }
667 files := strings.Split(strings.TrimSpace(string(data)), "\n")
668 for _, file := range files {
669 ctx.AddNinjaFileDeps(file)
670 }
671
672 // Register bazel-owned build statements (obtained from the aquery invocation).
673 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500674 if len(buildStatement.Command) < 1 {
675 panic(fmt.Sprintf("unhandled build statement: %s", buildStatement))
676 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500677 rule := NewRuleBuilder(pctx, ctx)
678 cmd := rule.Command()
679 cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ && %s",
680 ctx.Config().BazelContext.OutputBase(), buildStatement.Command))
681
682 for _, outputPath := range buildStatement.OutputPaths {
683 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400684 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500685 for _, inputPath := range buildStatement.InputPaths {
686 cmd.Implicit(PathForBazelOut(ctx, inputPath))
Chris Parsonsa798d962020-10-12 23:44:08 -0400687 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500688
689 // This is required to silence warnings pertaining to unexpected timestamps. Particularly,
690 // some Bazel builtins (such as files in the bazel_tools directory) have far-future
691 // timestamps. Without restat, Ninja would emit warnings that the input files of a
692 // build statement have later timestamps than the outputs.
693 rule.Restat()
694
Liz Kammer13548d72020-12-16 11:13:30 -0800695 rule.Build(fmt.Sprintf("bazel %d", index), buildStatement.Mnemonic)
Chris Parsonsa798d962020-10-12 23:44:08 -0400696 }
697}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500698
699func getCqueryId(key cqueryKey) string {
700 return canonicalizeLabel(key.label) + "|" + getArchString(key)
701}
702
703func getArchString(key cqueryKey) string {
704 arch := key.archType.Name
705 if len(arch) > 0 {
706 return arch
707 } else {
708 return "x86_64"
709 }
710}