blob: fd4b5ef1b2253d64457a60cd5a97fa8f49e69af7 [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"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040025 "runtime"
Cole Faust705968d2022-12-14 11:32:05 -080026 "sort"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040027 "strings"
28 "sync"
Chris Parsonsa798d962020-10-12 23:44:08 -040029
Chris Parsonsad876012022-08-20 14:48:32 -040030 "android/soong/android/allowlists"
Chris Parsons944e7d02021-03-11 11:08:46 -050031 "android/soong/bazel/cquery"
Jingwen Chen1e347862021-09-02 12:11:49 +000032 "android/soong/shared"
Cole Faust8a161be2023-06-14 15:45:12 -070033 "android/soong/starlark_import"
Jingwen Chen379221f2023-03-30 13:19:29 +000034
Chris Parsons1a7aca02022-04-25 22:35:15 -040035 "github.com/google/blueprint"
Liz Kammer690fbac2023-02-10 11:11:17 -050036 "github.com/google/blueprint/metrics"
Liz Kammer8206d4f2021-03-03 16:40:52 -050037
Patrice Arruda05ab2d02020-12-12 06:24:26 +000038 "android/soong/bazel"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040039)
40
Sasha Smundak1da064c2022-06-08 16:36:16 -070041var (
Sasha Smundakc180dbd2022-07-03 14:55:58 -070042 _ = pctx.HostBinToolVariable("bazelBuildRunfilesTool", "build-runfiles")
43 buildRunfilesRule = pctx.AndroidStaticRule("bazelBuildRunfiles", blueprint.RuleParams{
44 Command: "${bazelBuildRunfilesTool} ${in} ${outDir}",
45 Depfile: "",
46 Description: "",
47 CommandDeps: []string{"${bazelBuildRunfilesTool}"},
48 }, "outDir")
Sasha Smundak1da064c2022-06-08 16:36:16 -070049)
50
Liz Kammerc13f7852023-05-17 13:01:48 -040051func registerMixedBuildsMutator(ctx RegisterMutatorsContext) {
52 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
Chris Parsonsf874e462022-05-10 13:50:12 -040053}
54
55func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammerc13f7852023-05-17 13:01:48 -040056 ctx.FinalDepsMutators(registerMixedBuildsMutator)
Chris Parsonsf874e462022-05-10 13:50:12 -040057}
58
59func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
60 if m := ctx.Module(); m.Enabled() {
61 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
MarkDacekf47e1422023-04-19 16:47:36 +000062 mixedBuildEnabled := MixedBuildsEnabled(ctx)
63 queueMixedBuild := mixedBuildMod.IsMixedBuildSupported(ctx) && mixedBuildEnabled == MixedBuildEnabled
MarkDacek9c094ca2023-03-16 19:15:19 +000064 if queueMixedBuild {
Chris Parsonsf874e462022-05-10 13:50:12 -040065 mixedBuildMod.QueueBazelCall(ctx)
66 }
67 }
68 }
69}
70
Liz Kammerf29df7c2021-04-02 13:37:39 -040071type cqueryRequest interface {
72 // Name returns a string name for this request type. Such request type names must be unique,
73 // and must only consist of alphanumeric characters.
74 Name() string
75
76 // StarlarkFunctionBody returns a starlark function body to process this request type.
77 // The returned string is the body of a Starlark function which obtains
78 // all request-relevant information about a target and returns a string containing
79 // this information.
80 // The function should have the following properties:
Cole Faust97d15272022-11-22 14:08:59 -080081 // - The arguments are `target` (a configured target) and `id_string` (the label + configuration).
Liz Kammerf29df7c2021-04-02 13:37:39 -040082 // - The return value must be a string.
83 // - The function body should not be indented outside of its own scope.
84 StarlarkFunctionBody() string
85}
86
Chris Parsons787fb362021-10-14 18:43:51 -040087// Portion of cquery map key to describe target configuration.
88type configKey struct {
Yu Liue4312402023-01-18 09:15:31 -080089 arch string
90 osType OsType
91 apexKey ApexConfigKey
92}
93
94type ApexConfigKey struct {
95 WithinApex bool
96 ApexSdkVersion string
Spandan Das40b79f82023-06-25 20:56:06 +000097 ApiDomain string
Yu Liue4312402023-01-18 09:15:31 -080098}
99
100func (c ApexConfigKey) String() string {
Spandan Das40b79f82023-06-25 20:56:06 +0000101 return fmt.Sprintf("%s_%s_%s", withinApexToString(c.WithinApex), c.ApexSdkVersion, c.ApiDomain)
Yu Liue4312402023-01-18 09:15:31 -0800102}
103
104func withinApexToString(withinApex bool) string {
105 if withinApex {
106 return "within_apex"
107 }
108 return ""
Chris Parsons787fb362021-10-14 18:43:51 -0400109}
110
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700111func (c configKey) String() string {
Yu Liue4312402023-01-18 09:15:31 -0800112 return fmt.Sprintf("%s::%s::%s", c.arch, c.osType, c.apexKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700113}
114
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400115// Map key to describe bazel cquery requests.
116type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400117 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400118 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400119 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400120}
121
Chris Parsons86dc2c22022-09-28 14:58:41 -0400122func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
123 if strings.HasPrefix(label, "//") {
124 // Normalize Bazel labels to specify main repository explicitly.
125 label = "@" + label
126 }
127 return cqueryKey{label, cqueryRequest, cfgKey}
128}
129
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700130func (c cqueryKey) String() string {
131 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700132}
133
Liz Kammer690fbac2023-02-10 11:11:17 -0500134type invokeBazelContext interface {
135 GetEventHandler() *metrics.EventHandler
136}
137
Chris Parsonsf874e462022-05-10 13:50:12 -0400138// BazelContext is a context object useful for interacting with Bazel during
139// the course of a build. Use of Bazel to evaluate part of the build graph
140// is referred to as a "mixed build". (Some modules are managed by Soong,
141// some are managed by Bazel). To facilitate interop between these build
142// subgraphs, Soong may make requests to Bazel and evaluate their responses
143// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400144type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400145 // Add a cquery request to the bazel request queue. All queued requests
146 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
147 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
148
149 // ** Cquery Results Retrieval Functions
150 // The below functions pertain to retrieving cquery results from a prior
151 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400152
153 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400154 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500155
Chris Parsons944e7d02021-03-11 11:08:46 -0500156 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400157 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400158
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700159 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400160 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700161
Sasha Smundakedd16662022-10-07 14:44:50 -0700162 // Returns the results of the GetCcUnstrippedInfo query
163 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
164
Spandan Dasbd156812023-06-05 22:43:13 +0000165 // Returns the results of the GetPrebuiltFileInfo query
166 GetPrebuiltFileInfo(label string, cfgKey configKey) (cquery.PrebuiltFileInfo, error)
167
Chris Parsonsf874e462022-05-10 13:50:12 -0400168 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400169
170 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800171 // queued in the BazelContext. The ctx argument is optional and is only
172 // used for performance data collection
Liz Kammer690fbac2023-02-10 11:11:17 -0500173 InvokeBazel(config Config, ctx invokeBazelContext) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400174
Chris Parsonsad876012022-08-20 14:48:32 -0400175 // Returns true if Bazel handling is enabled for the module with the given name.
176 // Note that this only implies "bazel mixed build" allowlisting. The caller
177 // should independently verify the module is eligible for Bazel handling
178 // (for example, that it is MixedBuildBuildable).
Yu Liue4312402023-01-18 09:15:31 -0800179 IsModuleNameAllowed(moduleName string, withinApex bool) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500180
181 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
182 OutputBase() string
183
184 // Returns build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500185 BuildStatementsToRegister() []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400186
187 // Returns the depsets defined in Bazel's aquery response.
188 AqueryDepsets() []bazel.AqueryDepset
Cole Faustbc65a3f2023-08-01 16:38:55 +0000189
190 QueueBazelSandwichCqueryRequests(config Config) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400191}
192
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400193type bazelRunner interface {
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000194 issueBazelCommand(cmdRequest bazel.CmdRequest, paths *bazelPaths, eventHandler *metrics.EventHandler) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400195}
196
197type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000198 homeDir string
199 bazelPath string
200 outputBase string
201 workspaceDir string
202 soongOutDir string
203 metricsDir string
204 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400205}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400206
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400207// A context object which tracks queued requests that need to be made to Bazel,
208// and their results after the requests have been made.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800209type mixedBuildBazelContext struct {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400210 bazelRunner
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500211 paths *bazelPaths
212 // cquery requests that have not yet been issued to Bazel. This list is maintained
213 // in a sorted state, and is guaranteed to have no duplicates.
214 requests []cqueryKey
215 requestMutex sync.Mutex // requests can be written in parallel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400216
217 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500218
219 // Build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500220 buildStatements []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400221
222 // Depsets which should be used for Bazel's build statements.
223 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400224
225 // Per-module allowlist/denylist functionality to control whether analysis of
226 // modules are handled by Bazel. For modules which do not have a Bazel definition
227 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
228 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
229 // Per-module denylist to opt modules out of bazel handling.
230 bazelDisabledModules map[string]bool
231 // Per-module allowlist to opt modules in to bazel handling.
232 bazelEnabledModules map[string]bool
Yu Liue4312402023-01-18 09:15:31 -0800233 // DCLA modules are enabled when used in apex.
234 bazelDclaEnabledModules map[string]bool
Cole Faustb85d1a12022-11-08 18:14:01 -0800235
236 targetProduct string
237 targetBuildVariant string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400238}
239
Sasha Smundak39a301c2022-12-29 17:11:49 -0800240var _ BazelContext = &mixedBuildBazelContext{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400241
242// A bazel context to use when Bazel is disabled.
243type noopBazelContext struct{}
244
245var _ BazelContext = noopBazelContext{}
246
247// A bazel context to use for tests.
248type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400249 OutputBaseDir string
250
Spandan Dasbd156812023-06-05 22:43:13 +0000251 LabelToOutputFiles map[string][]string
252 LabelToCcInfo map[string]cquery.CcInfo
253 LabelToPythonBinary map[string]string
254 LabelToApexInfo map[string]cquery.ApexInfo
255 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
256 LabelToPrebuiltFileInfo map[string]cquery.PrebuiltFileInfo
Yu Liue4312402023-01-18 09:15:31 -0800257
258 BazelRequests map[string]bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400259}
260
Yu Liue4312402023-01-18 09:15:31 -0800261func (m MockBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
262 key := BuildMockBazelContextRequestKey(label, requestType, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
263 if m.BazelRequests == nil {
264 m.BazelRequests = make(map[string]bool)
265 }
266 m.BazelRequests[key] = true
Chris Parsons8d6e4332021-02-22 16:13:50 -0500267}
268
Cole Faustbc65a3f2023-08-01 16:38:55 +0000269func (m MockBazelContext) QueueBazelSandwichCqueryRequests(config Config) error {
270 panic("unimplemented")
271}
272
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700273func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500274 result, ok := m.LabelToOutputFiles[label]
275 if !ok {
276 return []string{}, fmt.Errorf("no target with label %q in LabelToOutputFiles", label)
277 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400278 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400279}
280
Yu Liue4312402023-01-18 09:15:31 -0800281func (m MockBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500282 result, ok := m.LabelToCcInfo[label]
283 if !ok {
Yu Liue4312402023-01-18 09:15:31 -0800284 key := BuildMockBazelContextResultKey(label, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
285 result, ok = m.LabelToCcInfo[key]
286 if !ok {
287 return cquery.CcInfo{}, fmt.Errorf("no target with label %q in LabelToCcInfo", label)
288 }
Sam Delmericoce39f832023-01-23 14:04:24 -0500289 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400290 return result, nil
291}
292
Liz Kammerbe6a7122022-11-04 16:05:11 -0400293func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500294 result, ok := m.LabelToApexInfo[label]
295 if !ok {
296 return cquery.ApexInfo{}, fmt.Errorf("no target with label %q in LabelToApexInfo", label)
297 }
Liz Kammer0e255ef2022-11-04 16:07:04 -0400298 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700299}
300
Sasha Smundakedd16662022-10-07 14:44:50 -0700301func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500302 result, ok := m.LabelToCcBinary[label]
303 if !ok {
304 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no target with label %q in LabelToCcBinary", label)
305 }
Sasha Smundakedd16662022-10-07 14:44:50 -0700306 return result, nil
307}
308
Spandan Dasbd156812023-06-05 22:43:13 +0000309func (m MockBazelContext) GetPrebuiltFileInfo(label string, _ configKey) (cquery.PrebuiltFileInfo, error) {
310 result, ok := m.LabelToPrebuiltFileInfo[label]
311 if !ok {
312 return cquery.PrebuiltFileInfo{}, fmt.Errorf("no target with label %q in LabelToPrebuiltFileInfo", label)
313 }
314 return result, nil
315}
316
Liz Kammer690fbac2023-02-10 11:11:17 -0500317func (m MockBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400318 panic("unimplemented")
319}
320
Yu Liue4312402023-01-18 09:15:31 -0800321func (m MockBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400322 return true
323}
324
Liz Kammera92e8442021-04-07 20:25:21 -0400325func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500326
Liz Kammera4655a92023-02-10 17:17:28 -0500327func (m MockBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
328 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500329}
330
Chris Parsons1a7aca02022-04-25 22:35:15 -0400331func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
332 return []bazel.AqueryDepset{}
333}
334
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400335var _ BazelContext = MockBazelContext{}
336
Yu Liue4312402023-01-18 09:15:31 -0800337func BuildMockBazelContextRequestKey(label string, request cqueryRequest, arch string, osType OsType, apexKey ApexConfigKey) string {
338 cfgKey := configKey{
339 arch: arch,
340 osType: osType,
341 apexKey: apexKey,
342 }
343
344 return strings.Join([]string{label, request.Name(), cfgKey.String()}, "_")
345}
346
347func BuildMockBazelContextResultKey(label string, arch string, osType OsType, apexKey ApexConfigKey) string {
348 cfgKey := configKey{
349 arch: arch,
350 osType: osType,
351 apexKey: apexKey,
352 }
353
354 return strings.Join([]string{label, cfgKey.String()}, "_")
355}
356
Sasha Smundak39a301c2022-12-29 17:11:49 -0800357func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400358 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400359 bazelCtx.requestMutex.Lock()
360 defer bazelCtx.requestMutex.Unlock()
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500361
362 // Insert key into requests, maintaining the sort, and only if it's not duplicate.
363 keyString := key.String()
364 foundEqual := false
365 notLessThanKeyString := func(i int) bool {
366 s := bazelCtx.requests[i].String()
367 v := strings.Compare(s, keyString)
368 if v == 0 {
369 foundEqual = true
370 }
371 return v >= 0
372 }
373 targetIndex := sort.Search(len(bazelCtx.requests), notLessThanKeyString)
374 if foundEqual {
375 return
376 }
377
378 if targetIndex == len(bazelCtx.requests) {
379 bazelCtx.requests = append(bazelCtx.requests, key)
380 } else {
381 bazelCtx.requests = append(bazelCtx.requests[:targetIndex+1], bazelCtx.requests[targetIndex:]...)
382 bazelCtx.requests[targetIndex] = key
383 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400384}
385
Sasha Smundak39a301c2022-12-29 17:11:49 -0800386func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400387 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400388 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500389 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400390
Chris Parsonsf874e462022-05-10 13:50:12 -0400391 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400392 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400393 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400394}
395
Sasha Smundak39a301c2022-12-29 17:11:49 -0800396func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400397 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400398 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000399 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400400 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000401 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400402 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 +0000403}
404
Sasha Smundak39a301c2022-12-29 17:11:49 -0800405func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400406 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700407 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500408 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700409 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400410 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700411}
412
Sasha Smundak39a301c2022-12-29 17:11:49 -0800413func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700414 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
415 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500416 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700417 }
418 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
419}
420
Spandan Dasbd156812023-06-05 22:43:13 +0000421func (bazelCtx *mixedBuildBazelContext) GetPrebuiltFileInfo(label string, cfgKey configKey) (cquery.PrebuiltFileInfo, error) {
422 key := makeCqueryKey(label, cquery.GetPrebuiltFileInfo, cfgKey)
423 if rawString, ok := bazelCtx.results[key]; ok {
424 return cquery.GetPrebuiltFileInfo.ParseResult(strings.TrimSpace(rawString))
425 }
426 return cquery.PrebuiltFileInfo{}, fmt.Errorf("no bazel response for %s", key)
427}
428
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700429func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500430 panic("unimplemented")
431}
432
Cole Faustbc65a3f2023-08-01 16:38:55 +0000433func (n noopBazelContext) QueueBazelSandwichCqueryRequests(config Config) error {
434 panic("unimplemented")
435}
436
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700437func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500438 panic("unimplemented")
439}
440
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700441func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400442 panic("unimplemented")
443}
444
Liz Kammerbe6a7122022-11-04 16:05:11 -0400445func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700446 panic("unimplemented")
447}
448
Sasha Smundakedd16662022-10-07 14:44:50 -0700449func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
450 //TODO implement me
451 panic("implement me")
452}
453
Spandan Dasbd156812023-06-05 22:43:13 +0000454func (n noopBazelContext) GetPrebuiltFileInfo(_ string, _ configKey) (cquery.PrebuiltFileInfo, error) {
455 panic("implement me")
456}
457
Liz Kammer690fbac2023-02-10 11:11:17 -0500458func (n noopBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400459 panic("unimplemented")
460}
461
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500462func (m noopBazelContext) OutputBase() string {
463 return ""
464}
465
Yu Liue4312402023-01-18 09:15:31 -0800466func (n noopBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400467 return false
468}
469
Liz Kammera4655a92023-02-10 17:17:28 -0500470func (m noopBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
471 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500472}
473
Chris Parsons1a7aca02022-04-25 22:35:15 -0400474func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
475 return []bazel.AqueryDepset{}
476}
477
Yu Liu6a7940c2023-05-09 17:12:22 -0700478func AddToStringSet(set map[string]bool, items []string) {
Yu Liue4312402023-01-18 09:15:31 -0800479 for _, item := range items {
480 set[item] = true
481 }
482}
483
Cole Faust705968d2022-12-14 11:32:05 -0800484func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400485 disabledModules := map[string]bool{}
486 enabledModules := map[string]bool{}
487
Cole Faust705968d2022-12-14 11:32:05 -0800488 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400489 case BazelProdMode:
Yu Liu6a7940c2023-05-09 17:12:22 -0700490 AddToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800491 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000492 enabledModules[enabledAdHocModule] = true
493 }
MarkDacekb78465d2022-10-18 20:10:16 +0000494 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400495 // Staging mode includes all prod modules plus all staging modules.
Yu Liu6a7940c2023-05-09 17:12:22 -0700496 AddToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
497 AddToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800498 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000499 enabledModules[enabledAdHocModule] = true
500 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400501 default:
Chris Parsons21f80272023-06-15 04:02:28 +0000502 panic("Expected BazelProdMode or BazelStagingMode")
Cole Faust705968d2022-12-14 11:32:05 -0800503 }
504 return enabledModules, disabledModules
505}
506
507func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
508 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
509 enabledList := make([]string, 0, len(enabledModules))
510 for module := range enabledModules {
511 if !disabledModules[module] {
512 enabledList = append(enabledList, module)
513 }
514 }
515 sort.Strings(enabledList)
516 return enabledList
517}
518
519func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons21f80272023-06-15 04:02:28 +0000520 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400521 return noopBazelContext{}, nil
522 }
523
Cole Faust705968d2022-12-14 11:32:05 -0800524 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
525
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800526 paths := bazelPaths{
527 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400528 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800529 var missing []string
530 vars := []struct {
531 name string
532 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000533
534 // True if the environment variable needs to be tracked so that changes to the variable
535 // cause the ninja file to be regenerated, false otherwise. False should only be set for
536 // environment variables that have no effect on the generated ninja file.
537 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800538 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000539 {"BAZEL_HOME", &paths.homeDir, true},
540 {"BAZEL_PATH", &paths.bazelPath, true},
541 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
542 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
543 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
544 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800545 }
546 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000547 if v.track {
548 if s := c.Getenv(v.name); len(s) > 1 {
549 *v.ptr = s
550 continue
551 }
552 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800553 *v.ptr = s
554 } else {
555 missing = append(missing, v.name)
556 }
557 }
558 if len(missing) > 0 {
559 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
560 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800561
562 targetBuildVariant := "user"
563 if c.Eng() {
564 targetBuildVariant = "eng"
565 } else if c.Debuggable() {
566 targetBuildVariant = "userdebug"
567 }
568 targetProduct := "unknown"
569 if c.HasDeviceProduct() {
570 targetProduct = c.DeviceProduct()
571 }
Yu Liue4312402023-01-18 09:15:31 -0800572 dclaMixedBuildsEnabledList := []string{}
573 if c.BuildMode == BazelProdMode {
574 dclaMixedBuildsEnabledList = allowlists.ProdDclaMixedBuildsEnabledList
575 } else if c.BuildMode == BazelStagingMode {
576 dclaMixedBuildsEnabledList = append(allowlists.ProdDclaMixedBuildsEnabledList,
577 allowlists.StagingDclaMixedBuildsEnabledList...)
578 }
579 dclaEnabledModules := map[string]bool{}
Yu Liu6a7940c2023-05-09 17:12:22 -0700580 AddToStringSet(dclaEnabledModules, dclaMixedBuildsEnabledList)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800581 return &mixedBuildBazelContext{
Chris Parsons9402ca82023-02-23 17:28:06 -0500582 bazelRunner: &builtinBazelRunner{c.UseBazelProxy, absolutePath(c.outDir)},
Yu Liue4312402023-01-18 09:15:31 -0800583 paths: &paths,
Yu Liue4312402023-01-18 09:15:31 -0800584 bazelEnabledModules: enabledModules,
585 bazelDisabledModules: disabledModules,
586 bazelDclaEnabledModules: dclaEnabledModules,
587 targetProduct: targetProduct,
588 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400589 }, nil
590}
591
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400592func (p *bazelPaths) BazelMetricsDir() string {
593 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000594}
595
Yu Liue4312402023-01-18 09:15:31 -0800596func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string, withinApex bool) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400597 if context.bazelDisabledModules[moduleName] {
598 return false
599 }
600 if context.bazelEnabledModules[moduleName] {
601 return true
602 }
Spandan Das95b24b12023-06-26 22:39:19 +0000603 if withinApex && context.bazelDclaEnabledModules[moduleName] {
Yu Liue4312402023-01-18 09:15:31 -0800604 return true
605 }
606
Chris Parsons21f80272023-06-15 04:02:28 +0000607 return false
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400608}
609
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400610func pwdPrefix() string {
611 // Darwin doesn't have /proc
612 if runtime.GOOS != "darwin" {
613 return "PWD=/proc/self/cwd"
614 }
615 return ""
616}
617
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400618type bazelCommand struct {
619 command string
620 // query or label
621 expression string
622}
623
Chris Parsons9402ca82023-02-23 17:28:06 -0500624type builtinBazelRunner struct {
625 useBazelProxy bool
626 outDir string
627}
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400628
Chris Parsons808d84c2021-03-09 20:43:32 -0500629// Issues the given bazel command with given build label and additional flags.
630// Returns (stdout, stderr, error). The first and second return values are strings
631// containing the stdout and stderr of the run command, and an error is returned if
632// the invocation returned an error code.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000633func (r *builtinBazelRunner) issueBazelCommand(cmdRequest bazel.CmdRequest, paths *bazelPaths, eventHandler *metrics.EventHandler) (string, string, error) {
Chris Parsons9402ca82023-02-23 17:28:06 -0500634 if r.useBazelProxy {
635 eventHandler.Begin("client_proxy")
636 defer eventHandler.End("client_proxy")
637 proxyClient := bazel.NewProxyClient(r.outDir)
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000638 resp, err := proxyClient.IssueCommand(cmdRequest)
Chris Parsons9402ca82023-02-23 17:28:06 -0500639
640 if err != nil {
641 return "", "", err
642 }
643 if len(resp.ErrorString) > 0 {
644 return "", "", fmt.Errorf(resp.ErrorString)
645 }
646 return resp.Stdout, resp.Stderr, nil
Jason Wu52cd1942022-09-08 15:37:57 +0000647 } else {
Chris Parsons9402ca82023-02-23 17:28:06 -0500648 eventHandler.Begin("bazel command")
649 defer eventHandler.End("bazel command")
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000650
651 stdout, stderr, err := bazel.ExecBazel(paths.bazelPath, absolutePath(paths.syntheticWorkspaceDir()), cmdRequest)
652 return string(stdout), string(stderr), err
Jason Wu52cd1942022-09-08 15:37:57 +0000653 }
654}
655
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000656func (context *mixedBuildBazelContext) createBazelCommand(config Config, runName bazel.RunName, command bazelCommand,
657 extraFlags ...string) bazel.CmdRequest {
Cole Faust319abae2023-06-06 15:12:49 -0700658 if runtime.GOOS != "linux" && runtime.GOOS != "darwin" {
659 panic("Unknown GOOS: " + runtime.GOOS)
660 }
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000661 cmdFlags := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000662 "--output_base=" + absolutePath(context.paths.outputBase),
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000663 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700664 command.expression,
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000665 "--profile=" + shared.BazelMetricsFilename(context.paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400666
Cole Faust319abae2023-06-06 15:12:49 -0700667 "--host_platform=@soong_injection//product_config_platforms:mixed_builds_product-" + context.targetBuildVariant + "_" + runtime.GOOS + "_x86_64",
668 // Don't specify --platforms, because on some products/branches (like kernel-build-tools)
669 // the main platform for mixed_builds_product-variant doesn't exist because an arch isn't
670 // specified in product config. The derivative platforms that config_node transitions into
671 // will still work.
Jingwen Chen583ab212023-05-30 09:45:23 +0000672
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700673 // Suppress noise
674 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500675 "--noshow_progress",
676 "--norun_validations",
677 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400678 cmdFlags = append(cmdFlags, extraFlags...)
679
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700680 extraEnv := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000681 "HOME=" + context.paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200682 pwdPrefix(),
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000683 "BUILD_DIR=" + absolutePath(context.paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700684 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000685 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000686 "OUT_DIR=" + absolutePath(context.paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500687 // Disables local host detection of gcc; toolchain information is defined
688 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700689 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
690 }
Cole Faust8a161be2023-06-14 15:45:12 -0700691 capturedEnvVars, err := starlark_import.GetStarlarkValue[[]string]("captured_env_vars")
692 if err != nil {
693 panic(err)
694 }
695 for _, envvar := range capturedEnvVars {
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500696 val := config.Getenv(envvar)
697 if val == "" {
698 continue
699 }
700 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
701 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000702 envVars := append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400703
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000704 return bazel.CmdRequest{cmdFlags, envVars}
Jason Wu52cd1942022-09-08 15:37:57 +0000705}
706
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000707func (context *mixedBuildBazelContext) printableCqueryCommand(bazelCmd bazel.CmdRequest) string {
708 args := append([]string{context.paths.bazelPath}, bazelCmd.Argv...)
709 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(args, "\" \"") + "\""
Jason Wu52cd1942022-09-08 15:37:57 +0000710 return outputString
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400711}
712
Sasha Smundak39a301c2022-12-29 17:11:49 -0800713func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500714 // TODO(cparsons): Define configuration transitions programmatically based
715 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400716 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500717#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400718# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500719#####################################################
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400720def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800721 if attr.os == "android" and attr.arch == "target":
Cole Faust319abae2023-06-06 15:12:49 -0700722 target = "mixed_builds_product-{VARIANT}"
Cole Faustb85d1a12022-11-08 18:14:01 -0800723 else:
Cole Faust319abae2023-06-06 15:12:49 -0700724 target = "mixed_builds_product-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Yu Liue4312402023-01-18 09:15:31 -0800725 apex_name = ""
726 if attr.within_apex:
727 # //build/bazel/rules/apex:apex_name has to be set to a non_empty value,
728 # otherwise //build/bazel/rules/apex:non_apex will be true and the
729 # "-D__ANDROID_APEX__" compiler flag will be missing. Apex_name is used
730 # in some validation on bazel side which don't really apply in mixed
731 # build because soong will do the work, so we just set it to a fixed
732 # value here.
733 apex_name = "dcla_apex"
734 outputs = {
Jingwen Chen583ab212023-05-30 09:45:23 +0000735 "//command_line_option:platforms": "@soong_injection//product_config_platforms:%s" % target,
Yu Liue4312402023-01-18 09:15:31 -0800736 "@//build/bazel/rules/apex:within_apex": attr.within_apex,
737 "@//build/bazel/rules/apex:min_sdk_version": attr.apex_sdk_version,
738 "@//build/bazel/rules/apex:apex_name": apex_name,
Spandan Das40b79f82023-06-25 20:56:06 +0000739 "@//build/bazel/rules/apex:api_domain": attr.api_domain,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500740 }
741
Yu Liue4312402023-01-18 09:15:31 -0800742 return outputs
743
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400744_config_node_transition = transition(
745 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500746 inputs = [],
747 outputs = [
748 "//command_line_option:platforms",
Yu Liue4312402023-01-18 09:15:31 -0800749 "@//build/bazel/rules/apex:within_apex",
750 "@//build/bazel/rules/apex:min_sdk_version",
751 "@//build/bazel/rules/apex:apex_name",
Spandan Das40b79f82023-06-25 20:56:06 +0000752 "@//build/bazel/rules/apex:api_domain",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500753 ],
754)
755
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400756def _passthrough_rule_impl(ctx):
757 return [DefaultInfo(files = depset(ctx.files.deps))]
758
759config_node = rule(
760 implementation = _passthrough_rule_impl,
761 attrs = {
Yu Liue4312402023-01-18 09:15:31 -0800762 "arch" : attr.string(mandatory = True),
763 "os" : attr.string(mandatory = True),
764 "within_apex" : attr.bool(default = False),
765 "apex_sdk_version" : attr.string(mandatory = True),
Spandan Das40b79f82023-06-25 20:56:06 +0000766 "api_domain" : attr.string(mandatory = True),
Yu Liue4312402023-01-18 09:15:31 -0800767 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400768 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
769 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500770)
771
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400772
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500773# Rule representing the root of the build, to depend on all Bazel targets that
774# are required for the build. Building this target will build the entire Bazel
775# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400776mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400777 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500778 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400779 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500780 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400781)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500782
783def _phony_root_impl(ctx):
784 return []
785
786# Rule to depend on other targets but build nothing.
787# This is useful as follows: building a target of this rule will generate
788# symlink forests for all dependencies of the target, without executing any
789# actions of the build.
790phony_root = rule(
791 implementation = _phony_root_impl,
792 attrs = {"deps" : attr.label_list()},
793)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400794`
Cole Faustb85d1a12022-11-08 18:14:01 -0800795
796 productReplacer := strings.NewReplacer(
797 "{PRODUCT}", context.targetProduct,
798 "{VARIANT}", context.targetBuildVariant)
799
800 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400801}
802
Sasha Smundak39a301c2022-12-29 17:11:49 -0800803func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500804 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
805 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400806 formatString := `
807# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400808load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
809
810%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400811
812mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400813 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000814 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400815)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500816
817phony_root(name = "phonyroot",
818 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000819 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500820)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400821`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400822 configNodeFormatString := `
823config_node(name = "%s",
824 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400825 os = "%s",
Yu Liue4312402023-01-18 09:15:31 -0800826 within_apex = %s,
827 apex_sdk_version = "%s",
Spandan Das40b79f82023-06-25 20:56:06 +0000828 api_domain = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400829 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000830 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400831)
832`
833
834 configNodesSection := ""
835
Chris Parsons787fb362021-10-14 18:43:51 -0400836 labelsByConfig := map[string][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500837
838 for _, val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200839 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400840 configString := getConfigString(val)
841 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400842 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400843
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500844 // Configs need to be sorted to maintain determinism of the BUILD file.
845 sortedConfigs := make([]string, 0, len(labelsByConfig))
846 for val := range labelsByConfig {
847 sortedConfigs = append(sortedConfigs, val)
848 }
849 sort.Slice(sortedConfigs, func(i, j int) bool { return sortedConfigs[i] < sortedConfigs[j] })
850
Jingwen Chen1e347862021-09-02 12:11:49 +0000851 allLabels := []string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500852 for _, configString := range sortedConfigs {
853 labels := labelsByConfig[configString]
Chris Parsons787fb362021-10-14 18:43:51 -0400854 configTokens := strings.Split(configString, "|")
Yu Liue4312402023-01-18 09:15:31 -0800855 if len(configTokens) < 2 {
Chris Parsons787fb362021-10-14 18:43:51 -0400856 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000857 }
Chris Parsons787fb362021-10-14 18:43:51 -0400858 archString := configTokens[0]
859 osString := configTokens[1]
Yu Liue4312402023-01-18 09:15:31 -0800860 withinApex := "False"
861 apexSdkVerString := ""
Spandan Das40b79f82023-06-25 20:56:06 +0000862 apiDomainString := ""
863 if osString == "android" {
864 // api domains are meaningful only for device variants
865 apiDomainString = "system"
866 }
Chris Parsons787fb362021-10-14 18:43:51 -0400867 targetString := fmt.Sprintf("%s_%s", osString, archString)
Yu Liue4312402023-01-18 09:15:31 -0800868 if len(configTokens) > 2 {
869 targetString += "_" + configTokens[2]
870 if configTokens[2] == withinApexToString(true) {
871 withinApex = "True"
872 }
873 }
874 if len(configTokens) > 3 {
875 targetString += "_" + configTokens[3]
876 apexSdkVerString = configTokens[3]
877 }
Spandan Das40b79f82023-06-25 20:56:06 +0000878 if len(configTokens) > 4 {
879 apiDomainString = configTokens[4]
880 targetString += "_" + apiDomainString
881 }
Chris Parsons787fb362021-10-14 18:43:51 -0400882 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
883 labelsString := strings.Join(labels, ",\n ")
Spandan Das40b79f82023-06-25 20:56:06 +0000884 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, withinApex, apexSdkVerString, apiDomainString,
Yu Liue4312402023-01-18 09:15:31 -0800885 labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400886 }
887
Jingwen Chen1e347862021-09-02 12:11:49 +0000888 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400889}
890
Chris Parsons944e7d02021-03-11 11:08:46 -0500891func indent(original string) string {
892 result := ""
893 for _, line := range strings.Split(original, "\n") {
894 result += " " + line + "\n"
895 }
896 return result
897}
898
Chris Parsons808d84c2021-03-09 20:43:32 -0500899// Returns the file contents of the buildroot.cquery file that should be used for the cquery
900// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800901// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500902// and grouped by their request type. The data retrieved for each label depends on its
903// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800904func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400905 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons38851d82023-03-15 00:19:32 -0400906 requestTypes := []cqueryRequest{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500907 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500908 cqueryId := getCqueryId(val)
909 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
Chris Parsons38851d82023-03-15 00:19:32 -0400910 if _, seenKey := requestTypeToCqueryIdEntries[val.requestType]; !seenKey {
911 requestTypes = append(requestTypes, val.requestType)
912 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500913 requestTypeToCqueryIdEntries[val.requestType] =
914 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
915 }
916 labelRegistrationMapSection := ""
917 functionDefSection := ""
918 mainSwitchSection := ""
919
920 mapDeclarationFormatString := `
921%s = {
922 %s
923}
924`
925 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800926def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500927%s
928`
929 mainSwitchSectionFormatString := `
930 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800931 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500932`
933
Chris Parsons38851d82023-03-15 00:19:32 -0400934 for _, requestType := range requestTypes {
Chris Parsons944e7d02021-03-11 11:08:46 -0500935 labelMapName := requestType.Name() + "_Labels"
936 functionName := requestType.Name() + "_Fn"
937 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
938 labelMapName,
939 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
940 functionDefSection += fmt.Sprintf(functionDefFormatString,
941 functionName,
942 indent(requestType.StarlarkFunctionBody()))
943 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
944 labelMapName, functionName)
945 }
946
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400947 formatString := `
948# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400949
Cole Faustb85d1a12022-11-08 18:14:01 -0800950{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500951
Cole Faustb85d1a12022-11-08 18:14:01 -0800952{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500953
954def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400955 # TODO(b/199363072): filegroups and file targets aren't associated with any
956 # specific platform architecture in mixed builds. This is consistent with how
957 # Soong treats filegroups, but it may not be the case with manually-written
958 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500959 buildoptions = build_options(target)
Yu Liue4312402023-01-18 09:15:31 -0800960
Jingwen Chen8f222742021-10-07 12:02:23 +0000961 if buildoptions == None:
962 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400963 # any specific platform architecture in mixed builds, so use the host.
964 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -0800965 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500966 if len(platforms) != 1:
967 # An individual configured target should have only one platform architecture.
968 # Note that it's fine for there to be multiple architectures for the same label,
969 # but each is its own configured target.
970 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -0800971 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -0500972 if platform_name == "host":
973 return "HOST"
Cole Faust319abae2023-06-06 15:12:49 -0700974 if not platform_name.startswith("mixed_builds_product-{TARGET_BUILD_VARIANT}"):
975 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))
976 platform_name = platform_name.removeprefix("mixed_builds_product-{TARGET_BUILD_VARIANT}").removeprefix("_")
Yu Liue4312402023-01-18 09:15:31 -0800977 config_key = ""
Cole Faustb85d1a12022-11-08 18:14:01 -0800978 if not platform_name:
Yu Liue4312402023-01-18 09:15:31 -0800979 config_key = "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400980 elif platform_name.startswith("android_"):
Yu Liue4312402023-01-18 09:15:31 -0800981 config_key = platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400982 elif platform_name.startswith("linux_"):
Yu Liue4312402023-01-18 09:15:31 -0800983 config_key = platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400984 else:
Cole Faust319abae2023-06-06 15:12:49 -0700985 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 -0500986
Yu Liue4312402023-01-18 09:15:31 -0800987 within_apex = buildoptions.get("//build/bazel/rules/apex:within_apex")
988 apex_sdk_version = buildoptions.get("//build/bazel/rules/apex:min_sdk_version")
Spandan Das40b79f82023-06-25 20:56:06 +0000989 api_domain = buildoptions.get("//build/bazel/rules/apex:api_domain")
Yu Liue4312402023-01-18 09:15:31 -0800990
991 if within_apex:
992 config_key += "|within_apex"
993 if apex_sdk_version != None and len(apex_sdk_version) > 0:
994 config_key += "|" + apex_sdk_version
Spandan Das40b79f82023-06-25 20:56:06 +0000995 if api_domain != None and len(api_domain) > 0:
996 config_key += "|" + api_domain
Yu Liue4312402023-01-18 09:15:31 -0800997
998 return config_key
999
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001000def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -05001001 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -05001002
Chris Parsons86dc2c22022-09-28 14:58:41 -04001003 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
1004 if id_string.startswith("//"):
1005 id_string = "@" + id_string
1006
Cole Faustb85d1a12022-11-08 18:14:01 -08001007 {MAIN_SWITCH_SECTION}
1008
Chris Parsons944e7d02021-03-11 11:08:46 -05001009 # This target was not requested via cquery, and thus must be a dependency
1010 # of a requested target.
1011 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001012`
Cole Faustb85d1a12022-11-08 18:14:01 -08001013 replacer := strings.NewReplacer(
1014 "{TARGET_PRODUCT}", context.targetProduct,
1015 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
1016 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
1017 "{FUNCTION_DEF_SECTION}", functionDefSection,
1018 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001019
Cole Faustb85d1a12022-11-08 18:14:01 -08001020 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001021}
1022
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001023// Returns a path containing build-related metadata required for interfacing
1024// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001025func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001026 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -05001027}
1028
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001029// Returns the path where the contents of the @soong_injection repository live.
1030// It is used by Soong to tell Bazel things it cannot over the command line.
1031func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001032 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001033}
1034
1035// Returns the path of the synthetic Bazel workspace that contains a symlink
1036// forest composed the whole source tree and BUILD files generated by bp2build.
1037func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001038 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001039}
1040
Jingwen Chen8c523582021-06-01 11:19:53 +00001041// Returns the path to the top level out dir ($OUT_DIR).
1042func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001043 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +00001044}
1045
Sasha Smundak4975c822022-11-16 15:28:18 -08001046const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
1047
1048var (
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001049 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
1050 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
1051 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
1052 allBazelCommands = []bazelCommand{aqueryCmd, cqueryCmd, buildCmd}
Sasha Smundak4975c822022-11-16 15:28:18 -08001053)
1054
Cole Faustbc65a3f2023-08-01 16:38:55 +00001055func GetBazelSandwichCqueryRequests(config Config) ([]cqueryKey, error) {
1056 result := make([]cqueryKey, 0, len(allowlists.BazelSandwichTargets))
1057 // Note that bazel "targets" are different from soong "targets", the bazel targets are
1058 // synonymous with soong modules, and soong targets are a configuration a module is built in.
1059 for _, target := range allowlists.BazelSandwichTargets {
1060 var soongTarget Target
1061 if target.Host {
1062 soongTarget = config.BuildOSTarget
1063 } else {
1064 soongTarget = config.AndroidCommonTarget
1065 if soongTarget.Os.Class != Device {
1066 // kernel-build-tools seems to set the AndroidCommonTarget to a linux host
1067 // target for some reason, disable device builds in that case.
1068 continue
1069 }
1070 }
1071
1072 result = append(result, cqueryKey{
1073 label: target.Label,
1074 requestType: cquery.GetOutputFiles,
1075 configKey: configKey{
1076 arch: soongTarget.Arch.String(),
1077 osType: soongTarget.Os,
1078 },
1079 })
1080 }
1081 return result, nil
1082}
1083
1084// QueueBazelSandwichCqueryRequests queues cquery requests for all the bazel labels in
1085// bazel_sandwich_targets. These will later be given phony targets so that they can be built on the
1086// command line.
1087func (context *mixedBuildBazelContext) QueueBazelSandwichCqueryRequests(config Config) error {
1088 requests, err := GetBazelSandwichCqueryRequests(config)
1089 if err != nil {
1090 return err
1091 }
1092 for _, request := range requests {
1093 context.QueueBazelRequest(request.label, request.requestType, request.configKey)
1094 }
1095
1096 return nil
1097}
1098
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001099// Issues commands to Bazel to receive results for all cquery requests
1100// queued in the BazelContext.
Liz Kammer690fbac2023-02-10 11:11:17 -05001101func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx invokeBazelContext) error {
1102 eventHandler := ctx.GetEventHandler()
1103 eventHandler.Begin("bazel")
1104 defer eventHandler.End("bazel")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001105
Sasha Smundak4975c822022-11-16 15:28:18 -08001106 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
1107 if err := os.MkdirAll(metricsDir, 0777); err != nil {
1108 return err
1109 }
1110 }
1111 context.results = make(map[cqueryKey]string)
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001112 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001113 return err
1114 }
1115 if err := context.runAquery(config, ctx); err != nil {
1116 return err
1117 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001118 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001119 return err
1120 }
1121
1122 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001123 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -08001124 return nil
1125}
1126
Liz Kammer690fbac2023-02-10 11:11:17 -05001127func (context *mixedBuildBazelContext) runCquery(config Config, ctx invokeBazelContext) error {
1128 eventHandler := ctx.GetEventHandler()
1129 eventHandler.Begin("cquery")
1130 defer eventHandler.End("cquery")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001131 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +02001132 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
1133 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
1134 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -05001135 if err != nil {
1136 return err
1137 }
1138 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001139 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001140 return err
1141 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001142 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001143 return err
1144 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001145 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001146 return err
1147 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001148 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001149 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001150 return err
1151 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001152
Yu Liue4312402023-01-18 09:15:31 -08001153 extraFlags := []string{"--output=starlark", "--starlark:file=" + absolutePath(cqueryFileRelpath)}
1154 if Bool(config.productVariables.ClangCoverage) {
1155 extraFlags = append(extraFlags, "--collect_code_coverage")
1156 }
1157
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001158 cqueryCmdRequest := context.createBazelCommand(config, bazel.CqueryBuildRootRunName, cqueryCmd, extraFlags...)
1159 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCmdRequest, context.paths, eventHandler)
Wei Licbd181c2022-11-16 08:59:23 -08001160 if cqueryErr != nil {
1161 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001162 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001163 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", context.printableCqueryCommand(cqueryCmdRequest))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001164 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001165 return err
1166 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001167 cqueryResults := map[string]string{}
1168 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1169 if strings.Contains(outputLine, ">>") {
1170 splitLine := strings.SplitN(outputLine, ">>", 2)
1171 cqueryResults[splitLine[0]] = splitLine[1]
1172 }
1173 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001174 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001175 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001176 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001177 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001178 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001179 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001180 }
1181 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001182 return nil
1183}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001184
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001185func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1186 oldContents, err := os.ReadFile(path)
1187 if err != nil || !bytes.Equal(contents, oldContents) {
1188 err = os.WriteFile(path, contents, perm)
1189 }
1190 return nil
1191}
1192
Liz Kammer690fbac2023-02-10 11:11:17 -05001193func (context *mixedBuildBazelContext) runAquery(config Config, ctx invokeBazelContext) error {
1194 eventHandler := ctx.GetEventHandler()
1195 eventHandler.Begin("aquery")
1196 defer eventHandler.End("aquery")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001197 // Issue an aquery command to retrieve action information about the bazel build tree.
1198 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001199 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1200 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001201 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001202 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001203 extraFlags = append(extraFlags, "--collect_code_coverage")
1204 paths := make([]string, 0, 2)
1205 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001206 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001207 // TODO(b/259404593) convert path wildcard to regex values
1208 if p[i] == "*" {
1209 p[i] = ".*"
1210 }
1211 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001212 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1213 }
1214 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1215 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1216 }
1217 if len(paths) > 0 {
1218 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001219 }
1220 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001221 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.AqueryBuildRootRunName, aqueryCmd,
1222 extraFlags...), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001223 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001224 return err
1225 }
Liz Kammer690fbac2023-02-10 11:11:17 -05001226 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001227 return err
1228}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001229
Liz Kammer690fbac2023-02-10 11:11:17 -05001230func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx invokeBazelContext) error {
1231 eventHandler := ctx.GetEventHandler()
1232 eventHandler.Begin("symlinks")
1233 defer eventHandler.End("symlinks")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001234 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1235 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1236 // but some of symlinks may be required to resolve source dependencies of the build.
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001237 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.BazelBuildPhonyRootRunName, buildCmd), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001238 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001239}
Chris Parsonsa798d962020-10-12 23:44:08 -04001240
Liz Kammera4655a92023-02-10 17:17:28 -05001241func (context *mixedBuildBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001242 return context.buildStatements
1243}
1244
Sasha Smundak39a301c2022-12-29 17:11:49 -08001245func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001246 return context.depsets
1247}
1248
Sasha Smundak39a301c2022-12-29 17:11:49 -08001249func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001250 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001251}
1252
Chris Parsonsa798d962020-10-12 23:44:08 -04001253// Singleton used for registering BUILD file ninja dependencies (needed
1254// for correctness of builds which use Bazel.
1255func BazelSingleton() Singleton {
1256 return &bazelSingleton{}
1257}
1258
1259type bazelSingleton struct{}
1260
1261func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001262 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001263 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001264 return
1265 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001266
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001267 // Add ninja file dependencies for files which all bazel invocations require.
1268 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001269 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001270 ctx.AddNinjaFileDeps(bazelBuildList)
1271
Sasha Smundak0e87b182022-12-01 11:46:11 -08001272 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001273 if err != nil {
1274 ctx.Errorf(err.Error())
1275 }
1276 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1277 for _, file := range files {
1278 ctx.AddNinjaFileDeps(file)
1279 }
1280
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001281 depsetHashToDepset := map[string]bazel.AqueryDepset{}
1282
Chris Parsons1a7aca02022-04-25 22:35:15 -04001283 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001284 depsetHashToDepset[depset.ContentHash] = depset
1285
Chris Parsons1a7aca02022-04-25 22:35:15 -04001286 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001287 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001288 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1289 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001290 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1291 }
1292 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001293 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1294 if artifactPath == "bazel-out/volatile-status.txt" {
1295 // See https://bazel.build/docs/user-manual#workspace-status
1296 orderOnlies = append(orderOnlies, pathInBazelOut)
1297 } else {
1298 outputs = append(outputs, pathInBazelOut)
1299 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001300 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001301 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001302 ctx.Build(pctx, BuildParams{
1303 Rule: blueprint.Phony,
1304 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1305 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001306 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001307 })
1308 }
1309
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001310 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1311 bazelOutDir := path.Join(executionRoot, "bazel-out")
Cole Faustbc65a3f2023-08-01 16:38:55 +00001312 rel, err := filepath.Rel(ctx.Config().OutDir(), executionRoot)
1313 if err != nil {
1314 ctx.Errorf("%s", err.Error())
1315 }
1316 dotdotsToOutRoot := strings.Repeat("../", strings.Count(rel, "/")+1)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001317 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Liz Kammera4655a92023-02-10 17:17:28 -05001318 // nil build statements are a valid case where we do not create an action because it is
1319 // unnecessary or handled by other processing
1320 if buildStatement == nil {
1321 continue
1322 }
Sasha Smundak1da064c2022-06-08 16:36:16 -07001323 if len(buildStatement.Command) > 0 {
1324 rule := NewRuleBuilder(pctx, ctx)
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001325 intermediateDir, intermediateDirHash := intermediatePathForSboxMixedBuildAction(ctx, buildStatement)
1326 if buildStatement.ShouldRunInSbox {
1327 // Create a rule to build the output inside a sandbox
1328 // This will create two changes of working directory
1329 // 1. From ANDROID_BUILD_TOP to sbox top
1330 // 2. From sbox top to a a synthetic mixed build execution root relative to it
1331 // Finally, the outputs will be copied to intermediateDir
1332 rule.Sbox(intermediateDir,
1333 PathForOutput(ctx, "mixed_build_sbox_intermediates", intermediateDirHash+".textproto")).
1334 SandboxInputs().
1335 // Since we will cd to mixed build execution root, set sbox's out subdir to empty
1336 // Without this, we will try to copy from $SBOX_SANDBOX_DIR/out/out/bazel/output/execroot/__main__/...
1337 SetSboxOutDirDirAsEmpty()
1338
1339 // Create another set of rules to copy files from the intermediate dir to mixed build execution root
1340 for _, outputPath := range buildStatement.OutputPaths {
1341 ctx.Build(pctx, BuildParams{
1342 Rule: CpIfChanged,
1343 Input: intermediateDir.Join(ctx, executionRoot, outputPath),
1344 Output: PathForBazelOut(ctx, outputPath),
1345 })
1346 }
1347 }
Cole Faustbc65a3f2023-08-01 16:38:55 +00001348 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx, depsetHashToDepset, dotdotsToOutRoot)
1349
Sasha Smundak1da064c2022-06-08 16:36:16 -07001350 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1351 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1352 continue
1353 }
1354 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1355 // and thus require special treatment. If BuildStatement were an interface implementing
1356 // buildRule(ctx) function, the code here would just call it.
1357 // Unfortunately, the BuildStatement is defined in
1358 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1359 // because this would cause circular dependency. So, until we move aquery processing
1360 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001361 switch buildStatement.Mnemonic {
Cole Faust950689a2023-06-21 15:07:21 -07001362 case "RepoMappingManifest":
1363 // It appears RepoMappingManifest files currently have
1364 // non-deterministic content. Just emit empty files for
1365 // now because they're unused.
1366 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1367 WriteFileRuleVerbatim(ctx, out, "")
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001368 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001369 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1370 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001371 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001372 // build-runfiles arguments are the manifest file and the target directory
1373 // where it creates the symlink tree according to this manifest (and then
1374 // writes the MANIFEST file to it).
1375 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1376 outManifestPath := outManifest.String()
1377 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1378 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1379 }
1380 outDir := filepath.Dir(outManifestPath)
1381 ctx.Build(pctx, BuildParams{
1382 Rule: buildRunfilesRule,
1383 Output: outManifest,
1384 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1385 Description: "symlink tree for " + outDir,
1386 Args: map[string]string{
1387 "outDir": outDir,
1388 },
1389 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001390 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001391 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001392 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001393 }
Cole Faustbc65a3f2023-08-01 16:38:55 +00001394
1395 // Create phony targets for all the bazel sandwich output files
1396 requests, err := GetBazelSandwichCqueryRequests(ctx.Config())
1397 if err != nil {
1398 ctx.Errorf(err.Error())
1399 }
1400 for _, request := range requests {
1401 files, err := ctx.Config().BazelContext.GetOutputFiles(request.label, request.configKey)
1402 if err != nil {
1403 ctx.Errorf(err.Error())
1404 }
1405 filesAsPaths := make([]Path, 0, len(files))
1406 for _, file := range files {
1407 filesAsPaths = append(filesAsPaths, PathForBazelOut(ctx, file))
1408 }
1409 ctx.Phony("bazel_sandwich", filesAsPaths...)
1410 }
1411 ctx.Phony("checkbuild", PathForPhony(ctx, "bazel_sandwich"))
Chris Parsonsa798d962020-10-12 23:44:08 -04001412}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001413
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001414// Returns a out dir path for a sandboxed mixed build action
1415func intermediatePathForSboxMixedBuildAction(ctx PathContext, statement *bazel.BuildStatement) (OutputPath, string) {
1416 // An artifact can be generated by a single buildstatement.
1417 // Use the hash of the first artifact to create a unique path
1418 uniqueDir := sha1.New()
1419 uniqueDir.Write([]byte(statement.OutputPaths[0]))
1420 uniqueDirHashString := hex.EncodeToString(uniqueDir.Sum(nil))
1421 return PathForOutput(ctx, "mixed_build_sbox_intermediates", uniqueDirHashString), uniqueDirHashString
1422}
1423
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001424// Register bazel-owned build statements (obtained from the aquery invocation).
Cole Faustbc65a3f2023-08-01 16:38:55 +00001425func 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 -04001426 // executionRoot is the action cwd.
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001427 if buildStatement.ShouldRunInSbox {
1428 // mkdir -p ensures that the directory exists when run via sbox
1429 cmd.Text(fmt.Sprintf("mkdir -p '%s' && cd '%s' &&", executionRoot, executionRoot))
1430 } else {
1431 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1432 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001433
1434 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1435 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001436 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001437 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001438 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001439 }
1440 cmd.Text("&&")
1441 }
1442
1443 for _, pair := range buildStatement.Env {
1444 // Set per-action env variables, if any.
1445 cmd.Flag(pair.Key + "=" + pair.Value)
1446 }
1447
Cole Faustbc65a3f2023-08-01 16:38:55 +00001448 command := buildStatement.Command
1449 command = strings.ReplaceAll(command, "{DOTDOTS_TO_OUTPUT_ROOT}", dotdotsToOutRoot)
1450
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001451 // The actual Bazel action.
Cole Faustbc65a3f2023-08-01 16:38:55 +00001452 if len(command) > 16*1024 {
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001453 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
Cole Faustbc65a3f2023-08-01 16:38:55 +00001454 WriteFileRule(ctx, commandFile, command)
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001455
1456 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1457 } else {
Cole Faustbc65a3f2023-08-01 16:38:55 +00001458 cmd.Text(command)
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001459 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001460
1461 for _, outputPath := range buildStatement.OutputPaths {
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001462 if buildStatement.ShouldRunInSbox {
1463 // The full path has three components that get joined together
1464 // 1. intermediate output dir that `sbox` will place the artifacts at
1465 // 2. mixed build execution root
1466 // 3. artifact path returned by aquery
1467 intermediateDir, _ := intermediatePathForSboxMixedBuildAction(ctx, buildStatement)
1468 cmd.ImplicitOutput(intermediateDir.Join(ctx, executionRoot, outputPath))
1469 } else {
1470 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1471 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001472 }
1473 for _, inputPath := range buildStatement.InputPaths {
1474 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1475 }
1476 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
Spandan Dasaf4ccaa2023-06-29 01:15:51 +00001477 if buildStatement.ShouldRunInSbox {
1478 // Bazel depsets are phony targets that are used to group files.
1479 // We need to copy the grouped files into the sandbox
1480 ds, _ := depsetHashToDepset[inputDepsetHash]
1481 cmd.Implicits(PathsForBazelOut(ctx, ds.DirectArtifacts))
1482 } else {
1483 otherDepsetName := bazelDepsetName(inputDepsetHash)
1484 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1485 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001486 }
Cole Faustbc65a3f2023-08-01 16:38:55 +00001487 for _, implicitPath := range buildStatement.ImplicitDeps {
1488 cmd.Implicit(PathForArbitraryOutput(ctx, implicitPath))
1489 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001490
1491 if depfile := buildStatement.Depfile; depfile != nil {
1492 // The paths in depfile are relative to `executionRoot`.
1493 // Hence, they need to be corrected by replacing "bazel-out"
1494 // with the full `bazelOutDir`.
1495 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1496 // would be deemed missing.
1497 // (Note: The regexp uses a capture group because the version of sed
1498 // does not support a look-behind pattern.)
1499 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1500 bazelOutDir, *depfile)
1501 cmd.Text(replacement)
1502 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1503 }
1504
1505 for _, symlinkPath := range buildStatement.SymlinkPaths {
1506 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1507 }
1508}
1509
Chris Parsons8d6e4332021-02-22 16:13:50 -05001510func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001511 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001512}
1513
Chris Parsons787fb362021-10-14 18:43:51 -04001514func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001515 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001516 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001517 if key.configKey.osType.Class == Device {
1518 // For the generic Android, the expected result is "target|android", which
1519 // corresponds to the product_variable_config named "android_target" in
1520 // build/bazel/platforms/BUILD.bazel.
1521 arch = "target"
1522 } else {
1523 // Use host platform, which is currently hardcoded to be x86_64.
1524 arch = "x86_64"
1525 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001526 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001527 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001528 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001529 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001530 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001531 }
Yu Liue4312402023-01-18 09:15:31 -08001532 keyString := arch + "|" + osName
1533 if key.configKey.apexKey.WithinApex {
1534 keyString += "|" + withinApexToString(key.configKey.apexKey.WithinApex)
1535 }
1536
1537 if len(key.configKey.apexKey.ApexSdkVersion) > 0 {
1538 keyString += "|" + key.configKey.apexKey.ApexSdkVersion
1539 }
1540
Spandan Das40b79f82023-06-25 20:56:06 +00001541 if len(key.configKey.apexKey.ApiDomain) > 0 {
1542 keyString += "|" + key.configKey.apexKey.ApiDomain
1543 }
1544
Yu Liue4312402023-01-18 09:15:31 -08001545 return keyString
Chris Parsons787fb362021-10-14 18:43:51 -04001546}
1547
Chris Parsonsf874e462022-05-10 13:50:12 -04001548func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001549 return configKey{
1550 // use string because Arch is not a valid key in go
1551 arch: ctx.Arch().String(),
1552 osType: ctx.Os(),
1553 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001554}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001555
Yu Liue4312402023-01-18 09:15:31 -08001556func GetConfigKeyApexVariant(ctx BaseModuleContext, apexKey *ApexConfigKey) configKey {
1557 configKey := GetConfigKey(ctx)
1558
1559 if apexKey != nil {
1560 configKey.apexKey = ApexConfigKey{
1561 WithinApex: apexKey.WithinApex,
1562 ApexSdkVersion: apexKey.ApexSdkVersion,
Spandan Das40b79f82023-06-25 20:56:06 +00001563 ApiDomain: apexKey.ApiDomain,
Yu Liue4312402023-01-18 09:15:31 -08001564 }
1565 }
1566
1567 return configKey
1568}
1569
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001570func bazelDepsetName(contentHash string) string {
1571 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001572}