blob: d5ccfcad857096b540c718b0a40f2c186af8c2ad [file] [log] [blame]
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001// Copyright 2020 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package android
16
17import (
18 "bytes"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040019 "fmt"
20 "os"
Usta Shresthaacd5a0c2022-06-22 11:20:50 -040021 "path"
Chris Parsonsa798d962020-10-12 23:44:08 -040022 "path/filepath"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040023 "runtime"
Cole Faust705968d2022-12-14 11:32:05 -080024 "sort"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040025 "strings"
26 "sync"
Chris Parsonsa798d962020-10-12 23:44:08 -040027
Chris Parsonsad876012022-08-20 14:48:32 -040028 "android/soong/android/allowlists"
Chris Parsons944e7d02021-03-11 11:08:46 -050029 "android/soong/bazel/cquery"
Jingwen Chen1e347862021-09-02 12:11:49 +000030 "android/soong/shared"
Cole Faust8a161be2023-06-14 15:45:12 -070031 "android/soong/starlark_import"
Jingwen Chen379221f2023-03-30 13:19:29 +000032
Chris Parsons1a7aca02022-04-25 22:35:15 -040033 "github.com/google/blueprint"
Liz Kammer690fbac2023-02-10 11:11:17 -050034 "github.com/google/blueprint/metrics"
Liz Kammer8206d4f2021-03-03 16:40:52 -050035
Patrice Arruda05ab2d02020-12-12 06:24:26 +000036 "android/soong/bazel"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040037)
38
Sasha Smundak1da064c2022-06-08 16:36:16 -070039var (
Sasha Smundakc180dbd2022-07-03 14:55:58 -070040 _ = pctx.HostBinToolVariable("bazelBuildRunfilesTool", "build-runfiles")
41 buildRunfilesRule = pctx.AndroidStaticRule("bazelBuildRunfiles", blueprint.RuleParams{
42 Command: "${bazelBuildRunfilesTool} ${in} ${outDir}",
43 Depfile: "",
44 Description: "",
45 CommandDeps: []string{"${bazelBuildRunfilesTool}"},
46 }, "outDir")
Sasha Smundak1da064c2022-06-08 16:36:16 -070047)
48
Liz Kammerc13f7852023-05-17 13:01:48 -040049func registerMixedBuildsMutator(ctx RegisterMutatorsContext) {
50 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
Chris Parsonsf874e462022-05-10 13:50:12 -040051}
52
53func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammerc13f7852023-05-17 13:01:48 -040054 ctx.FinalDepsMutators(registerMixedBuildsMutator)
Chris Parsonsf874e462022-05-10 13:50:12 -040055}
56
57func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
58 if m := ctx.Module(); m.Enabled() {
59 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
MarkDacekf47e1422023-04-19 16:47:36 +000060 mixedBuildEnabled := MixedBuildsEnabled(ctx)
61 queueMixedBuild := mixedBuildMod.IsMixedBuildSupported(ctx) && mixedBuildEnabled == MixedBuildEnabled
MarkDacek9c094ca2023-03-16 19:15:19 +000062 if queueMixedBuild {
Chris Parsonsf874e462022-05-10 13:50:12 -040063 mixedBuildMod.QueueBazelCall(ctx)
64 }
65 }
66 }
67}
68
Liz Kammerf29df7c2021-04-02 13:37:39 -040069type cqueryRequest interface {
70 // Name returns a string name for this request type. Such request type names must be unique,
71 // and must only consist of alphanumeric characters.
72 Name() string
73
74 // StarlarkFunctionBody returns a starlark function body to process this request type.
75 // The returned string is the body of a Starlark function which obtains
76 // all request-relevant information about a target and returns a string containing
77 // this information.
78 // The function should have the following properties:
Cole Faust97d15272022-11-22 14:08:59 -080079 // - The arguments are `target` (a configured target) and `id_string` (the label + configuration).
Liz Kammerf29df7c2021-04-02 13:37:39 -040080 // - The return value must be a string.
81 // - The function body should not be indented outside of its own scope.
82 StarlarkFunctionBody() string
83}
84
Chris Parsons787fb362021-10-14 18:43:51 -040085// Portion of cquery map key to describe target configuration.
86type configKey struct {
Yu Liue4312402023-01-18 09:15:31 -080087 arch string
88 osType OsType
89 apexKey ApexConfigKey
90}
91
92type ApexConfigKey struct {
93 WithinApex bool
94 ApexSdkVersion string
Spandan Das40b79f82023-06-25 20:56:06 +000095 ApiDomain string
Yu Liue4312402023-01-18 09:15:31 -080096}
97
98func (c ApexConfigKey) String() string {
Spandan Das40b79f82023-06-25 20:56:06 +000099 return fmt.Sprintf("%s_%s_%s", withinApexToString(c.WithinApex), c.ApexSdkVersion, c.ApiDomain)
Yu Liue4312402023-01-18 09:15:31 -0800100}
101
102func withinApexToString(withinApex bool) string {
103 if withinApex {
104 return "within_apex"
105 }
106 return ""
Chris Parsons787fb362021-10-14 18:43:51 -0400107}
108
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700109func (c configKey) String() string {
Yu Liue4312402023-01-18 09:15:31 -0800110 return fmt.Sprintf("%s::%s::%s", c.arch, c.osType, c.apexKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700111}
112
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400113// Map key to describe bazel cquery requests.
114type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400115 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400116 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400117 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400118}
119
Chris Parsons86dc2c22022-09-28 14:58:41 -0400120func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
121 if strings.HasPrefix(label, "//") {
122 // Normalize Bazel labels to specify main repository explicitly.
123 label = "@" + label
124 }
125 return cqueryKey{label, cqueryRequest, cfgKey}
126}
127
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700128func (c cqueryKey) String() string {
129 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700130}
131
Liz Kammer690fbac2023-02-10 11:11:17 -0500132type invokeBazelContext interface {
133 GetEventHandler() *metrics.EventHandler
134}
135
Chris Parsonsf874e462022-05-10 13:50:12 -0400136// BazelContext is a context object useful for interacting with Bazel during
137// the course of a build. Use of Bazel to evaluate part of the build graph
138// is referred to as a "mixed build". (Some modules are managed by Soong,
139// some are managed by Bazel). To facilitate interop between these build
140// subgraphs, Soong may make requests to Bazel and evaluate their responses
141// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400142type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400143 // Add a cquery request to the bazel request queue. All queued requests
144 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
145 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
146
147 // ** Cquery Results Retrieval Functions
148 // The below functions pertain to retrieving cquery results from a prior
149 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400150
151 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400152 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500153
Chris Parsons944e7d02021-03-11 11:08:46 -0500154 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400155 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400156
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700157 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400158 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700159
Sasha Smundakedd16662022-10-07 14:44:50 -0700160 // Returns the results of the GetCcUnstrippedInfo query
161 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
162
Spandan Dasbd156812023-06-05 22:43:13 +0000163 // Returns the results of the GetPrebuiltFileInfo query
164 GetPrebuiltFileInfo(label string, cfgKey configKey) (cquery.PrebuiltFileInfo, error)
165
Chris Parsonsf874e462022-05-10 13:50:12 -0400166 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400167
168 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800169 // queued in the BazelContext. The ctx argument is optional and is only
170 // used for performance data collection
Liz Kammer690fbac2023-02-10 11:11:17 -0500171 InvokeBazel(config Config, ctx invokeBazelContext) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400172
Chris Parsonsad876012022-08-20 14:48:32 -0400173 // Returns true if Bazel handling is enabled for the module with the given name.
174 // Note that this only implies "bazel mixed build" allowlisting. The caller
175 // should independently verify the module is eligible for Bazel handling
176 // (for example, that it is MixedBuildBuildable).
Yu Liue4312402023-01-18 09:15:31 -0800177 IsModuleNameAllowed(moduleName string, withinApex bool) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500178
179 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
180 OutputBase() string
181
182 // Returns build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500183 BuildStatementsToRegister() []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400184
185 // Returns the depsets defined in Bazel's aquery response.
186 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400187}
188
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400189type bazelRunner interface {
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000190 issueBazelCommand(cmdRequest bazel.CmdRequest, paths *bazelPaths, eventHandler *metrics.EventHandler) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400191}
192
193type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000194 homeDir string
195 bazelPath string
196 outputBase string
197 workspaceDir string
198 soongOutDir string
199 metricsDir string
200 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400201}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400202
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400203// A context object which tracks queued requests that need to be made to Bazel,
204// and their results after the requests have been made.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800205type mixedBuildBazelContext struct {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400206 bazelRunner
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500207 paths *bazelPaths
208 // cquery requests that have not yet been issued to Bazel. This list is maintained
209 // in a sorted state, and is guaranteed to have no duplicates.
210 requests []cqueryKey
211 requestMutex sync.Mutex // requests can be written in parallel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400212
213 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500214
215 // Build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500216 buildStatements []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400217
218 // Depsets which should be used for Bazel's build statements.
219 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400220
221 // Per-module allowlist/denylist functionality to control whether analysis of
222 // modules are handled by Bazel. For modules which do not have a Bazel definition
223 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
224 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
225 // Per-module denylist to opt modules out of bazel handling.
226 bazelDisabledModules map[string]bool
227 // Per-module allowlist to opt modules in to bazel handling.
228 bazelEnabledModules map[string]bool
Yu Liue4312402023-01-18 09:15:31 -0800229 // DCLA modules are enabled when used in apex.
230 bazelDclaEnabledModules map[string]bool
Cole Faustb85d1a12022-11-08 18:14:01 -0800231
232 targetProduct string
233 targetBuildVariant string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400234}
235
Sasha Smundak39a301c2022-12-29 17:11:49 -0800236var _ BazelContext = &mixedBuildBazelContext{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400237
238// A bazel context to use when Bazel is disabled.
239type noopBazelContext struct{}
240
241var _ BazelContext = noopBazelContext{}
242
243// A bazel context to use for tests.
244type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400245 OutputBaseDir string
246
Spandan Dasbd156812023-06-05 22:43:13 +0000247 LabelToOutputFiles map[string][]string
248 LabelToCcInfo map[string]cquery.CcInfo
249 LabelToPythonBinary map[string]string
250 LabelToApexInfo map[string]cquery.ApexInfo
251 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
252 LabelToPrebuiltFileInfo map[string]cquery.PrebuiltFileInfo
Yu Liue4312402023-01-18 09:15:31 -0800253
254 BazelRequests map[string]bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400255}
256
Yu Liue4312402023-01-18 09:15:31 -0800257func (m MockBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
258 key := BuildMockBazelContextRequestKey(label, requestType, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
259 if m.BazelRequests == nil {
260 m.BazelRequests = make(map[string]bool)
261 }
262 m.BazelRequests[key] = true
Chris Parsons8d6e4332021-02-22 16:13:50 -0500263}
264
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700265func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500266 result, ok := m.LabelToOutputFiles[label]
267 if !ok {
268 return []string{}, fmt.Errorf("no target with label %q in LabelToOutputFiles", label)
269 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400270 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400271}
272
Yu Liue4312402023-01-18 09:15:31 -0800273func (m MockBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500274 result, ok := m.LabelToCcInfo[label]
275 if !ok {
Yu Liue4312402023-01-18 09:15:31 -0800276 key := BuildMockBazelContextResultKey(label, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
277 result, ok = m.LabelToCcInfo[key]
278 if !ok {
279 return cquery.CcInfo{}, fmt.Errorf("no target with label %q in LabelToCcInfo", label)
280 }
Sam Delmericoce39f832023-01-23 14:04:24 -0500281 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400282 return result, nil
283}
284
Liz Kammerbe6a7122022-11-04 16:05:11 -0400285func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500286 result, ok := m.LabelToApexInfo[label]
287 if !ok {
288 return cquery.ApexInfo{}, fmt.Errorf("no target with label %q in LabelToApexInfo", label)
289 }
Liz Kammer0e255ef2022-11-04 16:07:04 -0400290 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700291}
292
Sasha Smundakedd16662022-10-07 14:44:50 -0700293func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500294 result, ok := m.LabelToCcBinary[label]
295 if !ok {
296 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no target with label %q in LabelToCcBinary", label)
297 }
Sasha Smundakedd16662022-10-07 14:44:50 -0700298 return result, nil
299}
300
Spandan Dasbd156812023-06-05 22:43:13 +0000301func (m MockBazelContext) GetPrebuiltFileInfo(label string, _ configKey) (cquery.PrebuiltFileInfo, error) {
302 result, ok := m.LabelToPrebuiltFileInfo[label]
303 if !ok {
304 return cquery.PrebuiltFileInfo{}, fmt.Errorf("no target with label %q in LabelToPrebuiltFileInfo", label)
305 }
306 return result, nil
307}
308
Liz Kammer690fbac2023-02-10 11:11:17 -0500309func (m MockBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400310 panic("unimplemented")
311}
312
Yu Liue4312402023-01-18 09:15:31 -0800313func (m MockBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400314 return true
315}
316
Liz Kammera92e8442021-04-07 20:25:21 -0400317func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500318
Liz Kammera4655a92023-02-10 17:17:28 -0500319func (m MockBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
320 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500321}
322
Chris Parsons1a7aca02022-04-25 22:35:15 -0400323func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
324 return []bazel.AqueryDepset{}
325}
326
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400327var _ BazelContext = MockBazelContext{}
328
Yu Liue4312402023-01-18 09:15:31 -0800329func BuildMockBazelContextRequestKey(label string, request cqueryRequest, arch string, osType OsType, apexKey ApexConfigKey) string {
330 cfgKey := configKey{
331 arch: arch,
332 osType: osType,
333 apexKey: apexKey,
334 }
335
336 return strings.Join([]string{label, request.Name(), cfgKey.String()}, "_")
337}
338
339func BuildMockBazelContextResultKey(label string, arch string, osType OsType, apexKey ApexConfigKey) string {
340 cfgKey := configKey{
341 arch: arch,
342 osType: osType,
343 apexKey: apexKey,
344 }
345
346 return strings.Join([]string{label, cfgKey.String()}, "_")
347}
348
Sasha Smundak39a301c2022-12-29 17:11:49 -0800349func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400350 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400351 bazelCtx.requestMutex.Lock()
352 defer bazelCtx.requestMutex.Unlock()
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500353
354 // Insert key into requests, maintaining the sort, and only if it's not duplicate.
355 keyString := key.String()
356 foundEqual := false
357 notLessThanKeyString := func(i int) bool {
358 s := bazelCtx.requests[i].String()
359 v := strings.Compare(s, keyString)
360 if v == 0 {
361 foundEqual = true
362 }
363 return v >= 0
364 }
365 targetIndex := sort.Search(len(bazelCtx.requests), notLessThanKeyString)
366 if foundEqual {
367 return
368 }
369
370 if targetIndex == len(bazelCtx.requests) {
371 bazelCtx.requests = append(bazelCtx.requests, key)
372 } else {
373 bazelCtx.requests = append(bazelCtx.requests[:targetIndex+1], bazelCtx.requests[targetIndex:]...)
374 bazelCtx.requests[targetIndex] = key
375 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400376}
377
Sasha Smundak39a301c2022-12-29 17:11:49 -0800378func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400379 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400380 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500381 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400382
Chris Parsonsf874e462022-05-10 13:50:12 -0400383 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400384 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400385 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400386}
387
Sasha Smundak39a301c2022-12-29 17:11:49 -0800388func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400389 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400390 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000391 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400392 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000393 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400394 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 +0000395}
396
Sasha Smundak39a301c2022-12-29 17:11:49 -0800397func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400398 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700399 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500400 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700401 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400402 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700403}
404
Sasha Smundak39a301c2022-12-29 17:11:49 -0800405func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700406 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
407 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500408 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700409 }
410 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
411}
412
Spandan Dasbd156812023-06-05 22:43:13 +0000413func (bazelCtx *mixedBuildBazelContext) GetPrebuiltFileInfo(label string, cfgKey configKey) (cquery.PrebuiltFileInfo, error) {
414 key := makeCqueryKey(label, cquery.GetPrebuiltFileInfo, cfgKey)
415 if rawString, ok := bazelCtx.results[key]; ok {
416 return cquery.GetPrebuiltFileInfo.ParseResult(strings.TrimSpace(rawString))
417 }
418 return cquery.PrebuiltFileInfo{}, fmt.Errorf("no bazel response for %s", key)
419}
420
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700421func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500422 panic("unimplemented")
423}
424
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700425func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500426 panic("unimplemented")
427}
428
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700429func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400430 panic("unimplemented")
431}
432
Liz Kammerbe6a7122022-11-04 16:05:11 -0400433func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700434 panic("unimplemented")
435}
436
Sasha Smundakedd16662022-10-07 14:44:50 -0700437func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
438 //TODO implement me
439 panic("implement me")
440}
441
Spandan Dasbd156812023-06-05 22:43:13 +0000442func (n noopBazelContext) GetPrebuiltFileInfo(_ string, _ configKey) (cquery.PrebuiltFileInfo, error) {
443 panic("implement me")
444}
445
Liz Kammer690fbac2023-02-10 11:11:17 -0500446func (n noopBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400447 panic("unimplemented")
448}
449
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500450func (m noopBazelContext) OutputBase() string {
451 return ""
452}
453
Yu Liue4312402023-01-18 09:15:31 -0800454func (n noopBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400455 return false
456}
457
Liz Kammera4655a92023-02-10 17:17:28 -0500458func (m noopBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
459 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500460}
461
Chris Parsons1a7aca02022-04-25 22:35:15 -0400462func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
463 return []bazel.AqueryDepset{}
464}
465
Yu Liu6a7940c2023-05-09 17:12:22 -0700466func AddToStringSet(set map[string]bool, items []string) {
Yu Liue4312402023-01-18 09:15:31 -0800467 for _, item := range items {
468 set[item] = true
469 }
470}
471
Cole Faust705968d2022-12-14 11:32:05 -0800472func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400473 disabledModules := map[string]bool{}
474 enabledModules := map[string]bool{}
475
Cole Faust705968d2022-12-14 11:32:05 -0800476 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400477 case BazelProdMode:
Yu Liu6a7940c2023-05-09 17:12:22 -0700478 AddToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800479 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000480 enabledModules[enabledAdHocModule] = true
481 }
MarkDacekb78465d2022-10-18 20:10:16 +0000482 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400483 // Staging mode includes all prod modules plus all staging modules.
Yu Liu6a7940c2023-05-09 17:12:22 -0700484 AddToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
485 AddToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800486 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000487 enabledModules[enabledAdHocModule] = true
488 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400489 default:
Chris Parsons21f80272023-06-15 04:02:28 +0000490 panic("Expected BazelProdMode or BazelStagingMode")
Cole Faust705968d2022-12-14 11:32:05 -0800491 }
492 return enabledModules, disabledModules
493}
494
495func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
496 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
497 enabledList := make([]string, 0, len(enabledModules))
498 for module := range enabledModules {
499 if !disabledModules[module] {
500 enabledList = append(enabledList, module)
501 }
502 }
503 sort.Strings(enabledList)
504 return enabledList
505}
506
507func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons21f80272023-06-15 04:02:28 +0000508 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400509 return noopBazelContext{}, nil
510 }
511
Cole Faust705968d2022-12-14 11:32:05 -0800512 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
513
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800514 paths := bazelPaths{
515 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400516 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800517 var missing []string
518 vars := []struct {
519 name string
520 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000521
522 // True if the environment variable needs to be tracked so that changes to the variable
523 // cause the ninja file to be regenerated, false otherwise. False should only be set for
524 // environment variables that have no effect on the generated ninja file.
525 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800526 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000527 {"BAZEL_HOME", &paths.homeDir, true},
528 {"BAZEL_PATH", &paths.bazelPath, true},
529 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
530 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
531 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
532 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800533 }
534 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000535 if v.track {
536 if s := c.Getenv(v.name); len(s) > 1 {
537 *v.ptr = s
538 continue
539 }
540 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800541 *v.ptr = s
542 } else {
543 missing = append(missing, v.name)
544 }
545 }
546 if len(missing) > 0 {
547 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
548 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800549
550 targetBuildVariant := "user"
551 if c.Eng() {
552 targetBuildVariant = "eng"
553 } else if c.Debuggable() {
554 targetBuildVariant = "userdebug"
555 }
556 targetProduct := "unknown"
557 if c.HasDeviceProduct() {
558 targetProduct = c.DeviceProduct()
559 }
Yu Liue4312402023-01-18 09:15:31 -0800560 dclaMixedBuildsEnabledList := []string{}
561 if c.BuildMode == BazelProdMode {
562 dclaMixedBuildsEnabledList = allowlists.ProdDclaMixedBuildsEnabledList
563 } else if c.BuildMode == BazelStagingMode {
564 dclaMixedBuildsEnabledList = append(allowlists.ProdDclaMixedBuildsEnabledList,
565 allowlists.StagingDclaMixedBuildsEnabledList...)
566 }
567 dclaEnabledModules := map[string]bool{}
Yu Liu6a7940c2023-05-09 17:12:22 -0700568 AddToStringSet(dclaEnabledModules, dclaMixedBuildsEnabledList)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800569 return &mixedBuildBazelContext{
Chris Parsons9402ca82023-02-23 17:28:06 -0500570 bazelRunner: &builtinBazelRunner{c.UseBazelProxy, absolutePath(c.outDir)},
Yu Liue4312402023-01-18 09:15:31 -0800571 paths: &paths,
Yu Liue4312402023-01-18 09:15:31 -0800572 bazelEnabledModules: enabledModules,
573 bazelDisabledModules: disabledModules,
574 bazelDclaEnabledModules: dclaEnabledModules,
575 targetProduct: targetProduct,
576 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400577 }, nil
578}
579
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400580func (p *bazelPaths) BazelMetricsDir() string {
581 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000582}
583
Yu Liue4312402023-01-18 09:15:31 -0800584func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string, withinApex bool) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400585 if context.bazelDisabledModules[moduleName] {
586 return false
587 }
588 if context.bazelEnabledModules[moduleName] {
589 return true
590 }
Spandan Das95b24b12023-06-26 22:39:19 +0000591 if withinApex && context.bazelDclaEnabledModules[moduleName] {
Yu Liue4312402023-01-18 09:15:31 -0800592 return true
593 }
594
Chris Parsons21f80272023-06-15 04:02:28 +0000595 return false
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400596}
597
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400598func pwdPrefix() string {
599 // Darwin doesn't have /proc
600 if runtime.GOOS != "darwin" {
601 return "PWD=/proc/self/cwd"
602 }
603 return ""
604}
605
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400606type bazelCommand struct {
607 command string
608 // query or label
609 expression string
610}
611
Chris Parsons9402ca82023-02-23 17:28:06 -0500612type builtinBazelRunner struct {
613 useBazelProxy bool
614 outDir string
615}
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400616
Chris Parsons808d84c2021-03-09 20:43:32 -0500617// Issues the given bazel command with given build label and additional flags.
618// Returns (stdout, stderr, error). The first and second return values are strings
619// containing the stdout and stderr of the run command, and an error is returned if
620// the invocation returned an error code.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000621func (r *builtinBazelRunner) issueBazelCommand(cmdRequest bazel.CmdRequest, paths *bazelPaths, eventHandler *metrics.EventHandler) (string, string, error) {
Chris Parsons9402ca82023-02-23 17:28:06 -0500622 if r.useBazelProxy {
623 eventHandler.Begin("client_proxy")
624 defer eventHandler.End("client_proxy")
625 proxyClient := bazel.NewProxyClient(r.outDir)
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000626 resp, err := proxyClient.IssueCommand(cmdRequest)
Chris Parsons9402ca82023-02-23 17:28:06 -0500627
628 if err != nil {
629 return "", "", err
630 }
631 if len(resp.ErrorString) > 0 {
632 return "", "", fmt.Errorf(resp.ErrorString)
633 }
634 return resp.Stdout, resp.Stderr, nil
Jason Wu52cd1942022-09-08 15:37:57 +0000635 } else {
Chris Parsons9402ca82023-02-23 17:28:06 -0500636 eventHandler.Begin("bazel command")
637 defer eventHandler.End("bazel command")
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000638
639 stdout, stderr, err := bazel.ExecBazel(paths.bazelPath, absolutePath(paths.syntheticWorkspaceDir()), cmdRequest)
640 return string(stdout), string(stderr), err
Jason Wu52cd1942022-09-08 15:37:57 +0000641 }
642}
643
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000644func (context *mixedBuildBazelContext) createBazelCommand(config Config, runName bazel.RunName, command bazelCommand,
645 extraFlags ...string) bazel.CmdRequest {
Cole Faust319abae2023-06-06 15:12:49 -0700646 if runtime.GOOS != "linux" && runtime.GOOS != "darwin" {
647 panic("Unknown GOOS: " + runtime.GOOS)
648 }
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000649 cmdFlags := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000650 "--output_base=" + absolutePath(context.paths.outputBase),
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000651 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700652 command.expression,
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000653 "--profile=" + shared.BazelMetricsFilename(context.paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400654
Cole Faust319abae2023-06-06 15:12:49 -0700655 "--host_platform=@soong_injection//product_config_platforms:mixed_builds_product-" + context.targetBuildVariant + "_" + runtime.GOOS + "_x86_64",
656 // Don't specify --platforms, because on some products/branches (like kernel-build-tools)
657 // the main platform for mixed_builds_product-variant doesn't exist because an arch isn't
658 // specified in product config. The derivative platforms that config_node transitions into
659 // will still work.
Jingwen Chen583ab212023-05-30 09:45:23 +0000660
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700661 // Suppress noise
662 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500663 "--noshow_progress",
664 "--norun_validations",
665 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400666 cmdFlags = append(cmdFlags, extraFlags...)
667
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700668 extraEnv := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000669 "HOME=" + context.paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200670 pwdPrefix(),
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000671 "BUILD_DIR=" + absolutePath(context.paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700672 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000673 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000674 "OUT_DIR=" + absolutePath(context.paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500675 // Disables local host detection of gcc; toolchain information is defined
676 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700677 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
678 }
Cole Faust8a161be2023-06-14 15:45:12 -0700679 capturedEnvVars, err := starlark_import.GetStarlarkValue[[]string]("captured_env_vars")
680 if err != nil {
681 panic(err)
682 }
683 for _, envvar := range capturedEnvVars {
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500684 val := config.Getenv(envvar)
685 if val == "" {
686 continue
687 }
688 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
689 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000690 envVars := append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400691
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000692 return bazel.CmdRequest{cmdFlags, envVars}
Jason Wu52cd1942022-09-08 15:37:57 +0000693}
694
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000695func (context *mixedBuildBazelContext) printableCqueryCommand(bazelCmd bazel.CmdRequest) string {
696 args := append([]string{context.paths.bazelPath}, bazelCmd.Argv...)
697 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(args, "\" \"") + "\""
Jason Wu52cd1942022-09-08 15:37:57 +0000698 return outputString
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400699}
700
Sasha Smundak39a301c2022-12-29 17:11:49 -0800701func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500702 // TODO(cparsons): Define configuration transitions programmatically based
703 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400704 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500705#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400706# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500707#####################################################
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400708def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800709 if attr.os == "android" and attr.arch == "target":
Cole Faust319abae2023-06-06 15:12:49 -0700710 target = "mixed_builds_product-{VARIANT}"
Cole Faustb85d1a12022-11-08 18:14:01 -0800711 else:
Cole Faust319abae2023-06-06 15:12:49 -0700712 target = "mixed_builds_product-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Yu Liue4312402023-01-18 09:15:31 -0800713 apex_name = ""
714 if attr.within_apex:
715 # //build/bazel/rules/apex:apex_name has to be set to a non_empty value,
716 # otherwise //build/bazel/rules/apex:non_apex will be true and the
717 # "-D__ANDROID_APEX__" compiler flag will be missing. Apex_name is used
718 # in some validation on bazel side which don't really apply in mixed
719 # build because soong will do the work, so we just set it to a fixed
720 # value here.
721 apex_name = "dcla_apex"
722 outputs = {
Jingwen Chen583ab212023-05-30 09:45:23 +0000723 "//command_line_option:platforms": "@soong_injection//product_config_platforms:%s" % target,
Yu Liue4312402023-01-18 09:15:31 -0800724 "@//build/bazel/rules/apex:within_apex": attr.within_apex,
725 "@//build/bazel/rules/apex:min_sdk_version": attr.apex_sdk_version,
726 "@//build/bazel/rules/apex:apex_name": apex_name,
Spandan Das40b79f82023-06-25 20:56:06 +0000727 "@//build/bazel/rules/apex:api_domain": attr.api_domain,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500728 }
729
Yu Liue4312402023-01-18 09:15:31 -0800730 return outputs
731
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400732_config_node_transition = transition(
733 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500734 inputs = [],
735 outputs = [
736 "//command_line_option:platforms",
Yu Liue4312402023-01-18 09:15:31 -0800737 "@//build/bazel/rules/apex:within_apex",
738 "@//build/bazel/rules/apex:min_sdk_version",
739 "@//build/bazel/rules/apex:apex_name",
Spandan Das40b79f82023-06-25 20:56:06 +0000740 "@//build/bazel/rules/apex:api_domain",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500741 ],
742)
743
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400744def _passthrough_rule_impl(ctx):
745 return [DefaultInfo(files = depset(ctx.files.deps))]
746
747config_node = rule(
748 implementation = _passthrough_rule_impl,
749 attrs = {
Yu Liue4312402023-01-18 09:15:31 -0800750 "arch" : attr.string(mandatory = True),
751 "os" : attr.string(mandatory = True),
752 "within_apex" : attr.bool(default = False),
753 "apex_sdk_version" : attr.string(mandatory = True),
Spandan Das40b79f82023-06-25 20:56:06 +0000754 "api_domain" : attr.string(mandatory = True),
Yu Liue4312402023-01-18 09:15:31 -0800755 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400756 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
757 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500758)
759
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400760
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500761# Rule representing the root of the build, to depend on all Bazel targets that
762# are required for the build. Building this target will build the entire Bazel
763# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400764mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400765 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500766 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400767 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500768 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400769)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500770
771def _phony_root_impl(ctx):
772 return []
773
774# Rule to depend on other targets but build nothing.
775# This is useful as follows: building a target of this rule will generate
776# symlink forests for all dependencies of the target, without executing any
777# actions of the build.
778phony_root = rule(
779 implementation = _phony_root_impl,
780 attrs = {"deps" : attr.label_list()},
781)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400782`
Cole Faustb85d1a12022-11-08 18:14:01 -0800783
784 productReplacer := strings.NewReplacer(
785 "{PRODUCT}", context.targetProduct,
786 "{VARIANT}", context.targetBuildVariant)
787
788 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400789}
790
Sasha Smundak39a301c2022-12-29 17:11:49 -0800791func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500792 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
793 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400794 formatString := `
795# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400796load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
797
798%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400799
800mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400801 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000802 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400803)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500804
805phony_root(name = "phonyroot",
806 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000807 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500808)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400809`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400810 configNodeFormatString := `
811config_node(name = "%s",
812 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400813 os = "%s",
Yu Liue4312402023-01-18 09:15:31 -0800814 within_apex = %s,
815 apex_sdk_version = "%s",
Spandan Das40b79f82023-06-25 20:56:06 +0000816 api_domain = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400817 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000818 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400819)
820`
821
822 configNodesSection := ""
823
Chris Parsons787fb362021-10-14 18:43:51 -0400824 labelsByConfig := map[string][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500825
826 for _, val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200827 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400828 configString := getConfigString(val)
829 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400830 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400831
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500832 // Configs need to be sorted to maintain determinism of the BUILD file.
833 sortedConfigs := make([]string, 0, len(labelsByConfig))
834 for val := range labelsByConfig {
835 sortedConfigs = append(sortedConfigs, val)
836 }
837 sort.Slice(sortedConfigs, func(i, j int) bool { return sortedConfigs[i] < sortedConfigs[j] })
838
Jingwen Chen1e347862021-09-02 12:11:49 +0000839 allLabels := []string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500840 for _, configString := range sortedConfigs {
841 labels := labelsByConfig[configString]
Chris Parsons787fb362021-10-14 18:43:51 -0400842 configTokens := strings.Split(configString, "|")
Yu Liue4312402023-01-18 09:15:31 -0800843 if len(configTokens) < 2 {
Chris Parsons787fb362021-10-14 18:43:51 -0400844 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000845 }
Chris Parsons787fb362021-10-14 18:43:51 -0400846 archString := configTokens[0]
847 osString := configTokens[1]
Yu Liue4312402023-01-18 09:15:31 -0800848 withinApex := "False"
849 apexSdkVerString := ""
Spandan Das40b79f82023-06-25 20:56:06 +0000850 apiDomainString := ""
851 if osString == "android" {
852 // api domains are meaningful only for device variants
853 apiDomainString = "system"
854 }
Chris Parsons787fb362021-10-14 18:43:51 -0400855 targetString := fmt.Sprintf("%s_%s", osString, archString)
Yu Liue4312402023-01-18 09:15:31 -0800856 if len(configTokens) > 2 {
857 targetString += "_" + configTokens[2]
858 if configTokens[2] == withinApexToString(true) {
859 withinApex = "True"
860 }
861 }
862 if len(configTokens) > 3 {
863 targetString += "_" + configTokens[3]
864 apexSdkVerString = configTokens[3]
865 }
Spandan Das40b79f82023-06-25 20:56:06 +0000866 if len(configTokens) > 4 {
867 apiDomainString = configTokens[4]
868 targetString += "_" + apiDomainString
869 }
Chris Parsons787fb362021-10-14 18:43:51 -0400870 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
871 labelsString := strings.Join(labels, ",\n ")
Spandan Das40b79f82023-06-25 20:56:06 +0000872 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, withinApex, apexSdkVerString, apiDomainString,
Yu Liue4312402023-01-18 09:15:31 -0800873 labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400874 }
875
Jingwen Chen1e347862021-09-02 12:11:49 +0000876 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400877}
878
Chris Parsons944e7d02021-03-11 11:08:46 -0500879func indent(original string) string {
880 result := ""
881 for _, line := range strings.Split(original, "\n") {
882 result += " " + line + "\n"
883 }
884 return result
885}
886
Chris Parsons808d84c2021-03-09 20:43:32 -0500887// Returns the file contents of the buildroot.cquery file that should be used for the cquery
888// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800889// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500890// and grouped by their request type. The data retrieved for each label depends on its
891// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800892func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400893 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons38851d82023-03-15 00:19:32 -0400894 requestTypes := []cqueryRequest{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500895 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500896 cqueryId := getCqueryId(val)
897 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
Chris Parsons38851d82023-03-15 00:19:32 -0400898 if _, seenKey := requestTypeToCqueryIdEntries[val.requestType]; !seenKey {
899 requestTypes = append(requestTypes, val.requestType)
900 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500901 requestTypeToCqueryIdEntries[val.requestType] =
902 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
903 }
904 labelRegistrationMapSection := ""
905 functionDefSection := ""
906 mainSwitchSection := ""
907
908 mapDeclarationFormatString := `
909%s = {
910 %s
911}
912`
913 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800914def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500915%s
916`
917 mainSwitchSectionFormatString := `
918 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800919 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500920`
921
Chris Parsons38851d82023-03-15 00:19:32 -0400922 for _, requestType := range requestTypes {
Chris Parsons944e7d02021-03-11 11:08:46 -0500923 labelMapName := requestType.Name() + "_Labels"
924 functionName := requestType.Name() + "_Fn"
925 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
926 labelMapName,
927 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
928 functionDefSection += fmt.Sprintf(functionDefFormatString,
929 functionName,
930 indent(requestType.StarlarkFunctionBody()))
931 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
932 labelMapName, functionName)
933 }
934
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400935 formatString := `
936# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400937
Cole Faustb85d1a12022-11-08 18:14:01 -0800938{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500939
Cole Faustb85d1a12022-11-08 18:14:01 -0800940{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500941
942def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400943 # TODO(b/199363072): filegroups and file targets aren't associated with any
944 # specific platform architecture in mixed builds. This is consistent with how
945 # Soong treats filegroups, but it may not be the case with manually-written
946 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500947 buildoptions = build_options(target)
Yu Liue4312402023-01-18 09:15:31 -0800948
Jingwen Chen8f222742021-10-07 12:02:23 +0000949 if buildoptions == None:
950 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400951 # any specific platform architecture in mixed builds, so use the host.
952 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -0800953 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500954 if len(platforms) != 1:
955 # An individual configured target should have only one platform architecture.
956 # Note that it's fine for there to be multiple architectures for the same label,
957 # but each is its own configured target.
958 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -0800959 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -0500960 if platform_name == "host":
961 return "HOST"
Cole Faust319abae2023-06-06 15:12:49 -0700962 if not platform_name.startswith("mixed_builds_product-{TARGET_BUILD_VARIANT}"):
963 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))
964 platform_name = platform_name.removeprefix("mixed_builds_product-{TARGET_BUILD_VARIANT}").removeprefix("_")
Yu Liue4312402023-01-18 09:15:31 -0800965 config_key = ""
Cole Faustb85d1a12022-11-08 18:14:01 -0800966 if not platform_name:
Yu Liue4312402023-01-18 09:15:31 -0800967 config_key = "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400968 elif platform_name.startswith("android_"):
Yu Liue4312402023-01-18 09:15:31 -0800969 config_key = platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400970 elif platform_name.startswith("linux_"):
Yu Liue4312402023-01-18 09:15:31 -0800971 config_key = platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400972 else:
Cole Faust319abae2023-06-06 15:12:49 -0700973 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 -0500974
Yu Liue4312402023-01-18 09:15:31 -0800975 within_apex = buildoptions.get("//build/bazel/rules/apex:within_apex")
976 apex_sdk_version = buildoptions.get("//build/bazel/rules/apex:min_sdk_version")
Spandan Das40b79f82023-06-25 20:56:06 +0000977 api_domain = buildoptions.get("//build/bazel/rules/apex:api_domain")
Yu Liue4312402023-01-18 09:15:31 -0800978
979 if within_apex:
980 config_key += "|within_apex"
981 if apex_sdk_version != None and len(apex_sdk_version) > 0:
982 config_key += "|" + apex_sdk_version
Spandan Das40b79f82023-06-25 20:56:06 +0000983 if api_domain != None and len(api_domain) > 0:
984 config_key += "|" + api_domain
Yu Liue4312402023-01-18 09:15:31 -0800985
986 return config_key
987
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400988def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500989 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500990
Chris Parsons86dc2c22022-09-28 14:58:41 -0400991 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
992 if id_string.startswith("//"):
993 id_string = "@" + id_string
994
Cole Faustb85d1a12022-11-08 18:14:01 -0800995 {MAIN_SWITCH_SECTION}
996
Chris Parsons944e7d02021-03-11 11:08:46 -0500997 # This target was not requested via cquery, and thus must be a dependency
998 # of a requested target.
999 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001000`
Cole Faustb85d1a12022-11-08 18:14:01 -08001001 replacer := strings.NewReplacer(
1002 "{TARGET_PRODUCT}", context.targetProduct,
1003 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
1004 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
1005 "{FUNCTION_DEF_SECTION}", functionDefSection,
1006 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001007
Cole Faustb85d1a12022-11-08 18:14:01 -08001008 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001009}
1010
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001011// Returns a path containing build-related metadata required for interfacing
1012// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001013func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001014 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -05001015}
1016
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001017// Returns the path where the contents of the @soong_injection repository live.
1018// It is used by Soong to tell Bazel things it cannot over the command line.
1019func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001020 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001021}
1022
1023// Returns the path of the synthetic Bazel workspace that contains a symlink
1024// forest composed the whole source tree and BUILD files generated by bp2build.
1025func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001026 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001027}
1028
Jingwen Chen8c523582021-06-01 11:19:53 +00001029// Returns the path to the top level out dir ($OUT_DIR).
1030func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001031 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +00001032}
1033
Sasha Smundak4975c822022-11-16 15:28:18 -08001034const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
1035
1036var (
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001037 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
1038 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
1039 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
1040 allBazelCommands = []bazelCommand{aqueryCmd, cqueryCmd, buildCmd}
Sasha Smundak4975c822022-11-16 15:28:18 -08001041)
1042
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001043// Issues commands to Bazel to receive results for all cquery requests
1044// queued in the BazelContext.
Liz Kammer690fbac2023-02-10 11:11:17 -05001045func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx invokeBazelContext) error {
1046 eventHandler := ctx.GetEventHandler()
1047 eventHandler.Begin("bazel")
1048 defer eventHandler.End("bazel")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001049
Sasha Smundak4975c822022-11-16 15:28:18 -08001050 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
1051 if err := os.MkdirAll(metricsDir, 0777); err != nil {
1052 return err
1053 }
1054 }
1055 context.results = make(map[cqueryKey]string)
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001056 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001057 return err
1058 }
1059 if err := context.runAquery(config, ctx); err != nil {
1060 return err
1061 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001062 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001063 return err
1064 }
1065
1066 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001067 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -08001068 return nil
1069}
1070
Liz Kammer690fbac2023-02-10 11:11:17 -05001071func (context *mixedBuildBazelContext) runCquery(config Config, ctx invokeBazelContext) error {
1072 eventHandler := ctx.GetEventHandler()
1073 eventHandler.Begin("cquery")
1074 defer eventHandler.End("cquery")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001075 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +02001076 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
1077 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
1078 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -05001079 if err != nil {
1080 return err
1081 }
1082 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001083 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001084 return err
1085 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001086 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001087 return err
1088 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001089 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001090 return err
1091 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001092 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001093 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001094 return err
1095 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001096
Yu Liue4312402023-01-18 09:15:31 -08001097 extraFlags := []string{"--output=starlark", "--starlark:file=" + absolutePath(cqueryFileRelpath)}
1098 if Bool(config.productVariables.ClangCoverage) {
1099 extraFlags = append(extraFlags, "--collect_code_coverage")
1100 }
1101
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001102 cqueryCmdRequest := context.createBazelCommand(config, bazel.CqueryBuildRootRunName, cqueryCmd, extraFlags...)
1103 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCmdRequest, context.paths, eventHandler)
Wei Licbd181c2022-11-16 08:59:23 -08001104 if cqueryErr != nil {
1105 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001106 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001107 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", context.printableCqueryCommand(cqueryCmdRequest))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001108 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001109 return err
1110 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001111 cqueryResults := map[string]string{}
1112 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1113 if strings.Contains(outputLine, ">>") {
1114 splitLine := strings.SplitN(outputLine, ">>", 2)
1115 cqueryResults[splitLine[0]] = splitLine[1]
1116 }
1117 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001118 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001119 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001120 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001121 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001122 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001123 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001124 }
1125 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001126 return nil
1127}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001128
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001129func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1130 oldContents, err := os.ReadFile(path)
1131 if err != nil || !bytes.Equal(contents, oldContents) {
1132 err = os.WriteFile(path, contents, perm)
1133 }
1134 return nil
1135}
1136
Liz Kammer690fbac2023-02-10 11:11:17 -05001137func (context *mixedBuildBazelContext) runAquery(config Config, ctx invokeBazelContext) error {
1138 eventHandler := ctx.GetEventHandler()
1139 eventHandler.Begin("aquery")
1140 defer eventHandler.End("aquery")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001141 // Issue an aquery command to retrieve action information about the bazel build tree.
1142 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001143 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1144 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001145 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001146 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001147 extraFlags = append(extraFlags, "--collect_code_coverage")
1148 paths := make([]string, 0, 2)
1149 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001150 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001151 // TODO(b/259404593) convert path wildcard to regex values
1152 if p[i] == "*" {
1153 p[i] = ".*"
1154 }
1155 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001156 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1157 }
1158 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1159 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1160 }
1161 if len(paths) > 0 {
1162 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001163 }
1164 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001165 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.AqueryBuildRootRunName, aqueryCmd,
1166 extraFlags...), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001167 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001168 return err
1169 }
Liz Kammer690fbac2023-02-10 11:11:17 -05001170 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001171 return err
1172}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001173
Liz Kammer690fbac2023-02-10 11:11:17 -05001174func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx invokeBazelContext) error {
1175 eventHandler := ctx.GetEventHandler()
1176 eventHandler.Begin("symlinks")
1177 defer eventHandler.End("symlinks")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001178 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1179 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1180 // but some of symlinks may be required to resolve source dependencies of the build.
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001181 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.BazelBuildPhonyRootRunName, buildCmd), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001182 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001183}
Chris Parsonsa798d962020-10-12 23:44:08 -04001184
Liz Kammera4655a92023-02-10 17:17:28 -05001185func (context *mixedBuildBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001186 return context.buildStatements
1187}
1188
Sasha Smundak39a301c2022-12-29 17:11:49 -08001189func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001190 return context.depsets
1191}
1192
Sasha Smundak39a301c2022-12-29 17:11:49 -08001193func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001194 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001195}
1196
Chris Parsonsa798d962020-10-12 23:44:08 -04001197// Singleton used for registering BUILD file ninja dependencies (needed
1198// for correctness of builds which use Bazel.
1199func BazelSingleton() Singleton {
1200 return &bazelSingleton{}
1201}
1202
1203type bazelSingleton struct{}
1204
1205func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001206 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001207 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001208 return
1209 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001210
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001211 // Add ninja file dependencies for files which all bazel invocations require.
1212 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001213 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001214 ctx.AddNinjaFileDeps(bazelBuildList)
1215
Sasha Smundak0e87b182022-12-01 11:46:11 -08001216 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001217 if err != nil {
1218 ctx.Errorf(err.Error())
1219 }
1220 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1221 for _, file := range files {
1222 ctx.AddNinjaFileDeps(file)
1223 }
1224
Chris Parsons1a7aca02022-04-25 22:35:15 -04001225 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1226 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001227 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001228 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1229 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001230 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1231 }
1232 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001233 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1234 if artifactPath == "bazel-out/volatile-status.txt" {
1235 // See https://bazel.build/docs/user-manual#workspace-status
1236 orderOnlies = append(orderOnlies, pathInBazelOut)
1237 } else {
1238 outputs = append(outputs, pathInBazelOut)
1239 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001240 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001241 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001242 ctx.Build(pctx, BuildParams{
1243 Rule: blueprint.Phony,
1244 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1245 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001246 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001247 })
1248 }
1249
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001250 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1251 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001252 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Liz Kammera4655a92023-02-10 17:17:28 -05001253 // nil build statements are a valid case where we do not create an action because it is
1254 // unnecessary or handled by other processing
1255 if buildStatement == nil {
1256 continue
1257 }
Sasha Smundak1da064c2022-06-08 16:36:16 -07001258 if len(buildStatement.Command) > 0 {
1259 rule := NewRuleBuilder(pctx, ctx)
1260 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1261 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1262 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1263 continue
1264 }
1265 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1266 // and thus require special treatment. If BuildStatement were an interface implementing
1267 // buildRule(ctx) function, the code here would just call it.
1268 // Unfortunately, the BuildStatement is defined in
1269 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1270 // because this would cause circular dependency. So, until we move aquery processing
1271 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001272 switch buildStatement.Mnemonic {
1273 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001274 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1275 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001276 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001277 // build-runfiles arguments are the manifest file and the target directory
1278 // where it creates the symlink tree according to this manifest (and then
1279 // writes the MANIFEST file to it).
1280 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1281 outManifestPath := outManifest.String()
1282 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1283 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1284 }
1285 outDir := filepath.Dir(outManifestPath)
1286 ctx.Build(pctx, BuildParams{
1287 Rule: buildRunfilesRule,
1288 Output: outManifest,
1289 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1290 Description: "symlink tree for " + outDir,
1291 Args: map[string]string{
1292 "outDir": outDir,
1293 },
1294 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001295 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001296 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001297 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001298 }
1299}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001300
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001301// Register bazel-owned build statements (obtained from the aquery invocation).
Liz Kammera4655a92023-02-10 17:17:28 -05001302func createCommand(cmd *RuleBuilderCommand, buildStatement *bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001303 // executionRoot is the action cwd.
1304 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1305
1306 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1307 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001308 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001309 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001310 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001311 }
1312 cmd.Text("&&")
1313 }
1314
1315 for _, pair := range buildStatement.Env {
1316 // Set per-action env variables, if any.
1317 cmd.Flag(pair.Key + "=" + pair.Value)
1318 }
1319
1320 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001321 if len(buildStatement.Command) > 16*1024 {
1322 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1323 WriteFileRule(ctx, commandFile, buildStatement.Command)
1324
1325 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1326 } else {
1327 cmd.Text(buildStatement.Command)
1328 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001329
1330 for _, outputPath := range buildStatement.OutputPaths {
1331 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1332 }
1333 for _, inputPath := range buildStatement.InputPaths {
1334 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1335 }
1336 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1337 otherDepsetName := bazelDepsetName(inputDepsetHash)
1338 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1339 }
1340
1341 if depfile := buildStatement.Depfile; depfile != nil {
1342 // The paths in depfile are relative to `executionRoot`.
1343 // Hence, they need to be corrected by replacing "bazel-out"
1344 // with the full `bazelOutDir`.
1345 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1346 // would be deemed missing.
1347 // (Note: The regexp uses a capture group because the version of sed
1348 // does not support a look-behind pattern.)
1349 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1350 bazelOutDir, *depfile)
1351 cmd.Text(replacement)
1352 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1353 }
1354
1355 for _, symlinkPath := range buildStatement.SymlinkPaths {
1356 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1357 }
1358}
1359
Chris Parsons8d6e4332021-02-22 16:13:50 -05001360func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001361 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001362}
1363
Chris Parsons787fb362021-10-14 18:43:51 -04001364func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001365 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001366 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001367 if key.configKey.osType.Class == Device {
1368 // For the generic Android, the expected result is "target|android", which
1369 // corresponds to the product_variable_config named "android_target" in
1370 // build/bazel/platforms/BUILD.bazel.
1371 arch = "target"
1372 } else {
1373 // Use host platform, which is currently hardcoded to be x86_64.
1374 arch = "x86_64"
1375 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001376 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001377 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001378 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001379 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001380 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001381 }
Yu Liue4312402023-01-18 09:15:31 -08001382 keyString := arch + "|" + osName
1383 if key.configKey.apexKey.WithinApex {
1384 keyString += "|" + withinApexToString(key.configKey.apexKey.WithinApex)
1385 }
1386
1387 if len(key.configKey.apexKey.ApexSdkVersion) > 0 {
1388 keyString += "|" + key.configKey.apexKey.ApexSdkVersion
1389 }
1390
Spandan Das40b79f82023-06-25 20:56:06 +00001391 if len(key.configKey.apexKey.ApiDomain) > 0 {
1392 keyString += "|" + key.configKey.apexKey.ApiDomain
1393 }
1394
Yu Liue4312402023-01-18 09:15:31 -08001395 return keyString
Chris Parsons787fb362021-10-14 18:43:51 -04001396}
1397
Chris Parsonsf874e462022-05-10 13:50:12 -04001398func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001399 return configKey{
1400 // use string because Arch is not a valid key in go
1401 arch: ctx.Arch().String(),
1402 osType: ctx.Os(),
1403 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001404}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001405
Yu Liue4312402023-01-18 09:15:31 -08001406func GetConfigKeyApexVariant(ctx BaseModuleContext, apexKey *ApexConfigKey) configKey {
1407 configKey := GetConfigKey(ctx)
1408
1409 if apexKey != nil {
1410 configKey.apexKey = ApexConfigKey{
1411 WithinApex: apexKey.WithinApex,
1412 ApexSdkVersion: apexKey.ApexSdkVersion,
Spandan Das40b79f82023-06-25 20:56:06 +00001413 ApiDomain: apexKey.ApiDomain,
Yu Liue4312402023-01-18 09:15:31 -08001414 }
1415 }
1416
1417 return configKey
1418}
1419
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001420func bazelDepsetName(contentHash string) string {
1421 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001422}