blob: 9674ba25d3d05f723f4254afe0fdd7de4ffede35 [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"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040019 "fmt"
20 "os"
21 "os/exec"
Usta Shresthaacd5a0c2022-06-22 11:20:50 -040022 "path"
Chris Parsonsa798d962020-10-12 23:44:08 -040023 "path/filepath"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040024 "runtime"
Cole Faust705968d2022-12-14 11:32:05 -080025 "sort"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040026 "strings"
27 "sync"
Chris Parsonsa798d962020-10-12 23:44:08 -040028
Chris Parsonsad876012022-08-20 14:48:32 -040029 "android/soong/android/allowlists"
Chris Parsons944e7d02021-03-11 11:08:46 -050030 "android/soong/bazel/cquery"
Jingwen Chen1e347862021-09-02 12:11:49 +000031 "android/soong/shared"
Sam Delmericocb3c52c2023-02-03 17:40:08 -050032 "android/soong/starlark_fmt"
Liz Kammer337e9032022-08-03 15:49:43 -040033
Chris Parsons1a7aca02022-04-25 22:35:15 -040034 "github.com/google/blueprint"
Liz Kammer690fbac2023-02-10 11:11:17 -050035 "github.com/google/blueprint/metrics"
Liz Kammer8206d4f2021-03-03 16:40:52 -050036
Patrice Arruda05ab2d02020-12-12 06:24:26 +000037 "android/soong/bazel"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040038)
39
Sasha Smundak1da064c2022-06-08 16:36:16 -070040var (
Sasha Smundakc180dbd2022-07-03 14:55:58 -070041 _ = pctx.HostBinToolVariable("bazelBuildRunfilesTool", "build-runfiles")
42 buildRunfilesRule = pctx.AndroidStaticRule("bazelBuildRunfiles", blueprint.RuleParams{
43 Command: "${bazelBuildRunfilesTool} ${in} ${outDir}",
44 Depfile: "",
45 Description: "",
46 CommandDeps: []string{"${bazelBuildRunfilesTool}"},
47 }, "outDir")
Sam Delmericocb3c52c2023-02-03 17:40:08 -050048 allowedBazelEnvironmentVars = []string{
49 "ALLOW_LOCAL_TIDY_TRUE",
50 "DEFAULT_TIDY_HEADER_DIRS",
51 "TIDY_TIMEOUT",
52 "WITH_TIDY",
53 "WITH_TIDY_FLAGS",
54 "SKIP_ABI_CHECKS",
55 "UNSAFE_DISABLE_APEX_ALLOWED_DEPS_CHECK",
56 "AUTO_ZERO_INITIALIZE",
57 "AUTO_PATTERN_INITIALIZE",
58 "AUTO_UNINITIALIZE",
59 "USE_CCACHE",
60 "LLVM_NEXT",
61 "ALLOW_UNKNOWN_WARNING_OPTION",
62
63 // Overrides the version in the apex_manifest.json. The version is unique for
64 // each branch (internal, aosp, mainline releases, dessert releases). This
65 // enables modules built on an older branch to be installed against a newer
66 // device for development purposes.
67 "OVERRIDE_APEX_MANIFEST_DEFAULT_VERSION",
68 }
Sasha Smundak1da064c2022-06-08 16:36:16 -070069)
70
Chris Parsonsf874e462022-05-10 13:50:12 -040071func init() {
72 RegisterMixedBuildsMutator(InitRegistrationContext)
73}
74
75func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammer337e9032022-08-03 15:49:43 -040076 ctx.FinalDepsMutators(func(ctx RegisterMutatorsContext) {
Chris Parsonsf874e462022-05-10 13:50:12 -040077 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
78 })
79}
80
81func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
82 if m := ctx.Module(); m.Enabled() {
83 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
84 if mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx) {
85 mixedBuildMod.QueueBazelCall(ctx)
86 }
87 }
88 }
89}
90
Liz Kammerf29df7c2021-04-02 13:37:39 -040091type cqueryRequest interface {
92 // Name returns a string name for this request type. Such request type names must be unique,
93 // and must only consist of alphanumeric characters.
94 Name() string
95
96 // StarlarkFunctionBody returns a starlark function body to process this request type.
97 // The returned string is the body of a Starlark function which obtains
98 // all request-relevant information about a target and returns a string containing
99 // this information.
100 // The function should have the following properties:
Cole Faust97d15272022-11-22 14:08:59 -0800101 // - The arguments are `target` (a configured target) and `id_string` (the label + configuration).
Liz Kammerf29df7c2021-04-02 13:37:39 -0400102 // - The return value must be a string.
103 // - The function body should not be indented outside of its own scope.
104 StarlarkFunctionBody() string
105}
106
Chris Parsons787fb362021-10-14 18:43:51 -0400107// Portion of cquery map key to describe target configuration.
108type configKey struct {
Liz Kammer0940b892022-03-18 15:55:04 -0400109 arch string
110 osType OsType
Chris Parsons787fb362021-10-14 18:43:51 -0400111}
112
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700113func (c configKey) String() string {
114 return fmt.Sprintf("%s::%s", c.arch, c.osType)
115}
116
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400117// Map key to describe bazel cquery requests.
118type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400119 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400120 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400121 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400122}
123
Chris Parsons86dc2c22022-09-28 14:58:41 -0400124func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
125 if strings.HasPrefix(label, "//") {
126 // Normalize Bazel labels to specify main repository explicitly.
127 label = "@" + label
128 }
129 return cqueryKey{label, cqueryRequest, cfgKey}
130}
131
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700132func (c cqueryKey) String() string {
133 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700134}
135
Liz Kammer690fbac2023-02-10 11:11:17 -0500136type invokeBazelContext interface {
137 GetEventHandler() *metrics.EventHandler
138}
139
Chris Parsonsf874e462022-05-10 13:50:12 -0400140// BazelContext is a context object useful for interacting with Bazel during
141// the course of a build. Use of Bazel to evaluate part of the build graph
142// is referred to as a "mixed build". (Some modules are managed by Soong,
143// some are managed by Bazel). To facilitate interop between these build
144// subgraphs, Soong may make requests to Bazel and evaluate their responses
145// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400146type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400147 // Add a cquery request to the bazel request queue. All queued requests
148 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
149 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
150
151 // ** Cquery Results Retrieval Functions
152 // The below functions pertain to retrieving cquery results from a prior
153 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400154
155 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400156 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500157
Chris Parsons944e7d02021-03-11 11:08:46 -0500158 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400159 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400160
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000161 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400162 // TODO(b/232976601): Remove.
163 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000164
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700165 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400166 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700167
Sasha Smundakedd16662022-10-07 14:44:50 -0700168 // Returns the results of the GetCcUnstrippedInfo query
169 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
170
Chris Parsonsf874e462022-05-10 13:50:12 -0400171 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400172
173 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800174 // queued in the BazelContext. The ctx argument is optional and is only
175 // used for performance data collection
Liz Kammer690fbac2023-02-10 11:11:17 -0500176 InvokeBazel(config Config, ctx invokeBazelContext) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400177
Chris Parsonsad876012022-08-20 14:48:32 -0400178 // Returns true if Bazel handling is enabled for the module with the given name.
179 // Note that this only implies "bazel mixed build" allowlisting. The caller
180 // should independently verify the module is eligible for Bazel handling
181 // (for example, that it is MixedBuildBuildable).
Sasha Smundak39a301c2022-12-29 17:11:49 -0800182 IsModuleNameAllowed(moduleName string) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500183
184 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
185 OutputBase() string
186
187 // Returns build statements which should get registered to reflect Bazel's outputs.
188 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400189
190 // Returns the depsets defined in Bazel's aquery response.
191 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400192}
193
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400194type bazelRunner interface {
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500195 createBazelCommand(config Config, paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) *exec.Cmd
Liz Kammer690fbac2023-02-10 11:11:17 -0500196 issueBazelCommand(bazelCmd *exec.Cmd, eventHandler *metrics.EventHandler) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400197}
198
199type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000200 homeDir string
201 bazelPath string
202 outputBase string
203 workspaceDir string
204 soongOutDir string
205 metricsDir string
206 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400207}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400208
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400209// A context object which tracks queued requests that need to be made to Bazel,
210// and their results after the requests have been made.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800211type mixedBuildBazelContext struct {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400212 bazelRunner
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500213 paths *bazelPaths
214 // cquery requests that have not yet been issued to Bazel. This list is maintained
215 // in a sorted state, and is guaranteed to have no duplicates.
216 requests []cqueryKey
217 requestMutex sync.Mutex // requests can be written in parallel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400218
219 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500220
221 // Build statements which should get registered to reflect Bazel's outputs.
222 buildStatements []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400223
224 // Depsets which should be used for Bazel's build statements.
225 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400226
227 // Per-module allowlist/denylist functionality to control whether analysis of
228 // modules are handled by Bazel. For modules which do not have a Bazel definition
229 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
230 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
231 // Per-module denylist to opt modules out of bazel handling.
232 bazelDisabledModules map[string]bool
233 // Per-module allowlist to opt modules in to bazel handling.
234 bazelEnabledModules map[string]bool
235 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
236 modulesDefaultToBazel bool
Cole Faustb85d1a12022-11-08 18:14:01 -0800237
238 targetProduct string
239 targetBuildVariant string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400240}
241
Sasha Smundak39a301c2022-12-29 17:11:49 -0800242var _ BazelContext = &mixedBuildBazelContext{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400243
244// A bazel context to use when Bazel is disabled.
245type noopBazelContext struct{}
246
247var _ BazelContext = noopBazelContext{}
248
249// A bazel context to use for tests.
250type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400251 OutputBaseDir string
252
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000253 LabelToOutputFiles map[string][]string
254 LabelToCcInfo map[string]cquery.CcInfo
255 LabelToPythonBinary map[string]string
Liz Kammerbe6a7122022-11-04 16:05:11 -0400256 LabelToApexInfo map[string]cquery.ApexInfo
Sasha Smundakedd16662022-10-07 14:44:50 -0700257 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400258}
259
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700260func (m MockBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400261 panic("unimplemented")
Chris Parsons8d6e4332021-02-22 16:13:50 -0500262}
263
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700264func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500265 result, ok := m.LabelToOutputFiles[label]
266 if !ok {
267 return []string{}, fmt.Errorf("no target with label %q in LabelToOutputFiles", label)
268 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400269 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400270}
271
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700272func (m MockBazelContext) GetCcInfo(label string, _ configKey) (cquery.CcInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500273 result, ok := m.LabelToCcInfo[label]
274 if !ok {
275 return cquery.CcInfo{}, fmt.Errorf("no target with label %q in LabelToCcInfo", label)
276 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400277 return result, nil
278}
279
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700280func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500281 result, ok := m.LabelToPythonBinary[label]
282 if !ok {
283 return "", fmt.Errorf("no target with label %q in LabelToPythonBinary", label)
284 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400285 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000286}
287
Liz Kammerbe6a7122022-11-04 16:05:11 -0400288func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500289 result, ok := m.LabelToApexInfo[label]
290 if !ok {
291 return cquery.ApexInfo{}, fmt.Errorf("no target with label %q in LabelToApexInfo", label)
292 }
Liz Kammer0e255ef2022-11-04 16:07:04 -0400293 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700294}
295
Sasha Smundakedd16662022-10-07 14:44:50 -0700296func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500297 result, ok := m.LabelToCcBinary[label]
298 if !ok {
299 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no target with label %q in LabelToCcBinary", label)
300 }
Sasha Smundakedd16662022-10-07 14:44:50 -0700301 return result, nil
302}
303
Liz Kammer690fbac2023-02-10 11:11:17 -0500304func (m MockBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400305 panic("unimplemented")
306}
307
Sasha Smundak39a301c2022-12-29 17:11:49 -0800308func (m MockBazelContext) IsModuleNameAllowed(_ string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400309 return true
310}
311
Liz Kammera92e8442021-04-07 20:25:21 -0400312func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500313
314func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
315 return []bazel.BuildStatement{}
316}
317
Chris Parsons1a7aca02022-04-25 22:35:15 -0400318func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
319 return []bazel.AqueryDepset{}
320}
321
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400322var _ BazelContext = MockBazelContext{}
323
Sasha Smundak39a301c2022-12-29 17:11:49 -0800324func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400325 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400326 bazelCtx.requestMutex.Lock()
327 defer bazelCtx.requestMutex.Unlock()
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500328
329 // Insert key into requests, maintaining the sort, and only if it's not duplicate.
330 keyString := key.String()
331 foundEqual := false
332 notLessThanKeyString := func(i int) bool {
333 s := bazelCtx.requests[i].String()
334 v := strings.Compare(s, keyString)
335 if v == 0 {
336 foundEqual = true
337 }
338 return v >= 0
339 }
340 targetIndex := sort.Search(len(bazelCtx.requests), notLessThanKeyString)
341 if foundEqual {
342 return
343 }
344
345 if targetIndex == len(bazelCtx.requests) {
346 bazelCtx.requests = append(bazelCtx.requests, key)
347 } else {
348 bazelCtx.requests = append(bazelCtx.requests[:targetIndex+1], bazelCtx.requests[targetIndex:]...)
349 bazelCtx.requests[targetIndex] = key
350 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400351}
352
Sasha Smundak39a301c2022-12-29 17:11:49 -0800353func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400354 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400355 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500356 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400357
Chris Parsonsf874e462022-05-10 13:50:12 -0400358 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400359 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400360 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400361}
362
Sasha Smundak39a301c2022-12-29 17:11:49 -0800363func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400364 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400365 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000366 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400367 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000368 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400369 return cquery.CcInfo{}, fmt.Errorf("no bazel response found for %v", key)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000370}
371
Sasha Smundak39a301c2022-12-29 17:11:49 -0800372func (bazelCtx *mixedBuildBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400373 key := makeCqueryKey(label, cquery.GetPythonBinary, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400374 if rawString, ok := bazelCtx.results[key]; ok {
375 bazelOutput := strings.TrimSpace(rawString)
376 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
377 }
378 return "", fmt.Errorf("no bazel response found for %v", key)
379}
380
Sasha Smundak39a301c2022-12-29 17:11:49 -0800381func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400382 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700383 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500384 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700385 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400386 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700387}
388
Sasha Smundak39a301c2022-12-29 17:11:49 -0800389func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700390 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
391 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500392 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700393 }
394 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
395}
396
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700397func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500398 panic("unimplemented")
399}
400
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700401func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500402 panic("unimplemented")
403}
404
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700405func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400406 panic("unimplemented")
407}
408
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700409func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000410 panic("unimplemented")
411}
412
Liz Kammerbe6a7122022-11-04 16:05:11 -0400413func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700414 panic("unimplemented")
415}
416
Sasha Smundakedd16662022-10-07 14:44:50 -0700417func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
418 //TODO implement me
419 panic("implement me")
420}
421
Liz Kammer690fbac2023-02-10 11:11:17 -0500422func (n noopBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400423 panic("unimplemented")
424}
425
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500426func (m noopBazelContext) OutputBase() string {
427 return ""
428}
429
Sasha Smundak39a301c2022-12-29 17:11:49 -0800430func (n noopBazelContext) IsModuleNameAllowed(_ string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400431 return false
432}
433
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500434func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
435 return []bazel.BuildStatement{}
436}
437
Chris Parsons1a7aca02022-04-25 22:35:15 -0400438func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
439 return []bazel.AqueryDepset{}
440}
441
Cole Faust705968d2022-12-14 11:32:05 -0800442func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400443 disabledModules := map[string]bool{}
444 enabledModules := map[string]bool{}
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800445 addToStringSet := func(set map[string]bool, items []string) {
446 for _, item := range items {
447 set[item] = true
448 }
449 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400450
Cole Faust705968d2022-12-14 11:32:05 -0800451 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400452 case BazelProdMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800453 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800454 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000455 enabledModules[enabledAdHocModule] = true
456 }
MarkDacekb78465d2022-10-18 20:10:16 +0000457 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400458 // Staging mode includes all prod modules plus all staging modules.
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800459 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
460 addToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800461 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000462 enabledModules[enabledAdHocModule] = true
463 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400464 case BazelDevMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800465 addToStringSet(disabledModules, allowlists.MixedBuildsDisabledList)
Chris Parsonsef615e52022-08-18 22:04:11 -0400466 default:
Cole Faust705968d2022-12-14 11:32:05 -0800467 panic("Expected BazelProdMode, BazelStagingMode, or BazelDevMode")
468 }
469 return enabledModules, disabledModules
470}
471
472func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
473 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
474 enabledList := make([]string, 0, len(enabledModules))
475 for module := range enabledModules {
476 if !disabledModules[module] {
477 enabledList = append(enabledList, module)
478 }
479 }
480 sort.Strings(enabledList)
481 return enabledList
482}
483
484func NewBazelContext(c *config) (BazelContext, error) {
485 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode && c.BuildMode != BazelDevMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400486 return noopBazelContext{}, nil
487 }
488
Cole Faust705968d2022-12-14 11:32:05 -0800489 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
490
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800491 paths := bazelPaths{
492 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400493 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800494 var missing []string
495 vars := []struct {
496 name string
497 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000498
499 // True if the environment variable needs to be tracked so that changes to the variable
500 // cause the ninja file to be regenerated, false otherwise. False should only be set for
501 // environment variables that have no effect on the generated ninja file.
502 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800503 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000504 {"BAZEL_HOME", &paths.homeDir, true},
505 {"BAZEL_PATH", &paths.bazelPath, true},
506 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
507 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
508 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
509 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800510 }
511 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000512 if v.track {
513 if s := c.Getenv(v.name); len(s) > 1 {
514 *v.ptr = s
515 continue
516 }
517 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800518 *v.ptr = s
519 } else {
520 missing = append(missing, v.name)
521 }
522 }
523 if len(missing) > 0 {
524 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
525 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800526
527 targetBuildVariant := "user"
528 if c.Eng() {
529 targetBuildVariant = "eng"
530 } else if c.Debuggable() {
531 targetBuildVariant = "userdebug"
532 }
533 targetProduct := "unknown"
534 if c.HasDeviceProduct() {
535 targetProduct = c.DeviceProduct()
536 }
537
Sasha Smundak39a301c2022-12-29 17:11:49 -0800538 return &mixedBuildBazelContext{
Chris Parsonsad876012022-08-20 14:48:32 -0400539 bazelRunner: &builtinBazelRunner{},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800540 paths: &paths,
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800541 modulesDefaultToBazel: c.BuildMode == BazelDevMode,
Chris Parsonsef615e52022-08-18 22:04:11 -0400542 bazelEnabledModules: enabledModules,
Chris Parsonsad876012022-08-20 14:48:32 -0400543 bazelDisabledModules: disabledModules,
Cole Faustb85d1a12022-11-08 18:14:01 -0800544 targetProduct: targetProduct,
545 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400546 }, nil
547}
548
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400549func (p *bazelPaths) BazelMetricsDir() string {
550 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000551}
552
Sasha Smundak39a301c2022-12-29 17:11:49 -0800553func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400554 if context.bazelDisabledModules[moduleName] {
555 return false
556 }
557 if context.bazelEnabledModules[moduleName] {
558 return true
559 }
560 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400561}
562
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400563func pwdPrefix() string {
564 // Darwin doesn't have /proc
565 if runtime.GOOS != "darwin" {
566 return "PWD=/proc/self/cwd"
567 }
568 return ""
569}
570
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400571type bazelCommand struct {
572 command string
573 // query or label
574 expression string
575}
576
577type mockBazelRunner struct {
578 bazelCommandResults map[bazelCommand]string
Jason Wu52cd1942022-09-08 15:37:57 +0000579 // use *exec.Cmd as a key to get the bazelCommand, the map will be used in issueBazelCommand()
580 // Register createBazelCommand() invocations. Later, an
581 // issueBazelCommand() invocation can be mapped to the *exec.Cmd instance
582 // and then to the expected result via bazelCommandResults
583 tokens map[*exec.Cmd]bazelCommand
584 commands []bazelCommand
585 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400586}
587
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500588func (r *mockBazelRunner) createBazelCommand(_ Config, _ *bazelPaths, _ bazel.RunName,
Jason Wu52cd1942022-09-08 15:37:57 +0000589 command bazelCommand, extraFlags ...string) *exec.Cmd {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400590 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700591 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Jason Wu52cd1942022-09-08 15:37:57 +0000592 cmd := &exec.Cmd{}
593 if r.tokens == nil {
594 r.tokens = make(map[*exec.Cmd]bazelCommand)
595 }
596 r.tokens[cmd] = command
597 return cmd
598}
599
Liz Kammer690fbac2023-02-10 11:11:17 -0500600func (r *mockBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd, _ *metrics.EventHandler) (string, string, error) {
Jason Wu52cd1942022-09-08 15:37:57 +0000601 if command, ok := r.tokens[bazelCmd]; ok {
602 return r.bazelCommandResults[command], "", nil
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400603 }
604 return "", "", nil
605}
606
607type builtinBazelRunner struct{}
608
Chris Parsons808d84c2021-03-09 20:43:32 -0500609// Issues the given bazel command with given build label and additional flags.
610// Returns (stdout, stderr, error). The first and second return values are strings
611// containing the stdout and stderr of the run command, and an error is returned if
612// the invocation returned an error code.
Liz Kammer690fbac2023-02-10 11:11:17 -0500613func (r *builtinBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd, eventHandler *metrics.EventHandler) (string, string, error) {
614 eventHandler.Begin("bazel command")
615 defer eventHandler.End("bazel command")
Jason Wu52cd1942022-09-08 15:37:57 +0000616 stderr := &bytes.Buffer{}
617 bazelCmd.Stderr = stderr
618 if output, err := bazelCmd.Output(); err != nil {
619 return "", string(stderr.Bytes()),
Sasha Smundak0e87b182022-12-01 11:46:11 -0800620 fmt.Errorf("bazel command failed: %s\n---command---\n%s\n---env---\n%s\n---stderr---\n%s---",
621 err, bazelCmd, strings.Join(bazelCmd.Env, "\n"), stderr)
Jason Wu52cd1942022-09-08 15:37:57 +0000622 } else {
623 return string(output), string(stderr.Bytes()), nil
624 }
625}
626
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500627func (r *builtinBazelRunner) createBazelCommand(config Config, paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Jason Wu52cd1942022-09-08 15:37:57 +0000628 extraFlags ...string) *exec.Cmd {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000629 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000630 "--output_base=" + absolutePath(paths.outputBase),
631 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700632 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700633 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700634 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400635
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700636 // Set default platforms to canonicalized values for mixed builds requests.
637 // If these are set in the bazelrc, they will have values that are
638 // non-canonicalized to @sourceroot labels, and thus be invalid when
639 // referenced from the buildroot.
640 //
641 // The actual platform values here may be overridden by configuration
642 // transitions from the buildroot.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700643 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Cole Faustb85d1a12022-11-08 18:14:01 -0800644
645 // We don't need to set --host_platforms because it's set in bazelrc files
646 // that the bazel shell script wrapper passes
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700647
648 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
649 "--experimental_repository_disable_download",
650
651 // Suppress noise
652 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500653 "--noshow_progress",
654 "--norun_validations",
655 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400656 cmdFlags = append(cmdFlags, extraFlags...)
657
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400658 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200659 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700660 extraEnv := []string{
661 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200662 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700663 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700664 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000665 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700666 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500667 // Disables local host detection of gcc; toolchain information is defined
668 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700669 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
670 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500671 for _, envvar := range allowedBazelEnvironmentVars {
672 val := config.Getenv(envvar)
673 if val == "" {
674 continue
675 }
676 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
677 }
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700678 bazelCmd.Env = append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400679
Jason Wu52cd1942022-09-08 15:37:57 +0000680 return bazelCmd
681}
682
683func printableCqueryCommand(bazelCmd *exec.Cmd) string {
684 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(bazelCmd.Args, "\" \"") + "\""
685 return outputString
686
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400687}
688
Sasha Smundak39a301c2022-12-29 17:11:49 -0800689func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500690 // TODO(cparsons): Define configuration transitions programmatically based
691 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400692 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500693#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400694# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500695#####################################################
696
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400697def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800698 if attr.os == "android" and attr.arch == "target":
699 target = "{PRODUCT}-{VARIANT}"
700 else:
701 target = "{PRODUCT}-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500702 return {
Cole Faustb85d1a12022-11-08 18:14:01 -0800703 "//command_line_option:platforms": "@soong_injection//product_config_platforms/products/{PRODUCT}-{VARIANT}:%s" % target,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500704 }
705
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400706_config_node_transition = transition(
707 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500708 inputs = [],
709 outputs = [
710 "//command_line_option:platforms",
711 ],
712)
713
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400714def _passthrough_rule_impl(ctx):
715 return [DefaultInfo(files = depset(ctx.files.deps))]
716
717config_node = rule(
718 implementation = _passthrough_rule_impl,
719 attrs = {
720 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400721 "os" : attr.string(mandatory = True),
722 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400723 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
724 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500725)
726
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400727
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500728# Rule representing the root of the build, to depend on all Bazel targets that
729# are required for the build. Building this target will build the entire Bazel
730# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400731mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400732 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500733 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400734 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500735 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400736)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500737
738def _phony_root_impl(ctx):
739 return []
740
741# Rule to depend on other targets but build nothing.
742# This is useful as follows: building a target of this rule will generate
743# symlink forests for all dependencies of the target, without executing any
744# actions of the build.
745phony_root = rule(
746 implementation = _phony_root_impl,
747 attrs = {"deps" : attr.label_list()},
748)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400749`
Cole Faustb85d1a12022-11-08 18:14:01 -0800750
751 productReplacer := strings.NewReplacer(
752 "{PRODUCT}", context.targetProduct,
753 "{VARIANT}", context.targetBuildVariant)
754
755 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400756}
757
Sasha Smundak39a301c2022-12-29 17:11:49 -0800758func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500759 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
760 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400761 formatString := `
762# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400763load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
764
765%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400766
767mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400768 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000769 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400770)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500771
772phony_root(name = "phonyroot",
773 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000774 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500775)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400776`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400777 configNodeFormatString := `
778config_node(name = "%s",
779 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400780 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400781 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000782 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400783)
784`
785
786 configNodesSection := ""
787
Chris Parsons787fb362021-10-14 18:43:51 -0400788 labelsByConfig := map[string][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500789
790 for _, val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200791 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400792 configString := getConfigString(val)
793 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400794 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400795
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500796 // Configs need to be sorted to maintain determinism of the BUILD file.
797 sortedConfigs := make([]string, 0, len(labelsByConfig))
798 for val := range labelsByConfig {
799 sortedConfigs = append(sortedConfigs, val)
800 }
801 sort.Slice(sortedConfigs, func(i, j int) bool { return sortedConfigs[i] < sortedConfigs[j] })
802
Jingwen Chen1e347862021-09-02 12:11:49 +0000803 allLabels := []string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500804 for _, configString := range sortedConfigs {
805 labels := labelsByConfig[configString]
Chris Parsons787fb362021-10-14 18:43:51 -0400806 configTokens := strings.Split(configString, "|")
807 if len(configTokens) != 2 {
808 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000809 }
Chris Parsons787fb362021-10-14 18:43:51 -0400810 archString := configTokens[0]
811 osString := configTokens[1]
812 targetString := fmt.Sprintf("%s_%s", osString, archString)
813 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
814 labelsString := strings.Join(labels, ",\n ")
815 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400816 }
817
Jingwen Chen1e347862021-09-02 12:11:49 +0000818 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400819}
820
Chris Parsons944e7d02021-03-11 11:08:46 -0500821func indent(original string) string {
822 result := ""
823 for _, line := range strings.Split(original, "\n") {
824 result += " " + line + "\n"
825 }
826 return result
827}
828
Chris Parsons808d84c2021-03-09 20:43:32 -0500829// Returns the file contents of the buildroot.cquery file that should be used for the cquery
830// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800831// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500832// and grouped by their request type. The data retrieved for each label depends on its
833// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800834func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400835 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500836 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500837 cqueryId := getCqueryId(val)
838 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
839 requestTypeToCqueryIdEntries[val.requestType] =
840 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
841 }
842 labelRegistrationMapSection := ""
843 functionDefSection := ""
844 mainSwitchSection := ""
845
846 mapDeclarationFormatString := `
847%s = {
848 %s
849}
850`
851 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800852def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500853%s
854`
855 mainSwitchSectionFormatString := `
856 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800857 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500858`
859
Usta Shrestha0b52d832022-02-04 21:37:39 -0500860 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500861 labelMapName := requestType.Name() + "_Labels"
862 functionName := requestType.Name() + "_Fn"
863 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
864 labelMapName,
865 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
866 functionDefSection += fmt.Sprintf(functionDefFormatString,
867 functionName,
868 indent(requestType.StarlarkFunctionBody()))
869 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
870 labelMapName, functionName)
871 }
872
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400873 formatString := `
874# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400875
Usta Shrestha79fccef2022-09-02 18:37:40 -0400876# a drop-in replacement for json.encode(), not available in cquery environment
877# TODO(cparsons): bring json module in and remove this function
878def json_encode(input):
879 # Avoiding recursion by limiting
880 # - a dict to contain anything except a dict
881 # - a list to contain only primitives
882 def encode_primitive(p):
883 t = type(p)
884 if t == "string" or t == "int":
885 return repr(p)
Cole Faustb85d1a12022-11-08 18:14:01 -0800886 fail("unsupported value '%s' of type '%s'" % (p, type(p)))
Usta Shrestha79fccef2022-09-02 18:37:40 -0400887
888 def encode_list(list):
Cole Faustb85d1a12022-11-08 18:14:01 -0800889 return "[%s]" % ", ".join([encode_primitive(item) for item in list])
Usta Shrestha79fccef2022-09-02 18:37:40 -0400890
891 def encode_list_or_primitive(v):
892 return encode_list(v) if type(v) == "list" else encode_primitive(v)
893
894 if type(input) == "dict":
895 # TODO(juu): the result is read line by line so can't use '\n' yet
Cole Faustb85d1a12022-11-08 18:14:01 -0800896 kv_pairs = [("%s: %s" % (encode_primitive(k), encode_list_or_primitive(v))) for (k, v) in input.items()]
897 return "{ %s }" % ", ".join(kv_pairs)
Usta Shrestha79fccef2022-09-02 18:37:40 -0400898 else:
899 return encode_list_or_primitive(input)
900
Cole Faustb85d1a12022-11-08 18:14:01 -0800901{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500902
Cole Faustb85d1a12022-11-08 18:14:01 -0800903{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500904
905def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400906 # TODO(b/199363072): filegroups and file targets aren't associated with any
907 # specific platform architecture in mixed builds. This is consistent with how
908 # Soong treats filegroups, but it may not be the case with manually-written
909 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500910 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000911 if buildoptions == None:
912 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400913 # any specific platform architecture in mixed builds, so use the host.
914 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -0800915 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500916 if len(platforms) != 1:
917 # An individual configured target should have only one platform architecture.
918 # Note that it's fine for there to be multiple architectures for the same label,
919 # but each is its own configured target.
920 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -0800921 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -0500922 if platform_name == "host":
923 return "HOST"
Cole Faustb85d1a12022-11-08 18:14:01 -0800924 if not platform_name.startswith("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}"):
925 fail("expected platform name of the form '{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}_android_<arch>' or '{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}_linux_<arch>', but was " + str(platforms))
926 platform_name = platform_name.removeprefix("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}").removeprefix("_")
927 if not platform_name:
928 return "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400929 elif platform_name.startswith("android_"):
Cole Faustb85d1a12022-11-08 18:14:01 -0800930 return platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400931 elif platform_name.startswith("linux_"):
Cole Faustb85d1a12022-11-08 18:14:01 -0800932 return platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400933 else:
Cole Faustb85d1a12022-11-08 18:14:01 -0800934 fail("expected platform name of the form '{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}_android_<arch>' or '{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}_linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500935
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400936def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500937 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500938
Chris Parsons86dc2c22022-09-28 14:58:41 -0400939 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
940 if id_string.startswith("//"):
941 id_string = "@" + id_string
942
Cole Faustb85d1a12022-11-08 18:14:01 -0800943 {MAIN_SWITCH_SECTION}
944
Chris Parsons944e7d02021-03-11 11:08:46 -0500945 # This target was not requested via cquery, and thus must be a dependency
946 # of a requested target.
947 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400948`
Cole Faustb85d1a12022-11-08 18:14:01 -0800949 replacer := strings.NewReplacer(
950 "{TARGET_PRODUCT}", context.targetProduct,
951 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
952 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
953 "{FUNCTION_DEF_SECTION}", functionDefSection,
954 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400955
Cole Faustb85d1a12022-11-08 18:14:01 -0800956 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400957}
958
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200959// Returns a path containing build-related metadata required for interfacing
960// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400961func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200962 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500963}
964
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200965// Returns the path where the contents of the @soong_injection repository live.
966// It is used by Soong to tell Bazel things it cannot over the command line.
967func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200968 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200969}
970
971// Returns the path of the synthetic Bazel workspace that contains a symlink
972// forest composed the whole source tree and BUILD files generated by bp2build.
973func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200974 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200975}
976
Jingwen Chen8c523582021-06-01 11:19:53 +0000977// Returns the path to the top level out dir ($OUT_DIR).
978func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200979 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000980}
981
Sasha Smundak4975c822022-11-16 15:28:18 -0800982const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
983
984var (
985 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
986 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
987 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
988)
989
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400990// Issues commands to Bazel to receive results for all cquery requests
991// queued in the BazelContext.
Liz Kammer690fbac2023-02-10 11:11:17 -0500992func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx invokeBazelContext) error {
993 eventHandler := ctx.GetEventHandler()
994 eventHandler.Begin("bazel")
995 defer eventHandler.End("bazel")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400996
Sasha Smundak4975c822022-11-16 15:28:18 -0800997 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
998 if err := os.MkdirAll(metricsDir, 0777); err != nil {
999 return err
1000 }
1001 }
1002 context.results = make(map[cqueryKey]string)
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001003 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001004 return err
1005 }
1006 if err := context.runAquery(config, ctx); err != nil {
1007 return err
1008 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001009 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001010 return err
1011 }
1012
1013 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001014 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -08001015 return nil
1016}
1017
Liz Kammer690fbac2023-02-10 11:11:17 -05001018func (context *mixedBuildBazelContext) runCquery(config Config, ctx invokeBazelContext) error {
1019 eventHandler := ctx.GetEventHandler()
1020 eventHandler.Begin("cquery")
1021 defer eventHandler.End("cquery")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001022 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +02001023 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
1024 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
1025 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -05001026 if err != nil {
1027 return err
1028 }
1029 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001030 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001031 return err
1032 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001033 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001034 return err
1035 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001036 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001037 return err
1038 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001039 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001040 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001041 return err
1042 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001043
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001044 cqueryCommandWithFlag := context.createBazelCommand(config, context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001045 "--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
Liz Kammer690fbac2023-02-10 11:11:17 -05001046 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCommandWithFlag, eventHandler)
Wei Licbd181c2022-11-16 08:59:23 -08001047 if cqueryErr != nil {
1048 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001049 }
Jason Wu52cd1942022-09-08 15:37:57 +00001050 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", printableCqueryCommand(cqueryCommandWithFlag))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001051 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001052 return err
1053 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001054 cqueryResults := map[string]string{}
1055 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1056 if strings.Contains(outputLine, ">>") {
1057 splitLine := strings.SplitN(outputLine, ">>", 2)
1058 cqueryResults[splitLine[0]] = splitLine[1]
1059 }
1060 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001061 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001062 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001063 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001064 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001065 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001066 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001067 }
1068 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001069 return nil
1070}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001071
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001072func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1073 oldContents, err := os.ReadFile(path)
1074 if err != nil || !bytes.Equal(contents, oldContents) {
1075 err = os.WriteFile(path, contents, perm)
1076 }
1077 return nil
1078}
1079
Liz Kammer690fbac2023-02-10 11:11:17 -05001080func (context *mixedBuildBazelContext) runAquery(config Config, ctx invokeBazelContext) error {
1081 eventHandler := ctx.GetEventHandler()
1082 eventHandler.Begin("aquery")
1083 defer eventHandler.End("aquery")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001084 // Issue an aquery command to retrieve action information about the bazel build tree.
1085 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001086 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1087 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001088 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001089 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001090 extraFlags = append(extraFlags, "--collect_code_coverage")
1091 paths := make([]string, 0, 2)
1092 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001093 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001094 // TODO(b/259404593) convert path wildcard to regex values
1095 if p[i] == "*" {
1096 p[i] = ".*"
1097 }
1098 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001099 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1100 }
1101 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1102 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1103 }
1104 if len(paths) > 0 {
1105 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001106 }
1107 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001108 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
Liz Kammer690fbac2023-02-10 11:11:17 -05001109 extraFlags...), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001110 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001111 return err
1112 }
Liz Kammer690fbac2023-02-10 11:11:17 -05001113 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001114 return err
1115}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001116
Liz Kammer690fbac2023-02-10 11:11:17 -05001117func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx invokeBazelContext) error {
1118 eventHandler := ctx.GetEventHandler()
1119 eventHandler.Begin("symlinks")
1120 defer eventHandler.End("symlinks")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001121 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1122 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1123 // but some of symlinks may be required to resolve source dependencies of the build.
Liz Kammer690fbac2023-02-10 11:11:17 -05001124 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001125 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001126}
Chris Parsonsa798d962020-10-12 23:44:08 -04001127
Sasha Smundak39a301c2022-12-29 17:11:49 -08001128func (context *mixedBuildBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001129 return context.buildStatements
1130}
1131
Sasha Smundak39a301c2022-12-29 17:11:49 -08001132func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001133 return context.depsets
1134}
1135
Sasha Smundak39a301c2022-12-29 17:11:49 -08001136func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001137 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001138}
1139
Chris Parsonsa798d962020-10-12 23:44:08 -04001140// Singleton used for registering BUILD file ninja dependencies (needed
1141// for correctness of builds which use Bazel.
1142func BazelSingleton() Singleton {
1143 return &bazelSingleton{}
1144}
1145
1146type bazelSingleton struct{}
1147
1148func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001149 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001150 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001151 return
1152 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001153
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001154 // Add ninja file dependencies for files which all bazel invocations require.
1155 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001156 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001157 ctx.AddNinjaFileDeps(bazelBuildList)
1158
Sasha Smundak0e87b182022-12-01 11:46:11 -08001159 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001160 if err != nil {
1161 ctx.Errorf(err.Error())
1162 }
1163 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1164 for _, file := range files {
1165 ctx.AddNinjaFileDeps(file)
1166 }
1167
Chris Parsons1a7aca02022-04-25 22:35:15 -04001168 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1169 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001170 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001171 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1172 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001173 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1174 }
1175 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001176 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1177 if artifactPath == "bazel-out/volatile-status.txt" {
1178 // See https://bazel.build/docs/user-manual#workspace-status
1179 orderOnlies = append(orderOnlies, pathInBazelOut)
1180 } else {
1181 outputs = append(outputs, pathInBazelOut)
1182 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001183 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001184 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001185 ctx.Build(pctx, BuildParams{
1186 Rule: blueprint.Phony,
1187 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1188 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001189 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001190 })
1191 }
1192
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001193 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1194 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001195 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -07001196 if len(buildStatement.Command) > 0 {
1197 rule := NewRuleBuilder(pctx, ctx)
1198 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1199 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1200 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1201 continue
1202 }
1203 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1204 // and thus require special treatment. If BuildStatement were an interface implementing
1205 // buildRule(ctx) function, the code here would just call it.
1206 // Unfortunately, the BuildStatement is defined in
1207 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1208 // because this would cause circular dependency. So, until we move aquery processing
1209 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001210 switch buildStatement.Mnemonic {
1211 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001212 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1213 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001214 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001215 // build-runfiles arguments are the manifest file and the target directory
1216 // where it creates the symlink tree according to this manifest (and then
1217 // writes the MANIFEST file to it).
1218 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1219 outManifestPath := outManifest.String()
1220 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1221 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1222 }
1223 outDir := filepath.Dir(outManifestPath)
1224 ctx.Build(pctx, BuildParams{
1225 Rule: buildRunfilesRule,
1226 Output: outManifest,
1227 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1228 Description: "symlink tree for " + outDir,
1229 Args: map[string]string{
1230 "outDir": outDir,
1231 },
1232 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001233 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001234 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001235 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001236 }
1237}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001238
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001239// Register bazel-owned build statements (obtained from the aquery invocation).
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001240func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001241 // executionRoot is the action cwd.
1242 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1243
1244 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1245 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001246 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001247 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001248 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001249 }
1250 cmd.Text("&&")
1251 }
1252
1253 for _, pair := range buildStatement.Env {
1254 // Set per-action env variables, if any.
1255 cmd.Flag(pair.Key + "=" + pair.Value)
1256 }
1257
1258 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001259 if len(buildStatement.Command) > 16*1024 {
1260 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1261 WriteFileRule(ctx, commandFile, buildStatement.Command)
1262
1263 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1264 } else {
1265 cmd.Text(buildStatement.Command)
1266 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001267
1268 for _, outputPath := range buildStatement.OutputPaths {
1269 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1270 }
1271 for _, inputPath := range buildStatement.InputPaths {
1272 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1273 }
1274 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1275 otherDepsetName := bazelDepsetName(inputDepsetHash)
1276 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1277 }
1278
1279 if depfile := buildStatement.Depfile; depfile != nil {
1280 // The paths in depfile are relative to `executionRoot`.
1281 // Hence, they need to be corrected by replacing "bazel-out"
1282 // with the full `bazelOutDir`.
1283 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1284 // would be deemed missing.
1285 // (Note: The regexp uses a capture group because the version of sed
1286 // does not support a look-behind pattern.)
1287 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1288 bazelOutDir, *depfile)
1289 cmd.Text(replacement)
1290 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1291 }
1292
1293 for _, symlinkPath := range buildStatement.SymlinkPaths {
1294 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1295 }
1296}
1297
Chris Parsons8d6e4332021-02-22 16:13:50 -05001298func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001299 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001300}
1301
Chris Parsons787fb362021-10-14 18:43:51 -04001302func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001303 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001304 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001305 if key.configKey.osType.Class == Device {
1306 // For the generic Android, the expected result is "target|android", which
1307 // corresponds to the product_variable_config named "android_target" in
1308 // build/bazel/platforms/BUILD.bazel.
1309 arch = "target"
1310 } else {
1311 // Use host platform, which is currently hardcoded to be x86_64.
1312 arch = "x86_64"
1313 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001314 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001315 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001316 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001317 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001318 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001319 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001320 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -04001321}
1322
Chris Parsonsf874e462022-05-10 13:50:12 -04001323func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001324 return configKey{
1325 // use string because Arch is not a valid key in go
1326 arch: ctx.Arch().String(),
1327 osType: ctx.Os(),
1328 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001329}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001330
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001331func bazelDepsetName(contentHash string) string {
1332 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001333}
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001334
1335func EnvironmentVarsFile(config Config) string {
1336 return fmt.Sprintf(bazel.GeneratedBazelFileWarning+`
1337_env = %s
1338
1339env = _env
1340`,
1341 starlark_fmt.PrintStringList(allowedBazelEnvironmentVars, 0),
1342 )
1343}