• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// 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"
21	"io/ioutil"
22	"os"
23	"os/exec"
24	"path/filepath"
25	"runtime"
26	"strings"
27	"sync"
28
29	"android/soong/bazel/cquery"
30	"android/soong/shared"
31
32	"android/soong/bazel"
33)
34
35type cqueryRequest interface {
36	// Name returns a string name for this request type. Such request type names must be unique,
37	// and must only consist of alphanumeric characters.
38	Name() string
39
40	// StarlarkFunctionBody returns a starlark function body to process this request type.
41	// The returned string is the body of a Starlark function which obtains
42	// all request-relevant information about a target and returns a string containing
43	// this information.
44	// The function should have the following properties:
45	//   - `target` is the only parameter to this function (a configured target).
46	//   - The return value must be a string.
47	//   - The function body should not be indented outside of its own scope.
48	StarlarkFunctionBody() string
49}
50
51// Portion of cquery map key to describe target configuration.
52type configKey struct {
53	arch   string
54	osType OsType
55}
56
57// Map key to describe bazel cquery requests.
58type cqueryKey struct {
59	label       string
60	requestType cqueryRequest
61	configKey   configKey
62}
63
64// bazelHandler is the interface for a helper object related to deferring to Bazel for
65// processing a module (during Bazel mixed builds). Individual module types should define
66// their own bazel handler if they support deferring to Bazel.
67type BazelHandler interface {
68	// Issue query to Bazel to retrieve information about Bazel's view of the current module.
69	// If Bazel returns this information, set module properties on the current module to reflect
70	// the returned information.
71	// Returns true if information was available from Bazel, false if bazel invocation still needs to occur.
72	GenerateBazelBuildActions(ctx ModuleContext, label string) bool
73}
74
75type BazelContext interface {
76	// The methods below involve queuing cquery requests to be later invoked
77	// by bazel. If any of these methods return (_, false), then the request
78	// has been queued to be run later.
79
80	// Returns result files built by building the given bazel target label.
81	GetOutputFiles(label string, cfgKey configKey) ([]string, bool)
82
83	// TODO(cparsons): Other cquery-related methods should be added here.
84	// Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
85	GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, bool, error)
86
87	// Returns the executable binary resultant from building together the python sources
88	GetPythonBinary(label string, cfgKey configKey) (string, bool)
89
90	// ** End cquery methods
91
92	// Issues commands to Bazel to receive results for all cquery requests
93	// queued in the BazelContext.
94	InvokeBazel() error
95
96	// Returns true if bazel is enabled for the given configuration.
97	BazelEnabled() bool
98
99	// Returns the bazel output base (the root directory for all bazel intermediate outputs).
100	OutputBase() string
101
102	// Returns build statements which should get registered to reflect Bazel's outputs.
103	BuildStatementsToRegister() []bazel.BuildStatement
104}
105
106type bazelRunner interface {
107	issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) (string, string, error)
108}
109
110type bazelPaths struct {
111	homeDir      string
112	bazelPath    string
113	outputBase   string
114	workspaceDir string
115	soongOutDir  string
116	metricsDir   string
117}
118
119// A context object which tracks queued requests that need to be made to Bazel,
120// and their results after the requests have been made.
121type bazelContext struct {
122	bazelRunner
123	paths        *bazelPaths
124	requests     map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
125	requestMutex sync.Mutex         // requests can be written in parallel
126
127	results map[cqueryKey]string // Results of cquery requests after Bazel invocations
128
129	// Build statements which should get registered to reflect Bazel's outputs.
130	buildStatements []bazel.BuildStatement
131}
132
133var _ BazelContext = &bazelContext{}
134
135// A bazel context to use when Bazel is disabled.
136type noopBazelContext struct{}
137
138var _ BazelContext = noopBazelContext{}
139
140// A bazel context to use for tests.
141type MockBazelContext struct {
142	OutputBaseDir string
143
144	LabelToOutputFiles  map[string][]string
145	LabelToCcInfo       map[string]cquery.CcInfo
146	LabelToPythonBinary map[string]string
147}
148
149func (m MockBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, bool) {
150	result, ok := m.LabelToOutputFiles[label]
151	return result, ok
152}
153
154func (m MockBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, bool, error) {
155	result, ok := m.LabelToCcInfo[label]
156	return result, ok, nil
157}
158
159func (m MockBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, bool) {
160	result, ok := m.LabelToPythonBinary[label]
161	return result, ok
162}
163
164func (m MockBazelContext) InvokeBazel() error {
165	panic("unimplemented")
166}
167
168func (m MockBazelContext) BazelEnabled() bool {
169	return true
170}
171
172func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
173
174func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
175	return []bazel.BuildStatement{}
176}
177
178var _ BazelContext = MockBazelContext{}
179
180func (bazelCtx *bazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, bool) {
181	rawString, ok := bazelCtx.cquery(label, cquery.GetOutputFiles, cfgKey)
182	var ret []string
183	if ok {
184		bazelOutput := strings.TrimSpace(rawString)
185		ret = cquery.GetOutputFiles.ParseResult(bazelOutput)
186	}
187	return ret, ok
188}
189
190func (bazelCtx *bazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, bool, error) {
191	result, ok := bazelCtx.cquery(label, cquery.GetCcInfo, cfgKey)
192	if !ok {
193		return cquery.CcInfo{}, ok, nil
194	}
195
196	bazelOutput := strings.TrimSpace(result)
197	ret, err := cquery.GetCcInfo.ParseResult(bazelOutput)
198	return ret, ok, err
199}
200
201func (bazelCtx *bazelContext) GetPythonBinary(label string, cfgKey configKey) (string, bool) {
202	rawString, ok := bazelCtx.cquery(label, cquery.GetPythonBinary, cfgKey)
203	var ret string
204	if ok {
205		bazelOutput := strings.TrimSpace(rawString)
206		ret = cquery.GetPythonBinary.ParseResult(bazelOutput)
207	}
208	return ret, ok
209}
210
211func (n noopBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, bool) {
212	panic("unimplemented")
213}
214
215func (n noopBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, bool, error) {
216	panic("unimplemented")
217}
218
219func (n noopBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, bool) {
220	panic("unimplemented")
221}
222
223func (n noopBazelContext) InvokeBazel() error {
224	panic("unimplemented")
225}
226
227func (m noopBazelContext) OutputBase() string {
228	return ""
229}
230
231func (n noopBazelContext) BazelEnabled() bool {
232	return false
233}
234
235func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
236	return []bazel.BuildStatement{}
237}
238
239func NewBazelContext(c *config) (BazelContext, error) {
240	// TODO(cparsons): Assess USE_BAZEL=1 instead once "mixed Soong/Bazel builds"
241	// are production ready.
242	if !c.IsEnvTrue("USE_BAZEL_ANALYSIS") {
243		return noopBazelContext{}, nil
244	}
245
246	p, err := bazelPathsFromConfig(c)
247	if err != nil {
248		return nil, err
249	}
250	return &bazelContext{
251		bazelRunner: &builtinBazelRunner{},
252		paths:       p,
253		requests:    make(map[cqueryKey]bool),
254	}, nil
255}
256
257func bazelPathsFromConfig(c *config) (*bazelPaths, error) {
258	p := bazelPaths{
259		soongOutDir: c.soongOutDir,
260	}
261	missingEnvVars := []string{}
262	if len(c.Getenv("BAZEL_HOME")) > 1 {
263		p.homeDir = c.Getenv("BAZEL_HOME")
264	} else {
265		missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
266	}
267	if len(c.Getenv("BAZEL_PATH")) > 1 {
268		p.bazelPath = c.Getenv("BAZEL_PATH")
269	} else {
270		missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
271	}
272	if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
273		p.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
274	} else {
275		missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
276	}
277	if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
278		p.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
279	} else {
280		missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
281	}
282	if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
283		p.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
284	} else {
285		missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
286	}
287	if len(missingEnvVars) > 0 {
288		return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
289	} else {
290		return &p, nil
291	}
292}
293
294func (p *bazelPaths) BazelMetricsDir() string {
295	return p.metricsDir
296}
297
298func (context *bazelContext) BazelEnabled() bool {
299	return true
300}
301
302// Adds a cquery request to the Bazel request queue, to be later invoked, or
303// returns the result of the given request if the request was already made.
304// If the given request was already made (and the results are available), then
305// returns (result, true). If the request is queued but no results are available,
306// then returns ("", false).
307func (context *bazelContext) cquery(label string, requestType cqueryRequest,
308	cfgKey configKey) (string, bool) {
309	key := cqueryKey{label, requestType, cfgKey}
310	if result, ok := context.results[key]; ok {
311		return result, true
312	} else {
313		context.requestMutex.Lock()
314		defer context.requestMutex.Unlock()
315		context.requests[key] = true
316		return "", false
317	}
318}
319
320func pwdPrefix() string {
321	// Darwin doesn't have /proc
322	if runtime.GOOS != "darwin" {
323		return "PWD=/proc/self/cwd"
324	}
325	return ""
326}
327
328type bazelCommand struct {
329	command string
330	// query or label
331	expression string
332}
333
334type mockBazelRunner struct {
335	bazelCommandResults map[bazelCommand]string
336	commands            []bazelCommand
337}
338
339func (r *mockBazelRunner) issueBazelCommand(paths *bazelPaths,
340	runName bazel.RunName,
341	command bazelCommand,
342	extraFlags ...string) (string, string, error) {
343	r.commands = append(r.commands, command)
344	if ret, ok := r.bazelCommandResults[command]; ok {
345		return ret, "", nil
346	}
347	return "", "", nil
348}
349
350type builtinBazelRunner struct{}
351
352// Issues the given bazel command with given build label and additional flags.
353// Returns (stdout, stderr, error). The first and second return values are strings
354// containing the stdout and stderr of the run command, and an error is returned if
355// the invocation returned an error code.
356func (r *builtinBazelRunner) issueBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
357	extraFlags ...string) (string, string, error) {
358	cmdFlags := []string{
359		// --noautodetect_server_javabase has the practical consequence of preventing Bazel from
360		// attempting to download rules_java, which is incompatible with
361		// --experimental_repository_disable_download set further below.
362		// rules_java is also not needed until mixed builds start building java targets.
363		// TODO(b/197958133): Once rules_java is pulled into AOSP, remove this flag.
364		"--noautodetect_server_javabase",
365		"--output_base=" + absolutePath(paths.outputBase),
366		command.command,
367	}
368	cmdFlags = append(cmdFlags, command.expression)
369	cmdFlags = append(cmdFlags, "--profile="+shared.BazelMetricsFilename(paths, runName))
370
371	// Set default platforms to canonicalized values for mixed builds requests.
372	// If these are set in the bazelrc, they will have values that are
373	// non-canonicalized to @sourceroot labels, and thus be invalid when
374	// referenced from the buildroot.
375	//
376	// The actual platform values here may be overridden by configuration
377	// transitions from the buildroot.
378	cmdFlags = append(cmdFlags,
379		fmt.Sprintf("--platforms=%s", "//build/bazel/platforms:android_target"))
380	cmdFlags = append(cmdFlags,
381		fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"))
382	// This should be parameterized on the host OS, but let's restrict to linux
383	// to keep things simple for now.
384	cmdFlags = append(cmdFlags,
385		fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"))
386
387	// Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
388	cmdFlags = append(cmdFlags, "--experimental_repository_disable_download")
389	cmdFlags = append(cmdFlags, extraFlags...)
390
391	bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
392	bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
393	bazelCmd.Env = append(os.Environ(),
394		"HOME="+paths.homeDir,
395		pwdPrefix(),
396		"BUILD_DIR="+absolutePath(paths.soongOutDir),
397		// Make OUT_DIR absolute here so tools/bazel.sh uses the correct
398		// OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
399		"OUT_DIR="+absolutePath(paths.outDir()),
400		// Disables local host detection of gcc; toolchain information is defined
401		// explicitly in BUILD files.
402		"BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1")
403	stderr := &bytes.Buffer{}
404	bazelCmd.Stderr = stderr
405
406	if output, err := bazelCmd.Output(); err != nil {
407		return "", string(stderr.Bytes()),
408			fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
409	} else {
410		return string(output), string(stderr.Bytes()), nil
411	}
412}
413
414func (context *bazelContext) mainBzlFileContents() []byte {
415	// TODO(cparsons): Define configuration transitions programmatically based
416	// on available archs.
417	contents := `
418#####################################################
419# This file is generated by soong_build. Do not edit.
420#####################################################
421
422def _config_node_transition_impl(settings, attr):
423    return {
424        "//command_line_option:platforms": "@//build/bazel/platforms:%s_%s" % (attr.os, attr.arch),
425    }
426
427_config_node_transition = transition(
428    implementation = _config_node_transition_impl,
429    inputs = [],
430    outputs = [
431        "//command_line_option:platforms",
432    ],
433)
434
435def _passthrough_rule_impl(ctx):
436    return [DefaultInfo(files = depset(ctx.files.deps))]
437
438config_node = rule(
439    implementation = _passthrough_rule_impl,
440    attrs = {
441        "arch" : attr.string(mandatory = True),
442        "os"   : attr.string(mandatory = True),
443        "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
444        "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
445    },
446)
447
448
449# Rule representing the root of the build, to depend on all Bazel targets that
450# are required for the build. Building this target will build the entire Bazel
451# build tree.
452mixed_build_root = rule(
453    implementation = _passthrough_rule_impl,
454    attrs = {
455        "deps" : attr.label_list(),
456    },
457)
458
459def _phony_root_impl(ctx):
460    return []
461
462# Rule to depend on other targets but build nothing.
463# This is useful as follows: building a target of this rule will generate
464# symlink forests for all dependencies of the target, without executing any
465# actions of the build.
466phony_root = rule(
467    implementation = _phony_root_impl,
468    attrs = {"deps" : attr.label_list()},
469)
470`
471	return []byte(contents)
472}
473
474func (context *bazelContext) mainBuildFileContents() []byte {
475	// TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
476	// architecture mapping.
477	formatString := `
478# This file is generated by soong_build. Do not edit.
479load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
480
481%s
482
483mixed_build_root(name = "buildroot",
484    deps = [%s],
485)
486
487phony_root(name = "phonyroot",
488    deps = [":buildroot"],
489)
490`
491	configNodeFormatString := `
492config_node(name = "%s",
493    arch = "%s",
494    os = "%s",
495    deps = [%s],
496)
497`
498
499	configNodesSection := ""
500
501	labelsByConfig := map[string][]string{}
502	for val, _ := range context.requests {
503		labelString := fmt.Sprintf("\"@%s\"", val.label)
504		configString := getConfigString(val)
505		labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
506	}
507
508	allLabels := []string{}
509	for configString, labels := range labelsByConfig {
510		configTokens := strings.Split(configString, "|")
511		if len(configTokens) != 2 {
512			panic(fmt.Errorf("Unexpected config string format: %s", configString))
513		}
514		archString := configTokens[0]
515		osString := configTokens[1]
516		targetString := fmt.Sprintf("%s_%s", osString, archString)
517		allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
518		labelsString := strings.Join(labels, ",\n            ")
519		configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
520	}
521
522	return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n            ")))
523}
524
525func indent(original string) string {
526	result := ""
527	for _, line := range strings.Split(original, "\n") {
528		result += "  " + line + "\n"
529	}
530	return result
531}
532
533// Returns the file contents of the buildroot.cquery file that should be used for the cquery
534// expression in order to obtain information about buildroot and its dependencies.
535// The contents of this file depend on the bazelContext's requests; requests are enumerated
536// and grouped by their request type. The data retrieved for each label depends on its
537// request type.
538func (context *bazelContext) cqueryStarlarkFileContents() []byte {
539	requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
540	for val, _ := range context.requests {
541		cqueryId := getCqueryId(val)
542		mapEntryString := fmt.Sprintf("%q : True", cqueryId)
543		requestTypeToCqueryIdEntries[val.requestType] =
544			append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
545	}
546	labelRegistrationMapSection := ""
547	functionDefSection := ""
548	mainSwitchSection := ""
549
550	mapDeclarationFormatString := `
551%s = {
552  %s
553}
554`
555	functionDefFormatString := `
556def %s(target):
557%s
558`
559	mainSwitchSectionFormatString := `
560  if id_string in %s:
561    return id_string + ">>" + %s(target)
562`
563
564	for requestType := range requestTypeToCqueryIdEntries {
565		labelMapName := requestType.Name() + "_Labels"
566		functionName := requestType.Name() + "_Fn"
567		labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
568			labelMapName,
569			strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n  "))
570		functionDefSection += fmt.Sprintf(functionDefFormatString,
571			functionName,
572			indent(requestType.StarlarkFunctionBody()))
573		mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
574			labelMapName, functionName)
575	}
576
577	formatString := `
578# This file is generated by soong_build. Do not edit.
579
580# Label Map Section
581%s
582
583# Function Def Section
584%s
585
586def get_arch(target):
587  # TODO(b/199363072): filegroups and file targets aren't associated with any
588  # specific platform architecture in mixed builds. This is consistent with how
589  # Soong treats filegroups, but it may not be the case with manually-written
590  # filegroup BUILD targets.
591  buildoptions = build_options(target)
592  if buildoptions == None:
593    # File targets do not have buildoptions. File targets aren't associated with
594    #  any specific platform architecture in mixed builds, so use the host.
595    return "x86_64|linux"
596  platforms = build_options(target)["//command_line_option:platforms"]
597  if len(platforms) != 1:
598    # An individual configured target should have only one platform architecture.
599    # Note that it's fine for there to be multiple architectures for the same label,
600    # but each is its own configured target.
601    fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
602  platform_name = build_options(target)["//command_line_option:platforms"][0].name
603  if platform_name == "host":
604    return "HOST"
605  elif platform_name.startswith("android_"):
606    return platform_name[len("android_"):] + "|" + platform_name[:len("android_")-1]
607  elif platform_name.startswith("linux_"):
608    return platform_name[len("linux_"):] + "|" + platform_name[:len("linux_")-1]
609  else:
610    fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
611    return "UNKNOWN"
612
613def format(target):
614  id_string = str(target.label) + "|" + get_arch(target)
615
616  # Main switch section
617  %s
618  # This target was not requested via cquery, and thus must be a dependency
619  # of a requested target.
620  return id_string + ">>NONE"
621`
622
623	return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
624		mainSwitchSection))
625}
626
627// Returns a path containing build-related metadata required for interfacing
628// with Bazel. Example: out/soong/bazel.
629func (p *bazelPaths) intermediatesDir() string {
630	return filepath.Join(p.soongOutDir, "bazel")
631}
632
633// Returns the path where the contents of the @soong_injection repository live.
634// It is used by Soong to tell Bazel things it cannot over the command line.
635func (p *bazelPaths) injectedFilesDir() string {
636	return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
637}
638
639// Returns the path of the synthetic Bazel workspace that contains a symlink
640// forest composed the whole source tree and BUILD files generated by bp2build.
641func (p *bazelPaths) syntheticWorkspaceDir() string {
642	return filepath.Join(p.soongOutDir, "workspace")
643}
644
645// Returns the path to the top level out dir ($OUT_DIR).
646func (p *bazelPaths) outDir() string {
647	return filepath.Dir(p.soongOutDir)
648}
649
650// Issues commands to Bazel to receive results for all cquery requests
651// queued in the BazelContext.
652func (context *bazelContext) InvokeBazel() error {
653	context.results = make(map[cqueryKey]string)
654
655	var cqueryOutput string
656	var cqueryErr string
657	var err error
658
659	soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
660	mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
661	if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
662		err = os.MkdirAll(mixedBuildsPath, 0777)
663	}
664	if err != nil {
665		return err
666	}
667	if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
668		err = os.MkdirAll(metricsDir, 0777)
669		if err != nil {
670			return err
671		}
672	}
673	err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666)
674	if err != nil {
675		return err
676	}
677
678	err = ioutil.WriteFile(
679		filepath.Join(mixedBuildsPath, "main.bzl"),
680		context.mainBzlFileContents(), 0666)
681	if err != nil {
682		return err
683	}
684
685	err = ioutil.WriteFile(
686		filepath.Join(mixedBuildsPath, "BUILD.bazel"),
687		context.mainBuildFileContents(), 0666)
688	if err != nil {
689		return err
690	}
691	cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
692	err = ioutil.WriteFile(
693		absolutePath(cqueryFileRelpath),
694		context.cqueryStarlarkFileContents(), 0666)
695	if err != nil {
696		return err
697	}
698
699	buildrootLabel := "@soong_injection//mixed_builds:buildroot"
700	cqueryOutput, cqueryErr, err = context.issueBazelCommand(
701		context.paths,
702		bazel.CqueryBuildRootRunName,
703		bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)},
704		"--output=starlark",
705		"--starlark:file="+absolutePath(cqueryFileRelpath))
706	err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"),
707		[]byte(cqueryOutput), 0666)
708	if err != nil {
709		return err
710	}
711
712	if err != nil {
713		return err
714	}
715
716	cqueryResults := map[string]string{}
717	for _, outputLine := range strings.Split(cqueryOutput, "\n") {
718		if strings.Contains(outputLine, ">>") {
719			splitLine := strings.SplitN(outputLine, ">>", 2)
720			cqueryResults[splitLine[0]] = splitLine[1]
721		}
722	}
723
724	for val := range context.requests {
725		if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
726			context.results[val] = cqueryResult
727		} else {
728			return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
729				getCqueryId(val), cqueryOutput, cqueryErr)
730		}
731	}
732
733	// Issue an aquery command to retrieve action information about the bazel build tree.
734	//
735	// TODO(cparsons): Use --target_pattern_file to avoid command line limits.
736	var aqueryOutput string
737	aqueryOutput, _, err = context.issueBazelCommand(
738		context.paths,
739		bazel.AqueryBuildRootRunName,
740		bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)},
741		// Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
742		// proto sources, which would add a number of unnecessary dependencies.
743		"--output=jsonproto")
744
745	if err != nil {
746		return err
747	}
748
749	context.buildStatements, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
750	if err != nil {
751		return err
752	}
753
754	// Issue a build command of the phony root to generate symlink forests for dependencies of the
755	// Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
756	// but some of symlinks may be required to resolve source dependencies of the build.
757	_, _, err = context.issueBazelCommand(
758		context.paths,
759		bazel.BazelBuildPhonyRootRunName,
760		bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"})
761
762	if err != nil {
763		return err
764	}
765
766	// Clear requests.
767	context.requests = map[cqueryKey]bool{}
768	return nil
769}
770
771func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
772	return context.buildStatements
773}
774
775func (context *bazelContext) OutputBase() string {
776	return context.paths.outputBase
777}
778
779// Singleton used for registering BUILD file ninja dependencies (needed
780// for correctness of builds which use Bazel.
781func BazelSingleton() Singleton {
782	return &bazelSingleton{}
783}
784
785type bazelSingleton struct{}
786
787func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
788	// bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
789	if !ctx.Config().BazelContext.BazelEnabled() {
790		return
791	}
792
793	// Add ninja file dependencies for files which all bazel invocations require.
794	bazelBuildList := absolutePath(filepath.Join(
795		filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
796	ctx.AddNinjaFileDeps(bazelBuildList)
797
798	data, err := ioutil.ReadFile(bazelBuildList)
799	if err != nil {
800		ctx.Errorf(err.Error())
801	}
802	files := strings.Split(strings.TrimSpace(string(data)), "\n")
803	for _, file := range files {
804		ctx.AddNinjaFileDeps(file)
805	}
806
807	// Register bazel-owned build statements (obtained from the aquery invocation).
808	for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
809		if len(buildStatement.Command) < 1 {
810			panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
811		}
812		rule := NewRuleBuilder(pctx, ctx)
813		cmd := rule.Command()
814
815		// cd into Bazel's execution root, which is the action cwd.
816		cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ &&", ctx.Config().BazelContext.OutputBase()))
817
818		// Remove old outputs, as some actions might not rerun if the outputs are detected.
819		if len(buildStatement.OutputPaths) > 0 {
820			cmd.Text("rm -f")
821			for _, outputPath := range buildStatement.OutputPaths {
822				cmd.Text(outputPath)
823			}
824			cmd.Text("&&")
825		}
826
827		for _, pair := range buildStatement.Env {
828			// Set per-action env variables, if any.
829			cmd.Flag(pair.Key + "=" + pair.Value)
830		}
831
832		// The actual Bazel action.
833		cmd.Text(" " + buildStatement.Command)
834
835		for _, outputPath := range buildStatement.OutputPaths {
836			cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
837		}
838		for _, inputPath := range buildStatement.InputPaths {
839			cmd.Implicit(PathForBazelOut(ctx, inputPath))
840		}
841
842		if depfile := buildStatement.Depfile; depfile != nil {
843			cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
844		}
845
846		for _, symlinkPath := range buildStatement.SymlinkPaths {
847			cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
848		}
849
850		// This is required to silence warnings pertaining to unexpected timestamps. Particularly,
851		// some Bazel builtins (such as files in the bazel_tools directory) have far-future
852		// timestamps. Without restat, Ninja would emit warnings that the input files of a
853		// build statement have later timestamps than the outputs.
854		rule.Restat()
855
856		rule.Build(fmt.Sprintf("bazel %d", index), buildStatement.Mnemonic)
857	}
858}
859
860func getCqueryId(key cqueryKey) string {
861	return key.label + "|" + getConfigString(key)
862}
863
864func getConfigString(key cqueryKey) string {
865	arch := key.configKey.arch
866	if len(arch) == 0 || arch == "common" {
867		// Use host platform, which is currently hardcoded to be x86_64.
868		arch = "x86_64"
869	}
870	os := key.configKey.osType.Name
871	if len(os) == 0 || os == "common_os" || os == "linux_glibc" {
872		// Use host OS, which is currently hardcoded to be linux.
873		os = "linux"
874	}
875	return arch + "|" + os
876}
877
878func GetConfigKey(ctx ModuleContext) configKey {
879	return configKey{
880		// use string because Arch is not a valid key in go
881		arch:   ctx.Arch().String(),
882		osType: ctx.Os(),
883	}
884}
885