blob: 51ce3c9e98486fa2ca8b167a4ee30d372d86c52a [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"
Spandan Dasaf4ccaa2023-06-29 01:15:51 +000019 "crypto/sha1"
20 "encoding/hex"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040021 "fmt"
22 "os"
Usta Shresthaacd5a0c2022-06-22 11:20:50 -040023 "path"
Chris Parsonsa798d962020-10-12 23:44:08 -040024 "path/filepath"
Cole Faust16d10942023-08-02 11:45:43 -070025 "regexp"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040026 "runtime"
Cole Faust705968d2022-12-14 11:32:05 -080027 "sort"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040028 "strings"
29 "sync"
Chris Parsonsa798d962020-10-12 23:44:08 -040030
Chris Parsonsad876012022-08-20 14:48:32 -040031 "android/soong/android/allowlists"
Chris Parsons944e7d02021-03-11 11:08:46 -050032 "android/soong/bazel/cquery"
Jingwen Chen1e347862021-09-02 12:11:49 +000033 "android/soong/shared"
Cole Faust8a161be2023-06-14 15:45:12 -070034 "android/soong/starlark_import"
Jingwen Chen379221f2023-03-30 13:19:29 +000035
Cole Faustcb193ec2023-09-20 16:01:18 -070036 "android/soong/bazel"
37
Chris Parsons1a7aca02022-04-25 22:35:15 -040038 "github.com/google/blueprint"
Liz Kammer690fbac2023-02-10 11:11:17 -050039 "github.com/google/blueprint/metrics"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040040)
41
Sasha Smundak1da064c2022-06-08 16:36:16 -070042var (
Sasha Smundakc180dbd2022-07-03 14:55:58 -070043 _ = pctx.HostBinToolVariable("bazelBuildRunfilesTool", "build-runfiles")
44 buildRunfilesRule = pctx.AndroidStaticRule("bazelBuildRunfiles", blueprint.RuleParams{
45 Command: "${bazelBuildRunfilesTool} ${in} ${outDir}",
46 Depfile: "",
47 Description: "",
48 CommandDeps: []string{"${bazelBuildRunfilesTool}"},
49 }, "outDir")
Sasha Smundak1da064c2022-06-08 16:36:16 -070050)
51
Liz Kammerc13f7852023-05-17 13:01:48 -040052func registerMixedBuildsMutator(ctx RegisterMutatorsContext) {
53 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
Chris Parsonsf874e462022-05-10 13:50:12 -040054}
55
56func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammerc13f7852023-05-17 13:01:48 -040057 ctx.FinalDepsMutators(registerMixedBuildsMutator)
Chris Parsonsf874e462022-05-10 13:50:12 -040058}
59
60func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
61 if m := ctx.Module(); m.Enabled() {
62 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
MarkDacekf47e1422023-04-19 16:47:36 +000063 mixedBuildEnabled := MixedBuildsEnabled(ctx)
64 queueMixedBuild := mixedBuildMod.IsMixedBuildSupported(ctx) && mixedBuildEnabled == MixedBuildEnabled
MarkDacek9c094ca2023-03-16 19:15:19 +000065 if queueMixedBuild {
Chris Parsonsf874e462022-05-10 13:50:12 -040066 mixedBuildMod.QueueBazelCall(ctx)
67 }
68 }
69 }
70}
71
Liz Kammerf29df7c2021-04-02 13:37:39 -040072type cqueryRequest interface {
73 // Name returns a string name for this request type. Such request type names must be unique,
74 // and must only consist of alphanumeric characters.
75 Name() string
76
77 // StarlarkFunctionBody returns a starlark function body to process this request type.
78 // The returned string is the body of a Starlark function which obtains
79 // all request-relevant information about a target and returns a string containing
80 // this information.
81 // The function should have the following properties:
Cole Faust97d15272022-11-22 14:08:59 -080082 // - The arguments are `target` (a configured target) and `id_string` (the label + configuration).
Liz Kammerf29df7c2021-04-02 13:37:39 -040083 // - The return value must be a string.
84 // - The function body should not be indented outside of its own scope.
85 StarlarkFunctionBody() string
86}
87
Chris Parsons787fb362021-10-14 18:43:51 -040088// Portion of cquery map key to describe target configuration.
89type configKey struct {
Yu Liue4312402023-01-18 09:15:31 -080090 arch string
91 osType OsType
92 apexKey ApexConfigKey
93}
94
95type ApexConfigKey struct {
96 WithinApex bool
97 ApexSdkVersion string
Spandan Das40b79f82023-06-25 20:56:06 +000098 ApiDomain string
Yu Liue4312402023-01-18 09:15:31 -080099}
100
101func (c ApexConfigKey) String() string {
Spandan Das40b79f82023-06-25 20:56:06 +0000102 return fmt.Sprintf("%s_%s_%s", withinApexToString(c.WithinApex), c.ApexSdkVersion, c.ApiDomain)
Yu Liue4312402023-01-18 09:15:31 -0800103}
104
105func withinApexToString(withinApex bool) string {
106 if withinApex {
107 return "within_apex"
108 }
109 return ""
Chris Parsons787fb362021-10-14 18:43:51 -0400110}
111
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700112func (c configKey) String() string {
Yu Liue4312402023-01-18 09:15:31 -0800113 return fmt.Sprintf("%s::%s::%s", c.arch, c.osType, c.apexKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700114}
115
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400116// Map key to describe bazel cquery requests.
117type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400118 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400119 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400120 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400121}
122
Chris Parsons86dc2c22022-09-28 14:58:41 -0400123func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
124 if strings.HasPrefix(label, "//") {
125 // Normalize Bazel labels to specify main repository explicitly.
126 label = "@" + label
127 }
128 return cqueryKey{label, cqueryRequest, cfgKey}
129}
130
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700131func (c cqueryKey) String() string {
132 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700133}
134
Liz Kammer690fbac2023-02-10 11:11:17 -0500135type invokeBazelContext interface {
136 GetEventHandler() *metrics.EventHandler
137}
138
Chris Parsonsf874e462022-05-10 13:50:12 -0400139// BazelContext is a context object useful for interacting with Bazel during
140// the course of a build. Use of Bazel to evaluate part of the build graph
141// is referred to as a "mixed build". (Some modules are managed by Soong,
142// some are managed by Bazel). To facilitate interop between these build
143// subgraphs, Soong may make requests to Bazel and evaluate their responses
144// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400145type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400146 // Add a cquery request to the bazel request queue. All queued requests
147 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
148 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
149
150 // ** Cquery Results Retrieval Functions
151 // The below functions pertain to retrieving cquery results from a prior
152 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400153
154 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400155 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500156
Chris Parsons944e7d02021-03-11 11:08:46 -0500157 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400158 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400159
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700160 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400161 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700162
Sasha Smundakedd16662022-10-07 14:44:50 -0700163 // Returns the results of the GetCcUnstrippedInfo query
164 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
165
Spandan Dasbd156812023-06-05 22:43:13 +0000166 // Returns the results of the GetPrebuiltFileInfo query
167 GetPrebuiltFileInfo(label string, cfgKey configKey) (cquery.PrebuiltFileInfo, error)
168
Chris Parsonsf874e462022-05-10 13:50:12 -0400169 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400170
171 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800172 // queued in the BazelContext. The ctx argument is optional and is only
173 // used for performance data collection
Liz Kammer690fbac2023-02-10 11:11:17 -0500174 InvokeBazel(config Config, ctx invokeBazelContext) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400175
Chris Parsonsad876012022-08-20 14:48:32 -0400176 // Returns true if Bazel handling is enabled for the module with the given name.
177 // Note that this only implies "bazel mixed build" allowlisting. The caller
178 // should independently verify the module is eligible for Bazel handling
179 // (for example, that it is MixedBuildBuildable).
Yu Liue4312402023-01-18 09:15:31 -0800180 IsModuleNameAllowed(moduleName string, withinApex bool) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500181
182 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
183 OutputBase() string
184
185 // Returns build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500186 BuildStatementsToRegister() []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400187
188 // Returns the depsets defined in Bazel's aquery response.
189 AqueryDepsets() []bazel.AqueryDepset
Cole Faustbc65a3f2023-08-01 16:38:55 +0000190
191 QueueBazelSandwichCqueryRequests(config Config) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400192}
193
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400194type bazelRunner interface {
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000195 issueBazelCommand(cmdRequest bazel.CmdRequest, paths *bazelPaths, eventHandler *metrics.EventHandler) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400196}
197
198type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000199 homeDir string
200 bazelPath string
201 outputBase string
202 workspaceDir string
203 soongOutDir string
204 metricsDir string
205 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400206}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400207
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400208// A context object which tracks queued requests that need to be made to Bazel,
209// and their results after the requests have been made.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800210type mixedBuildBazelContext struct {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400211 bazelRunner
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500212 paths *bazelPaths
213 // cquery requests that have not yet been issued to Bazel. This list is maintained
214 // in a sorted state, and is guaranteed to have no duplicates.
215 requests []cqueryKey
216 requestMutex sync.Mutex // requests can be written in parallel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400217
218 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500219
220 // Build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500221 buildStatements []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400222
223 // Depsets which should be used for Bazel's build statements.
224 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400225
226 // Per-module allowlist/denylist functionality to control whether analysis of
227 // modules are handled by Bazel. For modules which do not have a Bazel definition
228 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
229 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
230 // Per-module denylist to opt modules out of bazel handling.
231 bazelDisabledModules map[string]bool
232 // Per-module allowlist to opt modules in to bazel handling.
233 bazelEnabledModules map[string]bool
Yu Liue4312402023-01-18 09:15:31 -0800234 // DCLA modules are enabled when used in apex.
235 bazelDclaEnabledModules map[string]bool
Cole Faustb85d1a12022-11-08 18:14:01 -0800236
237 targetProduct string
238 targetBuildVariant string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400239}
240
Sasha Smundak39a301c2022-12-29 17:11:49 -0800241var _ BazelContext = &mixedBuildBazelContext{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400242
243// A bazel context to use when Bazel is disabled.
244type noopBazelContext struct{}
245
246var _ BazelContext = noopBazelContext{}
247
248// A bazel context to use for tests.
249type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400250 OutputBaseDir string
251
Spandan Dasbd156812023-06-05 22:43:13 +0000252 LabelToOutputFiles map[string][]string
253 LabelToCcInfo map[string]cquery.CcInfo
254 LabelToPythonBinary map[string]string
255 LabelToApexInfo map[string]cquery.ApexInfo
256 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
257 LabelToPrebuiltFileInfo map[string]cquery.PrebuiltFileInfo
Yu Liue4312402023-01-18 09:15:31 -0800258
259 BazelRequests map[string]bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400260}
261
Yu Liue4312402023-01-18 09:15:31 -0800262func (m MockBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
263 key := BuildMockBazelContextRequestKey(label, requestType, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
264 if m.BazelRequests == nil {
265 m.BazelRequests = make(map[string]bool)
266 }
267 m.BazelRequests[key] = true
Chris Parsons8d6e4332021-02-22 16:13:50 -0500268}
269
Cole Faustbc65a3f2023-08-01 16:38:55 +0000270func (m MockBazelContext) QueueBazelSandwichCqueryRequests(config Config) error {
271 panic("unimplemented")
272}
273
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700274func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500275 result, ok := m.LabelToOutputFiles[label]
276 if !ok {
277 return []string{}, fmt.Errorf("no target with label %q in LabelToOutputFiles", label)
278 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400279 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400280}
281
Yu Liue4312402023-01-18 09:15:31 -0800282func (m MockBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500283 result, ok := m.LabelToCcInfo[label]
284 if !ok {
Yu Liue4312402023-01-18 09:15:31 -0800285 key := BuildMockBazelContextResultKey(label, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
286 result, ok = m.LabelToCcInfo[key]
287 if !ok {
288 return cquery.CcInfo{}, fmt.Errorf("no target with label %q in LabelToCcInfo", label)
289 }
Sam Delmericoce39f832023-01-23 14:04:24 -0500290 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400291 return result, nil
292}
293
Liz Kammerbe6a7122022-11-04 16:05:11 -0400294func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500295 result, ok := m.LabelToApexInfo[label]
296 if !ok {
297 return cquery.ApexInfo{}, fmt.Errorf("no target with label %q in LabelToApexInfo", label)
298 }
Liz Kammer0e255ef2022-11-04 16:07:04 -0400299 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700300}
301
Sasha Smundakedd16662022-10-07 14:44:50 -0700302func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500303 result, ok := m.LabelToCcBinary[label]
304 if !ok {
305 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no target with label %q in LabelToCcBinary", label)
306 }
Sasha Smundakedd16662022-10-07 14:44:50 -0700307 return result, nil
308}
309
Spandan Dasbd156812023-06-05 22:43:13 +0000310func (m MockBazelContext) GetPrebuiltFileInfo(label string, _ configKey) (cquery.PrebuiltFileInfo, error) {
311 result, ok := m.LabelToPrebuiltFileInfo[label]
312 if !ok {
313 return cquery.PrebuiltFileInfo{}, fmt.Errorf("no target with label %q in LabelToPrebuiltFileInfo", label)
314 }
315 return result, nil
316}
317
Liz Kammer690fbac2023-02-10 11:11:17 -0500318func (m MockBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400319 panic("unimplemented")
320}
321
Yu Liue4312402023-01-18 09:15:31 -0800322func (m MockBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400323 return true
324}
325
Liz Kammera92e8442021-04-07 20:25:21 -0400326func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500327
Liz Kammera4655a92023-02-10 17:17:28 -0500328func (m MockBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
329 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500330}
331
Chris Parsons1a7aca02022-04-25 22:35:15 -0400332func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
333 return []bazel.AqueryDepset{}
334}
335
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400336var _ BazelContext = MockBazelContext{}
337
Yu Liue4312402023-01-18 09:15:31 -0800338func BuildMockBazelContextRequestKey(label string, request cqueryRequest, arch string, osType OsType, apexKey ApexConfigKey) string {
339 cfgKey := configKey{
340 arch: arch,
341 osType: osType,
342 apexKey: apexKey,
343 }
344
345 return strings.Join([]string{label, request.Name(), cfgKey.String()}, "_")
346}
347
348func BuildMockBazelContextResultKey(label string, arch string, osType OsType, apexKey ApexConfigKey) string {
349 cfgKey := configKey{
350 arch: arch,
351 osType: osType,
352 apexKey: apexKey,
353 }
354
355 return strings.Join([]string{label, cfgKey.String()}, "_")
356}
357
Sasha Smundak39a301c2022-12-29 17:11:49 -0800358func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400359 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400360 bazelCtx.requestMutex.Lock()
361 defer bazelCtx.requestMutex.Unlock()
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500362
363 // Insert key into requests, maintaining the sort, and only if it's not duplicate.
364 keyString := key.String()
365 foundEqual := false
366 notLessThanKeyString := func(i int) bool {
367 s := bazelCtx.requests[i].String()
368 v := strings.Compare(s, keyString)
369 if v == 0 {
370 foundEqual = true
371 }
372 return v >= 0
373 }
374 targetIndex := sort.Search(len(bazelCtx.requests), notLessThanKeyString)
375 if foundEqual {
376 return
377 }
378
379 if targetIndex == len(bazelCtx.requests) {
380 bazelCtx.requests = append(bazelCtx.requests, key)
381 } else {
382 bazelCtx.requests = append(bazelCtx.requests[:targetIndex+1], bazelCtx.requests[targetIndex:]...)
383 bazelCtx.requests[targetIndex] = key
384 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400385}
386
Sasha Smundak39a301c2022-12-29 17:11:49 -0800387func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400388 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400389 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500390 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400391
Chris Parsonsf874e462022-05-10 13:50:12 -0400392 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400393 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400394 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400395}
396
Sasha Smundak39a301c2022-12-29 17:11:49 -0800397func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400398 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400399 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000400 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400401 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000402 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400403 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 +0000404}
405
Sasha Smundak39a301c2022-12-29 17:11:49 -0800406func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400407 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700408 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500409 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700410 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400411 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700412}
413
Sasha Smundak39a301c2022-12-29 17:11:49 -0800414func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700415 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
416 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500417 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700418 }
419 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
420}
421
Spandan Dasbd156812023-06-05 22:43:13 +0000422func (bazelCtx *mixedBuildBazelContext) GetPrebuiltFileInfo(label string, cfgKey configKey) (cquery.PrebuiltFileInfo, error) {
423 key := makeCqueryKey(label, cquery.GetPrebuiltFileInfo, cfgKey)
424 if rawString, ok := bazelCtx.results[key]; ok {
425 return cquery.GetPrebuiltFileInfo.ParseResult(strings.TrimSpace(rawString))
426 }
427 return cquery.PrebuiltFileInfo{}, fmt.Errorf("no bazel response for %s", key)
428}
429
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700430func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500431 panic("unimplemented")
432}
433
Cole Faustbc65a3f2023-08-01 16:38:55 +0000434func (n noopBazelContext) QueueBazelSandwichCqueryRequests(config Config) error {
435 panic("unimplemented")
436}
437
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700438func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500439 panic("unimplemented")
440}
441
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700442func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400443 panic("unimplemented")
444}
445
Liz Kammerbe6a7122022-11-04 16:05:11 -0400446func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700447 panic("unimplemented")
448}
449
Sasha Smundakedd16662022-10-07 14:44:50 -0700450func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
451 //TODO implement me
452 panic("implement me")
453}
454
Spandan Dasbd156812023-06-05 22:43:13 +0000455func (n noopBazelContext) GetPrebuiltFileInfo(_ string, _ configKey) (cquery.PrebuiltFileInfo, error) {
456 panic("implement me")
457}
458
Liz Kammer690fbac2023-02-10 11:11:17 -0500459func (n noopBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400460 panic("unimplemented")
461}
462
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500463func (m noopBazelContext) OutputBase() string {
464 return ""
465}
466
Yu Liue4312402023-01-18 09:15:31 -0800467func (n noopBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400468 return false
469}
470
Liz Kammera4655a92023-02-10 17:17:28 -0500471func (m noopBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
472 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500473}
474
Chris Parsons1a7aca02022-04-25 22:35:15 -0400475func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
476 return []bazel.AqueryDepset{}
477}
478
Yu Liu6a7940c2023-05-09 17:12:22 -0700479func AddToStringSet(set map[string]bool, items []string) {
Yu Liue4312402023-01-18 09:15:31 -0800480 for _, item := range items {
481 set[item] = true
482 }
483}
484
Cole Faust705968d2022-12-14 11:32:05 -0800485func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400486 disabledModules := map[string]bool{}
487 enabledModules := map[string]bool{}
488
Cole Faust705968d2022-12-14 11:32:05 -0800489 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400490 case BazelProdMode:
Yu Liu6a7940c2023-05-09 17:12:22 -0700491 AddToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800492 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000493 enabledModules[enabledAdHocModule] = true
494 }
MarkDacekb78465d2022-10-18 20:10:16 +0000495 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400496 // Staging mode includes all prod modules plus all staging modules.
Yu Liu6a7940c2023-05-09 17:12:22 -0700497 AddToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
498 AddToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800499 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000500 enabledModules[enabledAdHocModule] = true
501 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400502 default:
Chris Parsons21f80272023-06-15 04:02:28 +0000503 panic("Expected BazelProdMode or BazelStagingMode")
Cole Faust705968d2022-12-14 11:32:05 -0800504 }
505 return enabledModules, disabledModules
506}
507
508func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
509 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
510 enabledList := make([]string, 0, len(enabledModules))
511 for module := range enabledModules {
512 if !disabledModules[module] {
513 enabledList = append(enabledList, module)
514 }
515 }
516 sort.Strings(enabledList)
517 return enabledList
518}
519
520func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons21f80272023-06-15 04:02:28 +0000521 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400522 return noopBazelContext{}, nil
523 }
524
Cole Faust705968d2022-12-14 11:32:05 -0800525 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
526
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800527 paths := bazelPaths{
528 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400529 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800530 var missing []string
531 vars := []struct {
532 name string
533 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000534
535 // True if the environment variable needs to be tracked so that changes to the variable
536 // cause the ninja file to be regenerated, false otherwise. False should only be set for
537 // environment variables that have no effect on the generated ninja file.
538 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800539 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000540 {"BAZEL_HOME", &paths.homeDir, true},
541 {"BAZEL_PATH", &paths.bazelPath, true},
542 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
543 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
544 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
545 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800546 }
547 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000548 if v.track {
549 if s := c.Getenv(v.name); len(s) > 1 {
550 *v.ptr = s
551 continue
552 }
553 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800554 *v.ptr = s
555 } else {
556 missing = append(missing, v.name)
557 }
558 }
559 if len(missing) > 0 {
560 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
561 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800562
563 targetBuildVariant := "user"
564 if c.Eng() {
565 targetBuildVariant = "eng"
566 } else if c.Debuggable() {
567 targetBuildVariant = "userdebug"
568 }
569 targetProduct := "unknown"
570 if c.HasDeviceProduct() {
571 targetProduct = c.DeviceProduct()
572 }
Yu Liue4312402023-01-18 09:15:31 -0800573 dclaMixedBuildsEnabledList := []string{}
574 if c.BuildMode == BazelProdMode {
575 dclaMixedBuildsEnabledList = allowlists.ProdDclaMixedBuildsEnabledList
576 } else if c.BuildMode == BazelStagingMode {
577 dclaMixedBuildsEnabledList = append(allowlists.ProdDclaMixedBuildsEnabledList,
578 allowlists.StagingDclaMixedBuildsEnabledList...)
579 }
580 dclaEnabledModules := map[string]bool{}
Yu Liu6a7940c2023-05-09 17:12:22 -0700581 AddToStringSet(dclaEnabledModules, dclaMixedBuildsEnabledList)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800582 return &mixedBuildBazelContext{
Chris Parsons9402ca82023-02-23 17:28:06 -0500583 bazelRunner: &builtinBazelRunner{c.UseBazelProxy, absolutePath(c.outDir)},
Yu Liue4312402023-01-18 09:15:31 -0800584 paths: &paths,
Yu Liue4312402023-01-18 09:15:31 -0800585 bazelEnabledModules: enabledModules,
586 bazelDisabledModules: disabledModules,
587 bazelDclaEnabledModules: dclaEnabledModules,
588 targetProduct: targetProduct,
589 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400590 }, nil
591}
592
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400593func (p *bazelPaths) BazelMetricsDir() string {
594 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000595}
596
Yu Liue4312402023-01-18 09:15:31 -0800597func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string, withinApex bool) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400598 if context.bazelDisabledModules[moduleName] {
599 return false
600 }
601 if context.bazelEnabledModules[moduleName] {
602 return true
603 }
Spandan Das95b24b12023-06-26 22:39:19 +0000604 if withinApex && context.bazelDclaEnabledModules[moduleName] {
Yu Liue4312402023-01-18 09:15:31 -0800605 return true
606 }
607
Chris Parsons21f80272023-06-15 04:02:28 +0000608 return false
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400609}
610
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400611func pwdPrefix() string {
612 // Darwin doesn't have /proc
613 if runtime.GOOS != "darwin" {
614 return "PWD=/proc/self/cwd"
615 }
616 return ""
617}
618
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400619type bazelCommand struct {
620 command string
621 // query or label
622 expression string
623}
624
Chris Parsons9402ca82023-02-23 17:28:06 -0500625type builtinBazelRunner struct {
626 useBazelProxy bool
627 outDir string
628}
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400629
Chris Parsons808d84c2021-03-09 20:43:32 -0500630// Issues the given bazel command with given build label and additional flags.
631// Returns (stdout, stderr, error). The first and second return values are strings
632// containing the stdout and stderr of the run command, and an error is returned if
633// the invocation returned an error code.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000634func (r *builtinBazelRunner) issueBazelCommand(cmdRequest bazel.CmdRequest, paths *bazelPaths, eventHandler *metrics.EventHandler) (string, string, error) {
Chris Parsons9402ca82023-02-23 17:28:06 -0500635 if r.useBazelProxy {
636 eventHandler.Begin("client_proxy")
637 defer eventHandler.End("client_proxy")
638 proxyClient := bazel.NewProxyClient(r.outDir)
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000639 resp, err := proxyClient.IssueCommand(cmdRequest)
Chris Parsons9402ca82023-02-23 17:28:06 -0500640
641 if err != nil {
642 return "", "", err
643 }
644 if len(resp.ErrorString) > 0 {
645 return "", "", fmt.Errorf(resp.ErrorString)
646 }
647 return resp.Stdout, resp.Stderr, nil
Jason Wu52cd1942022-09-08 15:37:57 +0000648 } else {
Chris Parsons9402ca82023-02-23 17:28:06 -0500649 eventHandler.Begin("bazel command")
650 defer eventHandler.End("bazel command")
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000651
652 stdout, stderr, err := bazel.ExecBazel(paths.bazelPath, absolutePath(paths.syntheticWorkspaceDir()), cmdRequest)
653 return string(stdout), string(stderr), err
Jason Wu52cd1942022-09-08 15:37:57 +0000654 }
655}
656
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000657func (context *mixedBuildBazelContext) createBazelCommand(config Config, runName bazel.RunName, command bazelCommand,
658 extraFlags ...string) bazel.CmdRequest {
Cole Faust319abae2023-06-06 15:12:49 -0700659 if runtime.GOOS != "linux" && runtime.GOOS != "darwin" {
660 panic("Unknown GOOS: " + runtime.GOOS)
661 }
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000662 cmdFlags := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000663 "--output_base=" + absolutePath(context.paths.outputBase),
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000664 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700665 command.expression,
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000666 "--profile=" + shared.BazelMetricsFilename(context.paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400667
Cole Faustf3cf34e2023-09-20 17:02:40 -0700668 "--host_platform=@soong_injection//product_config_platforms:mixed_builds_product_" + runtime.GOOS + "_x86_64",
669 "--//build/bazel/product_config:target_build_variant=" + context.targetBuildVariant,
Cole Faust319abae2023-06-06 15:12:49 -0700670 // Don't specify --platforms, because on some products/branches (like kernel-build-tools)
671 // the main platform for mixed_builds_product-variant doesn't exist because an arch isn't
672 // specified in product config. The derivative platforms that config_node transitions into
673 // will still work.
Jingwen Chen583ab212023-05-30 09:45:23 +0000674
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700675 // Suppress noise
676 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500677 "--noshow_progress",
678 "--norun_validations",
679 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400680 cmdFlags = append(cmdFlags, extraFlags...)
681
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700682 extraEnv := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000683 "HOME=" + context.paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200684 pwdPrefix(),
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000685 "BUILD_DIR=" + absolutePath(context.paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700686 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000687 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000688 "OUT_DIR=" + absolutePath(context.paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500689 // Disables local host detection of gcc; toolchain information is defined
690 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700691 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
692 }
Cole Faust8a161be2023-06-14 15:45:12 -0700693 capturedEnvVars, err := starlark_import.GetStarlarkValue[[]string]("captured_env_vars")
694 if err != nil {
695 panic(err)
696 }
697 for _, envvar := range capturedEnvVars {
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500698 val := config.Getenv(envvar)
699 if val == "" {
700 continue
701 }
702 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
703 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000704 envVars := append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400705
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000706 return bazel.CmdRequest{cmdFlags, envVars}
Jason Wu52cd1942022-09-08 15:37:57 +0000707}
708
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000709func (context *mixedBuildBazelContext) printableCqueryCommand(bazelCmd bazel.CmdRequest) string {
710 args := append([]string{context.paths.bazelPath}, bazelCmd.Argv...)
711 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(args, "\" \"") + "\""
Jason Wu52cd1942022-09-08 15:37:57 +0000712 return outputString
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400713}
714
Sasha Smundak39a301c2022-12-29 17:11:49 -0800715func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500716 // TODO(cparsons): Define configuration transitions programmatically based
717 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400718 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500719#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400720# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500721#####################################################
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400722def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800723 if attr.os == "android" and attr.arch == "target":
Cole Faustf3cf34e2023-09-20 17:02:40 -0700724 target = "mixed_builds_product"
Cole Faustb85d1a12022-11-08 18:14:01 -0800725 else:
Cole Faustf3cf34e2023-09-20 17:02:40 -0700726 target = "mixed_builds_product_%s_%s" % (attr.os, attr.arch)
Yu Liue4312402023-01-18 09:15:31 -0800727 apex_name = ""
728 if attr.within_apex:
729 # //build/bazel/rules/apex:apex_name has to be set to a non_empty value,
730 # otherwise //build/bazel/rules/apex:non_apex will be true and the
731 # "-D__ANDROID_APEX__" compiler flag will be missing. Apex_name is used
732 # in some validation on bazel side which don't really apply in mixed
733 # build because soong will do the work, so we just set it to a fixed
734 # value here.
735 apex_name = "dcla_apex"
736 outputs = {
Jingwen Chen583ab212023-05-30 09:45:23 +0000737 "//command_line_option:platforms": "@soong_injection//product_config_platforms:%s" % target,
Yu Liue4312402023-01-18 09:15:31 -0800738 "@//build/bazel/rules/apex:within_apex": attr.within_apex,
739 "@//build/bazel/rules/apex:min_sdk_version": attr.apex_sdk_version,
740 "@//build/bazel/rules/apex:apex_name": apex_name,
Spandan Das40b79f82023-06-25 20:56:06 +0000741 "@//build/bazel/rules/apex:api_domain": attr.api_domain,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500742 }
743
Yu Liue4312402023-01-18 09:15:31 -0800744 return outputs
745
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400746_config_node_transition = transition(
747 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500748 inputs = [],
749 outputs = [
750 "//command_line_option:platforms",
Yu Liue4312402023-01-18 09:15:31 -0800751 "@//build/bazel/rules/apex:within_apex",
752 "@//build/bazel/rules/apex:min_sdk_version",
753 "@//build/bazel/rules/apex:apex_name",
Spandan Das40b79f82023-06-25 20:56:06 +0000754 "@//build/bazel/rules/apex:api_domain",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500755 ],
756)
757
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400758def _passthrough_rule_impl(ctx):
759 return [DefaultInfo(files = depset(ctx.files.deps))]
760
761config_node = rule(
762 implementation = _passthrough_rule_impl,
763 attrs = {
Yu Liue4312402023-01-18 09:15:31 -0800764 "arch" : attr.string(mandatory = True),
765 "os" : attr.string(mandatory = True),
766 "within_apex" : attr.bool(default = False),
767 "apex_sdk_version" : attr.string(mandatory = True),
Spandan Das40b79f82023-06-25 20:56:06 +0000768 "api_domain" : attr.string(mandatory = True),
Yu Liue4312402023-01-18 09:15:31 -0800769 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400770 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
771 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500772)
773
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400774
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500775# Rule representing the root of the build, to depend on all Bazel targets that
776# are required for the build. Building this target will build the entire Bazel
777# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400778mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400779 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500780 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400781 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500782 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400783)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500784
785def _phony_root_impl(ctx):
786 return []
787
788# Rule to depend on other targets but build nothing.
789# This is useful as follows: building a target of this rule will generate
790# symlink forests for all dependencies of the target, without executing any
791# actions of the build.
792phony_root = rule(
793 implementation = _phony_root_impl,
794 attrs = {"deps" : attr.label_list()},
795)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400796`
Cole Faustb85d1a12022-11-08 18:14:01 -0800797
Cole Faustf3cf34e2023-09-20 17:02:40 -0700798 return []byte(contents)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400799}
800
Sasha Smundak39a301c2022-12-29 17:11:49 -0800801func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500802 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
803 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400804 formatString := `
805# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400806load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
807
808%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400809
810mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400811 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000812 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400813)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500814
815phony_root(name = "phonyroot",
816 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000817 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500818)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400819`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400820 configNodeFormatString := `
821config_node(name = "%s",
822 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400823 os = "%s",
Yu Liue4312402023-01-18 09:15:31 -0800824 within_apex = %s,
825 apex_sdk_version = "%s",
Spandan Das40b79f82023-06-25 20:56:06 +0000826 api_domain = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400827 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000828 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400829)
830`
831
832 configNodesSection := ""
833
Chris Parsons787fb362021-10-14 18:43:51 -0400834 labelsByConfig := map[string][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500835
836 for _, val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200837 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400838 configString := getConfigString(val)
839 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400840 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400841
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500842 // Configs need to be sorted to maintain determinism of the BUILD file.
843 sortedConfigs := make([]string, 0, len(labelsByConfig))
844 for val := range labelsByConfig {
845 sortedConfigs = append(sortedConfigs, val)
846 }
847 sort.Slice(sortedConfigs, func(i, j int) bool { return sortedConfigs[i] < sortedConfigs[j] })
848
Jingwen Chen1e347862021-09-02 12:11:49 +0000849 allLabels := []string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500850 for _, configString := range sortedConfigs {
851 labels := labelsByConfig[configString]
Chris Parsons787fb362021-10-14 18:43:51 -0400852 configTokens := strings.Split(configString, "|")
Yu Liue4312402023-01-18 09:15:31 -0800853 if len(configTokens) < 2 {
Chris Parsons787fb362021-10-14 18:43:51 -0400854 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000855 }
Chris Parsons787fb362021-10-14 18:43:51 -0400856 archString := configTokens[0]
857 osString := configTokens[1]
Yu Liue4312402023-01-18 09:15:31 -0800858 withinApex := "False"
859 apexSdkVerString := ""
Spandan Das40b79f82023-06-25 20:56:06 +0000860 apiDomainString := ""
861 if osString == "android" {
862 // api domains are meaningful only for device variants
863 apiDomainString = "system"
864 }
Chris Parsons787fb362021-10-14 18:43:51 -0400865 targetString := fmt.Sprintf("%s_%s", osString, archString)
Yu Liue4312402023-01-18 09:15:31 -0800866 if len(configTokens) > 2 {
867 targetString += "_" + configTokens[2]
868 if configTokens[2] == withinApexToString(true) {
869 withinApex = "True"
870 }
871 }
872 if len(configTokens) > 3 {
873 targetString += "_" + configTokens[3]
874 apexSdkVerString = configTokens[3]
875 }
Spandan Das40b79f82023-06-25 20:56:06 +0000876 if len(configTokens) > 4 {
877 apiDomainString = configTokens[4]
878 targetString += "_" + apiDomainString
879 }
Chris Parsons787fb362021-10-14 18:43:51 -0400880 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
881 labelsString := strings.Join(labels, ",\n ")
Spandan Das40b79f82023-06-25 20:56:06 +0000882 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, withinApex, apexSdkVerString, apiDomainString,
Yu Liue4312402023-01-18 09:15:31 -0800883 labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400884 }
885
Jingwen Chen1e347862021-09-02 12:11:49 +0000886 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400887}
888
Chris Parsons944e7d02021-03-11 11:08:46 -0500889func indent(original string) string {
890 result := ""
891 for _, line := range strings.Split(original, "\n") {
892 result += " " + line + "\n"
893 }
894 return result
895}
896
Chris Parsons808d84c2021-03-09 20:43:32 -0500897// Returns the file contents of the buildroot.cquery file that should be used for the cquery
898// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800899// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500900// and grouped by their request type. The data retrieved for each label depends on its
901// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800902func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400903 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons38851d82023-03-15 00:19:32 -0400904 requestTypes := []cqueryRequest{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500905 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500906 cqueryId := getCqueryId(val)
907 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
Chris Parsons38851d82023-03-15 00:19:32 -0400908 if _, seenKey := requestTypeToCqueryIdEntries[val.requestType]; !seenKey {
909 requestTypes = append(requestTypes, val.requestType)
910 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500911 requestTypeToCqueryIdEntries[val.requestType] =
912 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
913 }
914 labelRegistrationMapSection := ""
915 functionDefSection := ""
916 mainSwitchSection := ""
917
918 mapDeclarationFormatString := `
919%s = {
920 %s
921}
922`
923 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800924def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500925%s
926`
927 mainSwitchSectionFormatString := `
928 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800929 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500930`
931
Chris Parsons38851d82023-03-15 00:19:32 -0400932 for _, requestType := range requestTypes {
Chris Parsons944e7d02021-03-11 11:08:46 -0500933 labelMapName := requestType.Name() + "_Labels"
934 functionName := requestType.Name() + "_Fn"
935 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
936 labelMapName,
937 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
938 functionDefSection += fmt.Sprintf(functionDefFormatString,
939 functionName,
940 indent(requestType.StarlarkFunctionBody()))
941 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
942 labelMapName, functionName)
943 }
944
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400945 formatString := `
946# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400947
Cole Faustb85d1a12022-11-08 18:14:01 -0800948{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500949
Cole Faustb85d1a12022-11-08 18:14:01 -0800950{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500951
952def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400953 # TODO(b/199363072): filegroups and file targets aren't associated with any
954 # specific platform architecture in mixed builds. This is consistent with how
955 # Soong treats filegroups, but it may not be the case with manually-written
956 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500957 buildoptions = build_options(target)
Yu Liue4312402023-01-18 09:15:31 -0800958
Jingwen Chen8f222742021-10-07 12:02:23 +0000959 if buildoptions == None:
960 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400961 # any specific platform architecture in mixed builds, so use the host.
962 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -0800963 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500964 if len(platforms) != 1:
965 # An individual configured target should have only one platform architecture.
966 # Note that it's fine for there to be multiple architectures for the same label,
967 # but each is its own configured target.
968 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -0800969 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -0500970 if platform_name == "host":
971 return "HOST"
Cole Faustf3cf34e2023-09-20 17:02:40 -0700972 if not platform_name.startswith("mixed_builds_product"):
973 fail("expected platform name of the form 'mixed_builds_product_android_<arch>' or 'mixed_builds_product_linux_<arch>', but was " + str(platforms))
974 platform_name = platform_name.removeprefix("mixed_builds_product").removeprefix("_")
Yu Liue4312402023-01-18 09:15:31 -0800975 config_key = ""
Cole Faustb85d1a12022-11-08 18:14:01 -0800976 if not platform_name:
Yu Liue4312402023-01-18 09:15:31 -0800977 config_key = "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400978 elif platform_name.startswith("android_"):
Yu Liue4312402023-01-18 09:15:31 -0800979 config_key = platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400980 elif platform_name.startswith("linux_"):
Yu Liue4312402023-01-18 09:15:31 -0800981 config_key = platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400982 else:
Cole Faustf3cf34e2023-09-20 17:02:40 -0700983 fail("expected platform name of the form 'mixed_builds_product_android_<arch>' or 'mixed_builds_product_linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500984
Yu Liue4312402023-01-18 09:15:31 -0800985 within_apex = buildoptions.get("//build/bazel/rules/apex:within_apex")
986 apex_sdk_version = buildoptions.get("//build/bazel/rules/apex:min_sdk_version")
Spandan Das40b79f82023-06-25 20:56:06 +0000987 api_domain = buildoptions.get("//build/bazel/rules/apex:api_domain")
Yu Liue4312402023-01-18 09:15:31 -0800988
989 if within_apex:
990 config_key += "|within_apex"
991 if apex_sdk_version != None and len(apex_sdk_version) > 0:
992 config_key += "|" + apex_sdk_version
Spandan Das40b79f82023-06-25 20:56:06 +0000993 if api_domain != None and len(api_domain) > 0:
994 config_key += "|" + api_domain
Yu Liue4312402023-01-18 09:15:31 -0800995
996 return config_key
997
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400998def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500999 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -05001000
Chris Parsons86dc2c22022-09-28 14:58:41 -04001001 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
1002 if id_string.startswith("//"):
1003 id_string = "@" + id_string
1004
Cole Faustb85d1a12022-11-08 18:14:01 -08001005 {MAIN_SWITCH_SECTION}
1006
Chris Parsons944e7d02021-03-11 11:08:46 -05001007 # This target was not requested via cquery, and thus must be a dependency
1008 # of a requested target.
1009 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001010`
Cole Faustb85d1a12022-11-08 18:14:01 -08001011 replacer := strings.NewReplacer(
Cole Faustb85d1a12022-11-08 18:14:01 -08001012 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
1013 "{FUNCTION_DEF_SECTION}", functionDefSection,
1014 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001015
Cole Faustb85d1a12022-11-08 18:14:01 -08001016 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001017}
1018
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001019// Returns a path containing build-related metadata required for interfacing
1020// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001021func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001022 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -05001023}
1024
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001025// Returns the path where the contents of the @soong_injection repository live.
1026// It is used by Soong to tell Bazel things it cannot over the command line.
1027func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001028 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001029}
1030
1031// Returns the path of the synthetic Bazel workspace that contains a symlink
1032// forest composed the whole source tree and BUILD files generated by bp2build.
1033func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001034 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001035}
1036
Jingwen Chen8c523582021-06-01 11:19:53 +00001037// Returns the path to the top level out dir ($OUT_DIR).
1038func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001039 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +00001040}
1041
Sasha Smundak4975c822022-11-16 15:28:18 -08001042const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
1043
1044var (
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001045 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
1046 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
1047 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
1048 allBazelCommands = []bazelCommand{aqueryCmd, cqueryCmd, buildCmd}
Sasha Smundak4975c822022-11-16 15:28:18 -08001049)
1050
Cole Faustcb193ec2023-09-20 16:01:18 -07001051// This can't be part of bp2build_product_config.go because it would create a circular go package dependency
1052func getLabelsForBazelSandwichPartitions(variables *ProductVariables) []string {
1053 targetProduct := "unknown"
1054 if variables.DeviceProduct != nil {
1055 targetProduct = *variables.DeviceProduct
1056 }
1057 currentProductFolder := fmt.Sprintf("build/bazel/products/%s", targetProduct)
1058 if len(variables.PartitionVarsForBazelMigrationOnlyDoNotUse.ProductDirectory) > 0 {
1059 currentProductFolder = fmt.Sprintf("%s%s", variables.PartitionVarsForBazelMigrationOnlyDoNotUse.ProductDirectory, targetProduct)
1060 }
1061 var ret []string
1062 if variables.PartitionVarsForBazelMigrationOnlyDoNotUse.PartitionQualifiedVariables["system"].BuildingImage {
1063 ret = append(ret, "@//"+currentProductFolder+":system_image")
1064 ret = append(ret, "@//"+currentProductFolder+":run_system_image_test")
1065 }
1066 return ret
1067}
1068
Cole Faustbc65a3f2023-08-01 16:38:55 +00001069func GetBazelSandwichCqueryRequests(config Config) ([]cqueryKey, error) {
Cole Faustcb193ec2023-09-20 16:01:18 -07001070 partitionLabels := getLabelsForBazelSandwichPartitions(&config.productVariables)
1071 result := make([]cqueryKey, 0, len(partitionLabels))
Cole Faust16d10942023-08-02 11:45:43 -07001072 labelRegex := regexp.MustCompile("^@?//([a-zA-Z0-9/_-]+):[a-zA-Z0-9_-]+$")
Cole Faustbc65a3f2023-08-01 16:38:55 +00001073 // Note that bazel "targets" are different from soong "targets", the bazel targets are
1074 // synonymous with soong modules, and soong targets are a configuration a module is built in.
Cole Faustcb193ec2023-09-20 16:01:18 -07001075 for _, target := range partitionLabels {
1076 match := labelRegex.FindStringSubmatch(target)
Cole Faust16d10942023-08-02 11:45:43 -07001077 if match == nil {
Cole Faustcb193ec2023-09-20 16:01:18 -07001078 return nil, fmt.Errorf("invalid label, must match `^@?//([a-zA-Z0-9/_-]+):[a-zA-Z0-9_-]+$`: %s", target)
Cole Faust16d10942023-08-02 11:45:43 -07001079 }
1080
Cole Faustcb193ec2023-09-20 16:01:18 -07001081 // change this to config.BuildOSTarget if we add host targets
1082 soongTarget := config.AndroidCommonTarget
1083 if soongTarget.Os.Class != Device {
1084 // kernel-build-tools seems to set the AndroidCommonTarget to a linux host
1085 // target for some reason, disable device builds in that case.
1086 continue
Cole Faustbc65a3f2023-08-01 16:38:55 +00001087 }
1088
1089 result = append(result, cqueryKey{
Cole Faustcb193ec2023-09-20 16:01:18 -07001090 label: target,
Cole Faustbc65a3f2023-08-01 16:38:55 +00001091 requestType: cquery.GetOutputFiles,
1092 configKey: configKey{
1093 arch: soongTarget.Arch.String(),
1094 osType: soongTarget.Os,
1095 },
1096 })
1097 }
1098 return result, nil
1099}
1100
1101// QueueBazelSandwichCqueryRequests queues cquery requests for all the bazel labels in
1102// bazel_sandwich_targets. These will later be given phony targets so that they can be built on the
1103// command line.
1104func (context *mixedBuildBazelContext) QueueBazelSandwichCqueryRequests(config Config) error {
1105 requests, err := GetBazelSandwichCqueryRequests(config)
1106 if err != nil {
1107 return err
1108 }
1109 for _, request := range requests {
1110 context.QueueBazelRequest(request.label, request.requestType, request.configKey)
1111 }
1112
1113 return nil
1114}
1115
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001116// Issues commands to Bazel to receive results for all cquery requests
1117// queued in the BazelContext.
Liz Kammer690fbac2023-02-10 11:11:17 -05001118func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx invokeBazelContext) error {
1119 eventHandler := ctx.GetEventHandler()
1120 eventHandler.Begin("bazel")
1121 defer eventHandler.End("bazel")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001122
Sasha Smundak4975c822022-11-16 15:28:18 -08001123 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
1124 if err := os.MkdirAll(metricsDir, 0777); err != nil {
1125 return err
1126 }
1127 }
1128 context.results = make(map[cqueryKey]string)
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001129 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001130 return err
1131 }
1132 if err := context.runAquery(config, ctx); err != nil {
1133 return err
1134 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001135 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001136 return err
1137 }
1138
1139 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001140 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -08001141 return nil
1142}
1143
Liz Kammer690fbac2023-02-10 11:11:17 -05001144func (context *mixedBuildBazelContext) runCquery(config Config, ctx invokeBazelContext) error {
1145 eventHandler := ctx.GetEventHandler()
1146 eventHandler.Begin("cquery")
1147 defer eventHandler.End("cquery")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001148 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +02001149 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
1150 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
1151 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -05001152 if err != nil {
1153 return err
1154 }
1155 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001156 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001157 return err
1158 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001159 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001160 return err
1161 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001162 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001163 return err
1164 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001165 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001166 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001167 return err
1168 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001169
Yu Liue4312402023-01-18 09:15:31 -08001170 extraFlags := []string{"--output=starlark", "--starlark:file=" + absolutePath(cqueryFileRelpath)}
1171 if Bool(config.productVariables.ClangCoverage) {
1172 extraFlags = append(extraFlags, "--collect_code_coverage")
1173 }
1174
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001175 cqueryCmdRequest := context.createBazelCommand(config, bazel.CqueryBuildRootRunName, cqueryCmd, extraFlags...)
1176 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCmdRequest, context.paths, eventHandler)
Wei Licbd181c2022-11-16 08:59:23 -08001177 if cqueryErr != nil {
1178 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001179 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001180 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", context.printableCqueryCommand(cqueryCmdRequest))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001181 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001182 return err
1183 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001184 cqueryResults := map[string]string{}
1185 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1186 if strings.Contains(outputLine, ">>") {
1187 splitLine := strings.SplitN(outputLine, ">>", 2)
1188 cqueryResults[splitLine[0]] = splitLine[1]
1189 }
1190 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001191 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001192 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001193 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001194 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001195 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001196 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001197 }
1198 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001199 return nil
1200}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001201
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001202func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1203 oldContents, err := os.ReadFile(path)
1204 if err != nil || !bytes.Equal(contents, oldContents) {
1205 err = os.WriteFile(path, contents, perm)
1206 }
1207 return nil
1208}
1209
Liz Kammer690fbac2023-02-10 11:11:17 -05001210func (context *mixedBuildBazelContext) runAquery(config Config, ctx invokeBazelContext) error {
1211 eventHandler := ctx.GetEventHandler()
1212 eventHandler.Begin("aquery")
1213 defer eventHandler.End("aquery")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001214 // Issue an aquery command to retrieve action information about the bazel build tree.
1215 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001216 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1217 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001218 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001219 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001220 extraFlags = append(extraFlags, "--collect_code_coverage")
1221 paths := make([]string, 0, 2)
1222 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001223 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001224 // TODO(b/259404593) convert path wildcard to regex values
1225 if p[i] == "*" {
1226 p[i] = ".*"
1227 }
1228 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001229 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1230 }
1231 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1232 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1233 }
1234 if len(paths) > 0 {
1235 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001236 }
1237 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001238 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.AqueryBuildRootRunName, aqueryCmd,
1239 extraFlags...), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001240 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001241 return err
1242 }
Liz Kammer690fbac2023-02-10 11:11:17 -05001243 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001244 return err
1245}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001246
Liz Kammer690fbac2023-02-10 11:11:17 -05001247func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx invokeBazelContext) error {
1248 eventHandler := ctx.GetEventHandler()
1249 eventHandler.Begin("symlinks")
1250 defer eventHandler.End("symlinks")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001251 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1252 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1253 // but some of symlinks may be required to resolve source dependencies of the build.
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001254 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.BazelBuildPhonyRootRunName, buildCmd), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001255 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001256}
Chris Parsonsa798d962020-10-12 23:44:08 -04001257
Liz Kammera4655a92023-02-10 17:17:28 -05001258func (context *mixedBuildBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001259 return context.buildStatements
1260}
1261
Sasha Smundak39a301c2022-12-29 17:11:49 -08001262func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001263 return context.depsets
1264}
1265
Sasha Smundak39a301c2022-12-29 17:11:49 -08001266func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001267 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001268}
1269
Chris Parsonsa798d962020-10-12 23:44:08 -04001270// Singleton used for registering BUILD file ninja dependencies (needed
1271// for correctness of builds which use Bazel.
1272func BazelSingleton() Singleton {
1273 return &bazelSingleton{}
1274}
1275
1276type bazelSingleton struct{}
1277
1278func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001279 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001280 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001281 return
1282 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001283
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001284 // Add ninja file dependencies for files which all bazel invocations require.
1285 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001286 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001287 ctx.AddNinjaFileDeps(bazelBuildList)
1288
Sasha Smundak0e87b182022-12-01 11:46:11 -08001289 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001290 if err != nil {
1291 ctx.Errorf(err.Error())
1292 }
1293 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1294 for _, file := range files {
1295 ctx.AddNinjaFileDeps(file)
1296 }
1297
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001298 depsetHashToDepset := map[string]bazel.AqueryDepset{}
1299
Chris Parsons1a7aca02022-04-25 22:35:15 -04001300 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001301 depsetHashToDepset[depset.ContentHash] = depset
1302
Chris Parsons1a7aca02022-04-25 22:35:15 -04001303 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001304 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001305 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1306 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001307 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1308 }
1309 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001310 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1311 if artifactPath == "bazel-out/volatile-status.txt" {
1312 // See https://bazel.build/docs/user-manual#workspace-status
1313 orderOnlies = append(orderOnlies, pathInBazelOut)
1314 } else {
1315 outputs = append(outputs, pathInBazelOut)
1316 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001317 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001318 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001319 ctx.Build(pctx, BuildParams{
1320 Rule: blueprint.Phony,
1321 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1322 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001323 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001324 })
1325 }
1326
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001327 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1328 bazelOutDir := path.Join(executionRoot, "bazel-out")
Cole Faustbc65a3f2023-08-01 16:38:55 +00001329 rel, err := filepath.Rel(ctx.Config().OutDir(), executionRoot)
1330 if err != nil {
1331 ctx.Errorf("%s", err.Error())
1332 }
1333 dotdotsToOutRoot := strings.Repeat("../", strings.Count(rel, "/")+1)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001334 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Liz Kammera4655a92023-02-10 17:17:28 -05001335 // nil build statements are a valid case where we do not create an action because it is
1336 // unnecessary or handled by other processing
1337 if buildStatement == nil {
1338 continue
1339 }
Sasha Smundak1da064c2022-06-08 16:36:16 -07001340 if len(buildStatement.Command) > 0 {
1341 rule := NewRuleBuilder(pctx, ctx)
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001342 intermediateDir, intermediateDirHash := intermediatePathForSboxMixedBuildAction(ctx, buildStatement)
1343 if buildStatement.ShouldRunInSbox {
1344 // Create a rule to build the output inside a sandbox
1345 // This will create two changes of working directory
1346 // 1. From ANDROID_BUILD_TOP to sbox top
1347 // 2. From sbox top to a a synthetic mixed build execution root relative to it
1348 // Finally, the outputs will be copied to intermediateDir
1349 rule.Sbox(intermediateDir,
1350 PathForOutput(ctx, "mixed_build_sbox_intermediates", intermediateDirHash+".textproto")).
1351 SandboxInputs().
1352 // Since we will cd to mixed build execution root, set sbox's out subdir to empty
1353 // Without this, we will try to copy from $SBOX_SANDBOX_DIR/out/out/bazel/output/execroot/__main__/...
1354 SetSboxOutDirDirAsEmpty()
1355
1356 // Create another set of rules to copy files from the intermediate dir to mixed build execution root
1357 for _, outputPath := range buildStatement.OutputPaths {
1358 ctx.Build(pctx, BuildParams{
1359 Rule: CpIfChanged,
1360 Input: intermediateDir.Join(ctx, executionRoot, outputPath),
1361 Output: PathForBazelOut(ctx, outputPath),
1362 })
1363 }
1364 }
Cole Faustbc65a3f2023-08-01 16:38:55 +00001365 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx, depsetHashToDepset, dotdotsToOutRoot)
1366
Sasha Smundak1da064c2022-06-08 16:36:16 -07001367 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1368 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1369 continue
1370 }
1371 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1372 // and thus require special treatment. If BuildStatement were an interface implementing
1373 // buildRule(ctx) function, the code here would just call it.
1374 // Unfortunately, the BuildStatement is defined in
1375 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1376 // because this would cause circular dependency. So, until we move aquery processing
1377 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001378 switch buildStatement.Mnemonic {
Cole Faust950689a2023-06-21 15:07:21 -07001379 case "RepoMappingManifest":
1380 // It appears RepoMappingManifest files currently have
1381 // non-deterministic content. Just emit empty files for
1382 // now because they're unused.
1383 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1384 WriteFileRuleVerbatim(ctx, out, "")
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001385 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001386 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
Cole Faust20f20302023-08-31 11:00:25 -07001387 if buildStatement.IsExecutable {
Cole Faust39b614a2023-08-23 16:11:26 -07001388 WriteExecutableFileRuleVerbatim(ctx, out, buildStatement.FileContents)
1389 } else {
1390 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
1391 }
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001392 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001393 // build-runfiles arguments are the manifest file and the target directory
1394 // where it creates the symlink tree according to this manifest (and then
1395 // writes the MANIFEST file to it).
1396 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1397 outManifestPath := outManifest.String()
1398 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1399 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1400 }
1401 outDir := filepath.Dir(outManifestPath)
1402 ctx.Build(pctx, BuildParams{
1403 Rule: buildRunfilesRule,
1404 Output: outManifest,
1405 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1406 Description: "symlink tree for " + outDir,
1407 Args: map[string]string{
1408 "outDir": outDir,
1409 },
1410 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001411 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001412 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001413 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001414 }
Cole Faustbc65a3f2023-08-01 16:38:55 +00001415
1416 // Create phony targets for all the bazel sandwich output files
1417 requests, err := GetBazelSandwichCqueryRequests(ctx.Config())
1418 if err != nil {
1419 ctx.Errorf(err.Error())
1420 }
1421 for _, request := range requests {
1422 files, err := ctx.Config().BazelContext.GetOutputFiles(request.label, request.configKey)
1423 if err != nil {
1424 ctx.Errorf(err.Error())
1425 }
1426 filesAsPaths := make([]Path, 0, len(files))
1427 for _, file := range files {
1428 filesAsPaths = append(filesAsPaths, PathForBazelOut(ctx, file))
1429 }
1430 ctx.Phony("bazel_sandwich", filesAsPaths...)
1431 }
1432 ctx.Phony("checkbuild", PathForPhony(ctx, "bazel_sandwich"))
Chris Parsonsa798d962020-10-12 23:44:08 -04001433}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001434
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001435// Returns a out dir path for a sandboxed mixed build action
1436func intermediatePathForSboxMixedBuildAction(ctx PathContext, statement *bazel.BuildStatement) (OutputPath, string) {
1437 // An artifact can be generated by a single buildstatement.
1438 // Use the hash of the first artifact to create a unique path
1439 uniqueDir := sha1.New()
1440 uniqueDir.Write([]byte(statement.OutputPaths[0]))
1441 uniqueDirHashString := hex.EncodeToString(uniqueDir.Sum(nil))
1442 return PathForOutput(ctx, "mixed_build_sbox_intermediates", uniqueDirHashString), uniqueDirHashString
1443}
1444
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001445// Register bazel-owned build statements (obtained from the aquery invocation).
Cole Faustbc65a3f2023-08-01 16:38:55 +00001446func createCommand(cmd *RuleBuilderCommand, buildStatement *bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext, depsetHashToDepset map[string]bazel.AqueryDepset, dotdotsToOutRoot string) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001447 // executionRoot is the action cwd.
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001448 if buildStatement.ShouldRunInSbox {
1449 // mkdir -p ensures that the directory exists when run via sbox
1450 cmd.Text(fmt.Sprintf("mkdir -p '%s' && cd '%s' &&", executionRoot, executionRoot))
1451 } else {
1452 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1453 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001454
1455 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1456 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001457 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001458 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001459 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001460 }
1461 cmd.Text("&&")
1462 }
1463
1464 for _, pair := range buildStatement.Env {
1465 // Set per-action env variables, if any.
1466 cmd.Flag(pair.Key + "=" + pair.Value)
1467 }
1468
Cole Faustbc65a3f2023-08-01 16:38:55 +00001469 command := buildStatement.Command
1470 command = strings.ReplaceAll(command, "{DOTDOTS_TO_OUTPUT_ROOT}", dotdotsToOutRoot)
1471
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001472 // The actual Bazel action.
Cole Faustbc65a3f2023-08-01 16:38:55 +00001473 if len(command) > 16*1024 {
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001474 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
Cole Faustbc65a3f2023-08-01 16:38:55 +00001475 WriteFileRule(ctx, commandFile, command)
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001476
1477 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1478 } else {
Cole Faustbc65a3f2023-08-01 16:38:55 +00001479 cmd.Text(command)
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001480 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001481
1482 for _, outputPath := range buildStatement.OutputPaths {
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001483 if buildStatement.ShouldRunInSbox {
1484 // The full path has three components that get joined together
1485 // 1. intermediate output dir that `sbox` will place the artifacts at
1486 // 2. mixed build execution root
1487 // 3. artifact path returned by aquery
1488 intermediateDir, _ := intermediatePathForSboxMixedBuildAction(ctx, buildStatement)
1489 cmd.ImplicitOutput(intermediateDir.Join(ctx, executionRoot, outputPath))
1490 } else {
1491 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1492 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001493 }
1494 for _, inputPath := range buildStatement.InputPaths {
1495 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1496 }
1497 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001498 if buildStatement.ShouldRunInSbox {
1499 // Bazel depsets are phony targets that are used to group files.
1500 // We need to copy the grouped files into the sandbox
1501 ds, _ := depsetHashToDepset[inputDepsetHash]
1502 cmd.Implicits(PathsForBazelOut(ctx, ds.DirectArtifacts))
1503 } else {
1504 otherDepsetName := bazelDepsetName(inputDepsetHash)
1505 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1506 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001507 }
Cole Faustbc65a3f2023-08-01 16:38:55 +00001508 for _, implicitPath := range buildStatement.ImplicitDeps {
1509 cmd.Implicit(PathForArbitraryOutput(ctx, implicitPath))
1510 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001511
1512 if depfile := buildStatement.Depfile; depfile != nil {
1513 // The paths in depfile are relative to `executionRoot`.
1514 // Hence, they need to be corrected by replacing "bazel-out"
1515 // with the full `bazelOutDir`.
1516 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1517 // would be deemed missing.
1518 // (Note: The regexp uses a capture group because the version of sed
1519 // does not support a look-behind pattern.)
1520 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1521 bazelOutDir, *depfile)
1522 cmd.Text(replacement)
1523 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1524 }
1525
1526 for _, symlinkPath := range buildStatement.SymlinkPaths {
1527 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1528 }
1529}
1530
Chris Parsons8d6e4332021-02-22 16:13:50 -05001531func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001532 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001533}
1534
Chris Parsons787fb362021-10-14 18:43:51 -04001535func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001536 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001537 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001538 if key.configKey.osType.Class == Device {
1539 // For the generic Android, the expected result is "target|android", which
1540 // corresponds to the product_variable_config named "android_target" in
1541 // build/bazel/platforms/BUILD.bazel.
1542 arch = "target"
1543 } else {
1544 // Use host platform, which is currently hardcoded to be x86_64.
1545 arch = "x86_64"
1546 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001547 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001548 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001549 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001550 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001551 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001552 }
Yu Liue4312402023-01-18 09:15:31 -08001553 keyString := arch + "|" + osName
1554 if key.configKey.apexKey.WithinApex {
1555 keyString += "|" + withinApexToString(key.configKey.apexKey.WithinApex)
1556 }
1557
1558 if len(key.configKey.apexKey.ApexSdkVersion) > 0 {
1559 keyString += "|" + key.configKey.apexKey.ApexSdkVersion
1560 }
1561
Spandan Das40b79f82023-06-25 20:56:06 +00001562 if len(key.configKey.apexKey.ApiDomain) > 0 {
1563 keyString += "|" + key.configKey.apexKey.ApiDomain
1564 }
1565
Yu Liue4312402023-01-18 09:15:31 -08001566 return keyString
Chris Parsons787fb362021-10-14 18:43:51 -04001567}
1568
Chris Parsonsf874e462022-05-10 13:50:12 -04001569func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001570 return configKey{
1571 // use string because Arch is not a valid key in go
1572 arch: ctx.Arch().String(),
1573 osType: ctx.Os(),
1574 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001575}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001576
Yu Liue4312402023-01-18 09:15:31 -08001577func GetConfigKeyApexVariant(ctx BaseModuleContext, apexKey *ApexConfigKey) configKey {
1578 configKey := GetConfigKey(ctx)
1579
1580 if apexKey != nil {
1581 configKey.apexKey = ApexConfigKey{
1582 WithinApex: apexKey.WithinApex,
1583 ApexSdkVersion: apexKey.ApexSdkVersion,
Spandan Das40b79f82023-06-25 20:56:06 +00001584 ApiDomain: apexKey.ApiDomain,
Yu Liue4312402023-01-18 09:15:31 -08001585 }
1586 }
1587
1588 return configKey
1589}
1590
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001591func bazelDepsetName(contentHash string) string {
1592 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001593}