blob: 4b983456449560cad3f9d31d5f86a6191bed47f1 [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
Chris Parsons1a7aca02022-04-25 22:35:15 -040036 "github.com/google/blueprint"
Liz Kammer690fbac2023-02-10 11:11:17 -050037 "github.com/google/blueprint/metrics"
Liz Kammer8206d4f2021-03-03 16:40:52 -050038
Patrice Arruda05ab2d02020-12-12 06:24:26 +000039 "android/soong/bazel"
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 Faust319abae2023-06-06 15:12:49 -0700668 "--host_platform=@soong_injection//product_config_platforms:mixed_builds_product-" + context.targetBuildVariant + "_" + runtime.GOOS + "_x86_64",
669 // Don't specify --platforms, because on some products/branches (like kernel-build-tools)
670 // the main platform for mixed_builds_product-variant doesn't exist because an arch isn't
671 // specified in product config. The derivative platforms that config_node transitions into
672 // will still work.
Jingwen Chen583ab212023-05-30 09:45:23 +0000673
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700674 // Suppress noise
675 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500676 "--noshow_progress",
677 "--norun_validations",
678 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400679 cmdFlags = append(cmdFlags, extraFlags...)
680
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700681 extraEnv := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000682 "HOME=" + context.paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200683 pwdPrefix(),
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000684 "BUILD_DIR=" + absolutePath(context.paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700685 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000686 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000687 "OUT_DIR=" + absolutePath(context.paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500688 // Disables local host detection of gcc; toolchain information is defined
689 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700690 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
691 }
Cole Faust8a161be2023-06-14 15:45:12 -0700692 capturedEnvVars, err := starlark_import.GetStarlarkValue[[]string]("captured_env_vars")
693 if err != nil {
694 panic(err)
695 }
696 for _, envvar := range capturedEnvVars {
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500697 val := config.Getenv(envvar)
698 if val == "" {
699 continue
700 }
701 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
702 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000703 envVars := append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400704
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000705 return bazel.CmdRequest{cmdFlags, envVars}
Jason Wu52cd1942022-09-08 15:37:57 +0000706}
707
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000708func (context *mixedBuildBazelContext) printableCqueryCommand(bazelCmd bazel.CmdRequest) string {
709 args := append([]string{context.paths.bazelPath}, bazelCmd.Argv...)
710 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(args, "\" \"") + "\""
Jason Wu52cd1942022-09-08 15:37:57 +0000711 return outputString
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400712}
713
Sasha Smundak39a301c2022-12-29 17:11:49 -0800714func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500715 // TODO(cparsons): Define configuration transitions programmatically based
716 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400717 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500718#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400719# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500720#####################################################
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400721def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800722 if attr.os == "android" and attr.arch == "target":
Cole Faust319abae2023-06-06 15:12:49 -0700723 target = "mixed_builds_product-{VARIANT}"
Cole Faustb85d1a12022-11-08 18:14:01 -0800724 else:
Cole Faust319abae2023-06-06 15:12:49 -0700725 target = "mixed_builds_product-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Yu Liue4312402023-01-18 09:15:31 -0800726 apex_name = ""
727 if attr.within_apex:
728 # //build/bazel/rules/apex:apex_name has to be set to a non_empty value,
729 # otherwise //build/bazel/rules/apex:non_apex will be true and the
730 # "-D__ANDROID_APEX__" compiler flag will be missing. Apex_name is used
731 # in some validation on bazel side which don't really apply in mixed
732 # build because soong will do the work, so we just set it to a fixed
733 # value here.
734 apex_name = "dcla_apex"
735 outputs = {
Jingwen Chen583ab212023-05-30 09:45:23 +0000736 "//command_line_option:platforms": "@soong_injection//product_config_platforms:%s" % target,
Yu Liue4312402023-01-18 09:15:31 -0800737 "@//build/bazel/rules/apex:within_apex": attr.within_apex,
738 "@//build/bazel/rules/apex:min_sdk_version": attr.apex_sdk_version,
739 "@//build/bazel/rules/apex:apex_name": apex_name,
Spandan Das40b79f82023-06-25 20:56:06 +0000740 "@//build/bazel/rules/apex:api_domain": attr.api_domain,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500741 }
742
Yu Liue4312402023-01-18 09:15:31 -0800743 return outputs
744
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400745_config_node_transition = transition(
746 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500747 inputs = [],
748 outputs = [
749 "//command_line_option:platforms",
Yu Liue4312402023-01-18 09:15:31 -0800750 "@//build/bazel/rules/apex:within_apex",
751 "@//build/bazel/rules/apex:min_sdk_version",
752 "@//build/bazel/rules/apex:apex_name",
Spandan Das40b79f82023-06-25 20:56:06 +0000753 "@//build/bazel/rules/apex:api_domain",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500754 ],
755)
756
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400757def _passthrough_rule_impl(ctx):
758 return [DefaultInfo(files = depset(ctx.files.deps))]
759
760config_node = rule(
761 implementation = _passthrough_rule_impl,
762 attrs = {
Yu Liue4312402023-01-18 09:15:31 -0800763 "arch" : attr.string(mandatory = True),
764 "os" : attr.string(mandatory = True),
765 "within_apex" : attr.bool(default = False),
766 "apex_sdk_version" : attr.string(mandatory = True),
Spandan Das40b79f82023-06-25 20:56:06 +0000767 "api_domain" : attr.string(mandatory = True),
Yu Liue4312402023-01-18 09:15:31 -0800768 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400769 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
770 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500771)
772
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400773
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500774# Rule representing the root of the build, to depend on all Bazel targets that
775# are required for the build. Building this target will build the entire Bazel
776# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400777mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400778 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500779 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400780 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500781 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400782)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500783
784def _phony_root_impl(ctx):
785 return []
786
787# Rule to depend on other targets but build nothing.
788# This is useful as follows: building a target of this rule will generate
789# symlink forests for all dependencies of the target, without executing any
790# actions of the build.
791phony_root = rule(
792 implementation = _phony_root_impl,
793 attrs = {"deps" : attr.label_list()},
794)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400795`
Cole Faustb85d1a12022-11-08 18:14:01 -0800796
797 productReplacer := strings.NewReplacer(
798 "{PRODUCT}", context.targetProduct,
799 "{VARIANT}", context.targetBuildVariant)
800
801 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400802}
803
Sasha Smundak39a301c2022-12-29 17:11:49 -0800804func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500805 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
806 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400807 formatString := `
808# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400809load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
810
811%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400812
813mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400814 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000815 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400816)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500817
818phony_root(name = "phonyroot",
819 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000820 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500821)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400822`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400823 configNodeFormatString := `
824config_node(name = "%s",
825 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400826 os = "%s",
Yu Liue4312402023-01-18 09:15:31 -0800827 within_apex = %s,
828 apex_sdk_version = "%s",
Spandan Das40b79f82023-06-25 20:56:06 +0000829 api_domain = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400830 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000831 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400832)
833`
834
835 configNodesSection := ""
836
Chris Parsons787fb362021-10-14 18:43:51 -0400837 labelsByConfig := map[string][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500838
839 for _, val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200840 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400841 configString := getConfigString(val)
842 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400843 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400844
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500845 // Configs need to be sorted to maintain determinism of the BUILD file.
846 sortedConfigs := make([]string, 0, len(labelsByConfig))
847 for val := range labelsByConfig {
848 sortedConfigs = append(sortedConfigs, val)
849 }
850 sort.Slice(sortedConfigs, func(i, j int) bool { return sortedConfigs[i] < sortedConfigs[j] })
851
Jingwen Chen1e347862021-09-02 12:11:49 +0000852 allLabels := []string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500853 for _, configString := range sortedConfigs {
854 labels := labelsByConfig[configString]
Chris Parsons787fb362021-10-14 18:43:51 -0400855 configTokens := strings.Split(configString, "|")
Yu Liue4312402023-01-18 09:15:31 -0800856 if len(configTokens) < 2 {
Chris Parsons787fb362021-10-14 18:43:51 -0400857 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000858 }
Chris Parsons787fb362021-10-14 18:43:51 -0400859 archString := configTokens[0]
860 osString := configTokens[1]
Yu Liue4312402023-01-18 09:15:31 -0800861 withinApex := "False"
862 apexSdkVerString := ""
Spandan Das40b79f82023-06-25 20:56:06 +0000863 apiDomainString := ""
864 if osString == "android" {
865 // api domains are meaningful only for device variants
866 apiDomainString = "system"
867 }
Chris Parsons787fb362021-10-14 18:43:51 -0400868 targetString := fmt.Sprintf("%s_%s", osString, archString)
Yu Liue4312402023-01-18 09:15:31 -0800869 if len(configTokens) > 2 {
870 targetString += "_" + configTokens[2]
871 if configTokens[2] == withinApexToString(true) {
872 withinApex = "True"
873 }
874 }
875 if len(configTokens) > 3 {
876 targetString += "_" + configTokens[3]
877 apexSdkVerString = configTokens[3]
878 }
Spandan Das40b79f82023-06-25 20:56:06 +0000879 if len(configTokens) > 4 {
880 apiDomainString = configTokens[4]
881 targetString += "_" + apiDomainString
882 }
Chris Parsons787fb362021-10-14 18:43:51 -0400883 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
884 labelsString := strings.Join(labels, ",\n ")
Spandan Das40b79f82023-06-25 20:56:06 +0000885 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, withinApex, apexSdkVerString, apiDomainString,
Yu Liue4312402023-01-18 09:15:31 -0800886 labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400887 }
888
Jingwen Chen1e347862021-09-02 12:11:49 +0000889 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400890}
891
Chris Parsons944e7d02021-03-11 11:08:46 -0500892func indent(original string) string {
893 result := ""
894 for _, line := range strings.Split(original, "\n") {
895 result += " " + line + "\n"
896 }
897 return result
898}
899
Chris Parsons808d84c2021-03-09 20:43:32 -0500900// Returns the file contents of the buildroot.cquery file that should be used for the cquery
901// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800902// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500903// and grouped by their request type. The data retrieved for each label depends on its
904// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800905func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400906 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons38851d82023-03-15 00:19:32 -0400907 requestTypes := []cqueryRequest{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500908 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500909 cqueryId := getCqueryId(val)
910 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
Chris Parsons38851d82023-03-15 00:19:32 -0400911 if _, seenKey := requestTypeToCqueryIdEntries[val.requestType]; !seenKey {
912 requestTypes = append(requestTypes, val.requestType)
913 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500914 requestTypeToCqueryIdEntries[val.requestType] =
915 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
916 }
917 labelRegistrationMapSection := ""
918 functionDefSection := ""
919 mainSwitchSection := ""
920
921 mapDeclarationFormatString := `
922%s = {
923 %s
924}
925`
926 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800927def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500928%s
929`
930 mainSwitchSectionFormatString := `
931 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800932 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500933`
934
Chris Parsons38851d82023-03-15 00:19:32 -0400935 for _, requestType := range requestTypes {
Chris Parsons944e7d02021-03-11 11:08:46 -0500936 labelMapName := requestType.Name() + "_Labels"
937 functionName := requestType.Name() + "_Fn"
938 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
939 labelMapName,
940 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
941 functionDefSection += fmt.Sprintf(functionDefFormatString,
942 functionName,
943 indent(requestType.StarlarkFunctionBody()))
944 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
945 labelMapName, functionName)
946 }
947
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400948 formatString := `
949# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400950
Cole Faustb85d1a12022-11-08 18:14:01 -0800951{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500952
Cole Faustb85d1a12022-11-08 18:14:01 -0800953{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500954
955def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400956 # TODO(b/199363072): filegroups and file targets aren't associated with any
957 # specific platform architecture in mixed builds. This is consistent with how
958 # Soong treats filegroups, but it may not be the case with manually-written
959 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500960 buildoptions = build_options(target)
Yu Liue4312402023-01-18 09:15:31 -0800961
Jingwen Chen8f222742021-10-07 12:02:23 +0000962 if buildoptions == None:
963 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400964 # any specific platform architecture in mixed builds, so use the host.
965 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -0800966 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500967 if len(platforms) != 1:
968 # An individual configured target should have only one platform architecture.
969 # Note that it's fine for there to be multiple architectures for the same label,
970 # but each is its own configured target.
971 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -0800972 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -0500973 if platform_name == "host":
974 return "HOST"
Cole Faust319abae2023-06-06 15:12:49 -0700975 if not platform_name.startswith("mixed_builds_product-{TARGET_BUILD_VARIANT}"):
976 fail("expected platform name of the form 'mixed_builds_product-{TARGET_BUILD_VARIANT}_android_<arch>' or 'mixed_builds_product-{TARGET_BUILD_VARIANT}_linux_<arch>', but was " + str(platforms))
977 platform_name = platform_name.removeprefix("mixed_builds_product-{TARGET_BUILD_VARIANT}").removeprefix("_")
Yu Liue4312402023-01-18 09:15:31 -0800978 config_key = ""
Cole Faustb85d1a12022-11-08 18:14:01 -0800979 if not platform_name:
Yu Liue4312402023-01-18 09:15:31 -0800980 config_key = "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400981 elif platform_name.startswith("android_"):
Yu Liue4312402023-01-18 09:15:31 -0800982 config_key = platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400983 elif platform_name.startswith("linux_"):
Yu Liue4312402023-01-18 09:15:31 -0800984 config_key = platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400985 else:
Cole Faust319abae2023-06-06 15:12:49 -0700986 fail("expected platform name of the form 'mixed_builds_product-{TARGET_BUILD_VARIANT}_android_<arch>' or 'mixed_builds_product-{TARGET_BUILD_VARIANT}_linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500987
Yu Liue4312402023-01-18 09:15:31 -0800988 within_apex = buildoptions.get("//build/bazel/rules/apex:within_apex")
989 apex_sdk_version = buildoptions.get("//build/bazel/rules/apex:min_sdk_version")
Spandan Das40b79f82023-06-25 20:56:06 +0000990 api_domain = buildoptions.get("//build/bazel/rules/apex:api_domain")
Yu Liue4312402023-01-18 09:15:31 -0800991
992 if within_apex:
993 config_key += "|within_apex"
994 if apex_sdk_version != None and len(apex_sdk_version) > 0:
995 config_key += "|" + apex_sdk_version
Spandan Das40b79f82023-06-25 20:56:06 +0000996 if api_domain != None and len(api_domain) > 0:
997 config_key += "|" + api_domain
Yu Liue4312402023-01-18 09:15:31 -0800998
999 return config_key
1000
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001001def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -05001002 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -05001003
Chris Parsons86dc2c22022-09-28 14:58:41 -04001004 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
1005 if id_string.startswith("//"):
1006 id_string = "@" + id_string
1007
Cole Faustb85d1a12022-11-08 18:14:01 -08001008 {MAIN_SWITCH_SECTION}
1009
Chris Parsons944e7d02021-03-11 11:08:46 -05001010 # This target was not requested via cquery, and thus must be a dependency
1011 # of a requested target.
1012 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001013`
Cole Faustb85d1a12022-11-08 18:14:01 -08001014 replacer := strings.NewReplacer(
1015 "{TARGET_PRODUCT}", context.targetProduct,
1016 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
1017 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
1018 "{FUNCTION_DEF_SECTION}", functionDefSection,
1019 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001020
Cole Faustb85d1a12022-11-08 18:14:01 -08001021 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001022}
1023
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001024// Returns a path containing build-related metadata required for interfacing
1025// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001026func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001027 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -05001028}
1029
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001030// Returns the path where the contents of the @soong_injection repository live.
1031// It is used by Soong to tell Bazel things it cannot over the command line.
1032func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001033 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001034}
1035
1036// Returns the path of the synthetic Bazel workspace that contains a symlink
1037// forest composed the whole source tree and BUILD files generated by bp2build.
1038func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001039 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001040}
1041
Jingwen Chen8c523582021-06-01 11:19:53 +00001042// Returns the path to the top level out dir ($OUT_DIR).
1043func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001044 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +00001045}
1046
Sasha Smundak4975c822022-11-16 15:28:18 -08001047const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
1048
1049var (
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001050 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
1051 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
1052 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
1053 allBazelCommands = []bazelCommand{aqueryCmd, cqueryCmd, buildCmd}
Sasha Smundak4975c822022-11-16 15:28:18 -08001054)
1055
Cole Faustbc65a3f2023-08-01 16:38:55 +00001056func GetBazelSandwichCqueryRequests(config Config) ([]cqueryKey, error) {
1057 result := make([]cqueryKey, 0, len(allowlists.BazelSandwichTargets))
Cole Faust16d10942023-08-02 11:45:43 -07001058 labelRegex := regexp.MustCompile("^@?//([a-zA-Z0-9/_-]+):[a-zA-Z0-9_-]+$")
Cole Faustbc65a3f2023-08-01 16:38:55 +00001059 // Note that bazel "targets" are different from soong "targets", the bazel targets are
1060 // synonymous with soong modules, and soong targets are a configuration a module is built in.
1061 for _, target := range allowlists.BazelSandwichTargets {
Cole Faust16d10942023-08-02 11:45:43 -07001062 match := labelRegex.FindStringSubmatch(target.Label)
1063 if match == nil {
1064 return nil, fmt.Errorf("invalid label, must match `^@?//([a-zA-Z0-9/_-]+):[a-zA-Z0-9_-]+$`: %s", target.Label)
1065 }
1066 if _, err := os.Stat(absolutePath(match[1])); err != nil {
1067 if os.IsNotExist(err) {
1068 // Ignore bazel sandwich targets that don't exist.
1069 continue
1070 } else {
1071 return nil, err
1072 }
1073 }
1074
Cole Faustbc65a3f2023-08-01 16:38:55 +00001075 var soongTarget Target
1076 if target.Host {
1077 soongTarget = config.BuildOSTarget
1078 } else {
1079 soongTarget = config.AndroidCommonTarget
1080 if soongTarget.Os.Class != Device {
1081 // kernel-build-tools seems to set the AndroidCommonTarget to a linux host
1082 // target for some reason, disable device builds in that case.
1083 continue
1084 }
1085 }
1086
1087 result = append(result, cqueryKey{
1088 label: target.Label,
1089 requestType: cquery.GetOutputFiles,
1090 configKey: configKey{
1091 arch: soongTarget.Arch.String(),
1092 osType: soongTarget.Os,
1093 },
1094 })
1095 }
1096 return result, nil
1097}
1098
1099// QueueBazelSandwichCqueryRequests queues cquery requests for all the bazel labels in
1100// bazel_sandwich_targets. These will later be given phony targets so that they can be built on the
1101// command line.
1102func (context *mixedBuildBazelContext) QueueBazelSandwichCqueryRequests(config Config) error {
1103 requests, err := GetBazelSandwichCqueryRequests(config)
1104 if err != nil {
1105 return err
1106 }
1107 for _, request := range requests {
1108 context.QueueBazelRequest(request.label, request.requestType, request.configKey)
1109 }
1110
1111 return nil
1112}
1113
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001114// Issues commands to Bazel to receive results for all cquery requests
1115// queued in the BazelContext.
Liz Kammer690fbac2023-02-10 11:11:17 -05001116func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx invokeBazelContext) error {
1117 eventHandler := ctx.GetEventHandler()
1118 eventHandler.Begin("bazel")
1119 defer eventHandler.End("bazel")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001120
Sasha Smundak4975c822022-11-16 15:28:18 -08001121 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
1122 if err := os.MkdirAll(metricsDir, 0777); err != nil {
1123 return err
1124 }
1125 }
1126 context.results = make(map[cqueryKey]string)
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001127 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001128 return err
1129 }
1130 if err := context.runAquery(config, ctx); err != nil {
1131 return err
1132 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001133 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001134 return err
1135 }
1136
1137 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001138 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -08001139 return nil
1140}
1141
Liz Kammer690fbac2023-02-10 11:11:17 -05001142func (context *mixedBuildBazelContext) runCquery(config Config, ctx invokeBazelContext) error {
1143 eventHandler := ctx.GetEventHandler()
1144 eventHandler.Begin("cquery")
1145 defer eventHandler.End("cquery")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001146 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +02001147 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
1148 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
1149 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -05001150 if err != nil {
1151 return err
1152 }
1153 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001154 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001155 return err
1156 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001157 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001158 return err
1159 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001160 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001161 return err
1162 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001163 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001164 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001165 return err
1166 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001167
Yu Liue4312402023-01-18 09:15:31 -08001168 extraFlags := []string{"--output=starlark", "--starlark:file=" + absolutePath(cqueryFileRelpath)}
1169 if Bool(config.productVariables.ClangCoverage) {
1170 extraFlags = append(extraFlags, "--collect_code_coverage")
1171 }
1172
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001173 cqueryCmdRequest := context.createBazelCommand(config, bazel.CqueryBuildRootRunName, cqueryCmd, extraFlags...)
1174 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCmdRequest, context.paths, eventHandler)
Wei Licbd181c2022-11-16 08:59:23 -08001175 if cqueryErr != nil {
1176 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001177 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001178 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", context.printableCqueryCommand(cqueryCmdRequest))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001179 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001180 return err
1181 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001182 cqueryResults := map[string]string{}
1183 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1184 if strings.Contains(outputLine, ">>") {
1185 splitLine := strings.SplitN(outputLine, ">>", 2)
1186 cqueryResults[splitLine[0]] = splitLine[1]
1187 }
1188 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001189 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001190 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001191 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001192 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001193 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001194 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001195 }
1196 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001197 return nil
1198}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001199
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001200func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1201 oldContents, err := os.ReadFile(path)
1202 if err != nil || !bytes.Equal(contents, oldContents) {
1203 err = os.WriteFile(path, contents, perm)
1204 }
1205 return nil
1206}
1207
Liz Kammer690fbac2023-02-10 11:11:17 -05001208func (context *mixedBuildBazelContext) runAquery(config Config, ctx invokeBazelContext) error {
1209 eventHandler := ctx.GetEventHandler()
1210 eventHandler.Begin("aquery")
1211 defer eventHandler.End("aquery")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001212 // Issue an aquery command to retrieve action information about the bazel build tree.
1213 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001214 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1215 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001216 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001217 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001218 extraFlags = append(extraFlags, "--collect_code_coverage")
1219 paths := make([]string, 0, 2)
1220 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001221 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001222 // TODO(b/259404593) convert path wildcard to regex values
1223 if p[i] == "*" {
1224 p[i] = ".*"
1225 }
1226 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001227 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1228 }
1229 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1230 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1231 }
1232 if len(paths) > 0 {
1233 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001234 }
1235 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001236 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.AqueryBuildRootRunName, aqueryCmd,
1237 extraFlags...), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001238 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001239 return err
1240 }
Liz Kammer690fbac2023-02-10 11:11:17 -05001241 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001242 return err
1243}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001244
Liz Kammer690fbac2023-02-10 11:11:17 -05001245func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx invokeBazelContext) error {
1246 eventHandler := ctx.GetEventHandler()
1247 eventHandler.Begin("symlinks")
1248 defer eventHandler.End("symlinks")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001249 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1250 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1251 // but some of symlinks may be required to resolve source dependencies of the build.
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001252 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.BazelBuildPhonyRootRunName, buildCmd), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001253 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001254}
Chris Parsonsa798d962020-10-12 23:44:08 -04001255
Liz Kammera4655a92023-02-10 17:17:28 -05001256func (context *mixedBuildBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001257 return context.buildStatements
1258}
1259
Sasha Smundak39a301c2022-12-29 17:11:49 -08001260func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001261 return context.depsets
1262}
1263
Sasha Smundak39a301c2022-12-29 17:11:49 -08001264func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001265 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001266}
1267
Chris Parsonsa798d962020-10-12 23:44:08 -04001268// Singleton used for registering BUILD file ninja dependencies (needed
1269// for correctness of builds which use Bazel.
1270func BazelSingleton() Singleton {
1271 return &bazelSingleton{}
1272}
1273
1274type bazelSingleton struct{}
1275
1276func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001277 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001278 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001279 return
1280 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001281
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001282 // Add ninja file dependencies for files which all bazel invocations require.
1283 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001284 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001285 ctx.AddNinjaFileDeps(bazelBuildList)
1286
Sasha Smundak0e87b182022-12-01 11:46:11 -08001287 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001288 if err != nil {
1289 ctx.Errorf(err.Error())
1290 }
1291 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1292 for _, file := range files {
1293 ctx.AddNinjaFileDeps(file)
1294 }
1295
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001296 depsetHashToDepset := map[string]bazel.AqueryDepset{}
1297
Chris Parsons1a7aca02022-04-25 22:35:15 -04001298 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001299 depsetHashToDepset[depset.ContentHash] = depset
1300
Chris Parsons1a7aca02022-04-25 22:35:15 -04001301 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001302 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001303 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1304 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001305 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1306 }
1307 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001308 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1309 if artifactPath == "bazel-out/volatile-status.txt" {
1310 // See https://bazel.build/docs/user-manual#workspace-status
1311 orderOnlies = append(orderOnlies, pathInBazelOut)
1312 } else {
1313 outputs = append(outputs, pathInBazelOut)
1314 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001315 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001316 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001317 ctx.Build(pctx, BuildParams{
1318 Rule: blueprint.Phony,
1319 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1320 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001321 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001322 })
1323 }
1324
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001325 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1326 bazelOutDir := path.Join(executionRoot, "bazel-out")
Cole Faustbc65a3f2023-08-01 16:38:55 +00001327 rel, err := filepath.Rel(ctx.Config().OutDir(), executionRoot)
1328 if err != nil {
1329 ctx.Errorf("%s", err.Error())
1330 }
1331 dotdotsToOutRoot := strings.Repeat("../", strings.Count(rel, "/")+1)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001332 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Liz Kammera4655a92023-02-10 17:17:28 -05001333 // nil build statements are a valid case where we do not create an action because it is
1334 // unnecessary or handled by other processing
1335 if buildStatement == nil {
1336 continue
1337 }
Sasha Smundak1da064c2022-06-08 16:36:16 -07001338 if len(buildStatement.Command) > 0 {
1339 rule := NewRuleBuilder(pctx, ctx)
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001340 intermediateDir, intermediateDirHash := intermediatePathForSboxMixedBuildAction(ctx, buildStatement)
1341 if buildStatement.ShouldRunInSbox {
1342 // Create a rule to build the output inside a sandbox
1343 // This will create two changes of working directory
1344 // 1. From ANDROID_BUILD_TOP to sbox top
1345 // 2. From sbox top to a a synthetic mixed build execution root relative to it
1346 // Finally, the outputs will be copied to intermediateDir
1347 rule.Sbox(intermediateDir,
1348 PathForOutput(ctx, "mixed_build_sbox_intermediates", intermediateDirHash+".textproto")).
1349 SandboxInputs().
1350 // Since we will cd to mixed build execution root, set sbox's out subdir to empty
1351 // Without this, we will try to copy from $SBOX_SANDBOX_DIR/out/out/bazel/output/execroot/__main__/...
1352 SetSboxOutDirDirAsEmpty()
1353
1354 // Create another set of rules to copy files from the intermediate dir to mixed build execution root
1355 for _, outputPath := range buildStatement.OutputPaths {
1356 ctx.Build(pctx, BuildParams{
1357 Rule: CpIfChanged,
1358 Input: intermediateDir.Join(ctx, executionRoot, outputPath),
1359 Output: PathForBazelOut(ctx, outputPath),
1360 })
1361 }
1362 }
Cole Faustbc65a3f2023-08-01 16:38:55 +00001363 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx, depsetHashToDepset, dotdotsToOutRoot)
1364
Sasha Smundak1da064c2022-06-08 16:36:16 -07001365 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1366 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1367 continue
1368 }
1369 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1370 // and thus require special treatment. If BuildStatement were an interface implementing
1371 // buildRule(ctx) function, the code here would just call it.
1372 // Unfortunately, the BuildStatement is defined in
1373 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1374 // because this would cause circular dependency. So, until we move aquery processing
1375 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001376 switch buildStatement.Mnemonic {
Cole Faust950689a2023-06-21 15:07:21 -07001377 case "RepoMappingManifest":
1378 // It appears RepoMappingManifest files currently have
1379 // non-deterministic content. Just emit empty files for
1380 // now because they're unused.
1381 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1382 WriteFileRuleVerbatim(ctx, out, "")
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001383 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001384 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
Cole Faust20f20302023-08-31 11:00:25 -07001385 if buildStatement.IsExecutable {
Cole Faust39b614a2023-08-23 16:11:26 -07001386 WriteExecutableFileRuleVerbatim(ctx, out, buildStatement.FileContents)
1387 } else {
1388 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
1389 }
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001390 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001391 // build-runfiles arguments are the manifest file and the target directory
1392 // where it creates the symlink tree according to this manifest (and then
1393 // writes the MANIFEST file to it).
1394 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1395 outManifestPath := outManifest.String()
1396 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1397 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1398 }
1399 outDir := filepath.Dir(outManifestPath)
1400 ctx.Build(pctx, BuildParams{
1401 Rule: buildRunfilesRule,
1402 Output: outManifest,
1403 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1404 Description: "symlink tree for " + outDir,
1405 Args: map[string]string{
1406 "outDir": outDir,
1407 },
1408 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001409 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001410 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001411 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001412 }
Cole Faustbc65a3f2023-08-01 16:38:55 +00001413
1414 // Create phony targets for all the bazel sandwich output files
1415 requests, err := GetBazelSandwichCqueryRequests(ctx.Config())
1416 if err != nil {
1417 ctx.Errorf(err.Error())
1418 }
1419 for _, request := range requests {
1420 files, err := ctx.Config().BazelContext.GetOutputFiles(request.label, request.configKey)
1421 if err != nil {
1422 ctx.Errorf(err.Error())
1423 }
1424 filesAsPaths := make([]Path, 0, len(files))
1425 for _, file := range files {
1426 filesAsPaths = append(filesAsPaths, PathForBazelOut(ctx, file))
1427 }
1428 ctx.Phony("bazel_sandwich", filesAsPaths...)
1429 }
1430 ctx.Phony("checkbuild", PathForPhony(ctx, "bazel_sandwich"))
Chris Parsonsa798d962020-10-12 23:44:08 -04001431}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001432
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001433// Returns a out dir path for a sandboxed mixed build action
1434func intermediatePathForSboxMixedBuildAction(ctx PathContext, statement *bazel.BuildStatement) (OutputPath, string) {
1435 // An artifact can be generated by a single buildstatement.
1436 // Use the hash of the first artifact to create a unique path
1437 uniqueDir := sha1.New()
1438 uniqueDir.Write([]byte(statement.OutputPaths[0]))
1439 uniqueDirHashString := hex.EncodeToString(uniqueDir.Sum(nil))
1440 return PathForOutput(ctx, "mixed_build_sbox_intermediates", uniqueDirHashString), uniqueDirHashString
1441}
1442
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001443// Register bazel-owned build statements (obtained from the aquery invocation).
Cole Faustbc65a3f2023-08-01 16:38:55 +00001444func 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 -04001445 // executionRoot is the action cwd.
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001446 if buildStatement.ShouldRunInSbox {
1447 // mkdir -p ensures that the directory exists when run via sbox
1448 cmd.Text(fmt.Sprintf("mkdir -p '%s' && cd '%s' &&", executionRoot, executionRoot))
1449 } else {
1450 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1451 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001452
1453 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1454 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001455 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001456 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001457 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001458 }
1459 cmd.Text("&&")
1460 }
1461
1462 for _, pair := range buildStatement.Env {
1463 // Set per-action env variables, if any.
1464 cmd.Flag(pair.Key + "=" + pair.Value)
1465 }
1466
Cole Faustbc65a3f2023-08-01 16:38:55 +00001467 command := buildStatement.Command
1468 command = strings.ReplaceAll(command, "{DOTDOTS_TO_OUTPUT_ROOT}", dotdotsToOutRoot)
1469
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001470 // The actual Bazel action.
Cole Faustbc65a3f2023-08-01 16:38:55 +00001471 if len(command) > 16*1024 {
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001472 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
Cole Faustbc65a3f2023-08-01 16:38:55 +00001473 WriteFileRule(ctx, commandFile, command)
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001474
1475 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1476 } else {
Cole Faustbc65a3f2023-08-01 16:38:55 +00001477 cmd.Text(command)
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001478 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001479
1480 for _, outputPath := range buildStatement.OutputPaths {
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001481 if buildStatement.ShouldRunInSbox {
1482 // The full path has three components that get joined together
1483 // 1. intermediate output dir that `sbox` will place the artifacts at
1484 // 2. mixed build execution root
1485 // 3. artifact path returned by aquery
1486 intermediateDir, _ := intermediatePathForSboxMixedBuildAction(ctx, buildStatement)
1487 cmd.ImplicitOutput(intermediateDir.Join(ctx, executionRoot, outputPath))
1488 } else {
1489 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1490 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001491 }
1492 for _, inputPath := range buildStatement.InputPaths {
1493 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1494 }
1495 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001496 if buildStatement.ShouldRunInSbox {
1497 // Bazel depsets are phony targets that are used to group files.
1498 // We need to copy the grouped files into the sandbox
1499 ds, _ := depsetHashToDepset[inputDepsetHash]
1500 cmd.Implicits(PathsForBazelOut(ctx, ds.DirectArtifacts))
1501 } else {
1502 otherDepsetName := bazelDepsetName(inputDepsetHash)
1503 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1504 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001505 }
Cole Faustbc65a3f2023-08-01 16:38:55 +00001506 for _, implicitPath := range buildStatement.ImplicitDeps {
1507 cmd.Implicit(PathForArbitraryOutput(ctx, implicitPath))
1508 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001509
1510 if depfile := buildStatement.Depfile; depfile != nil {
1511 // The paths in depfile are relative to `executionRoot`.
1512 // Hence, they need to be corrected by replacing "bazel-out"
1513 // with the full `bazelOutDir`.
1514 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1515 // would be deemed missing.
1516 // (Note: The regexp uses a capture group because the version of sed
1517 // does not support a look-behind pattern.)
1518 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1519 bazelOutDir, *depfile)
1520 cmd.Text(replacement)
1521 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1522 }
1523
1524 for _, symlinkPath := range buildStatement.SymlinkPaths {
1525 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1526 }
1527}
1528
Chris Parsons8d6e4332021-02-22 16:13:50 -05001529func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001530 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001531}
1532
Chris Parsons787fb362021-10-14 18:43:51 -04001533func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001534 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001535 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001536 if key.configKey.osType.Class == Device {
1537 // For the generic Android, the expected result is "target|android", which
1538 // corresponds to the product_variable_config named "android_target" in
1539 // build/bazel/platforms/BUILD.bazel.
1540 arch = "target"
1541 } else {
1542 // Use host platform, which is currently hardcoded to be x86_64.
1543 arch = "x86_64"
1544 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001545 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001546 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001547 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001548 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001549 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001550 }
Yu Liue4312402023-01-18 09:15:31 -08001551 keyString := arch + "|" + osName
1552 if key.configKey.apexKey.WithinApex {
1553 keyString += "|" + withinApexToString(key.configKey.apexKey.WithinApex)
1554 }
1555
1556 if len(key.configKey.apexKey.ApexSdkVersion) > 0 {
1557 keyString += "|" + key.configKey.apexKey.ApexSdkVersion
1558 }
1559
Spandan Das40b79f82023-06-25 20:56:06 +00001560 if len(key.configKey.apexKey.ApiDomain) > 0 {
1561 keyString += "|" + key.configKey.apexKey.ApiDomain
1562 }
1563
Yu Liue4312402023-01-18 09:15:31 -08001564 return keyString
Chris Parsons787fb362021-10-14 18:43:51 -04001565}
1566
Chris Parsonsf874e462022-05-10 13:50:12 -04001567func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001568 return configKey{
1569 // use string because Arch is not a valid key in go
1570 arch: ctx.Arch().String(),
1571 osType: ctx.Os(),
1572 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001573}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001574
Yu Liue4312402023-01-18 09:15:31 -08001575func GetConfigKeyApexVariant(ctx BaseModuleContext, apexKey *ApexConfigKey) configKey {
1576 configKey := GetConfigKey(ctx)
1577
1578 if apexKey != nil {
1579 configKey.apexKey = ApexConfigKey{
1580 WithinApex: apexKey.WithinApex,
1581 ApexSdkVersion: apexKey.ApexSdkVersion,
Spandan Das40b79f82023-06-25 20:56:06 +00001582 ApiDomain: apexKey.ApiDomain,
Yu Liue4312402023-01-18 09:15:31 -08001583 }
1584 }
1585
1586 return configKey
1587}
1588
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001589func bazelDepsetName(contentHash string) string {
1590 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001591}