blob: 4b1a8f491a15bea0bb403e47cf85bf9349f04d6a [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
Yu Liubfb23622023-02-22 10:42:15 -0800179 IsModuleDclaAllowed(moduleName string) bool
180
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500181 // 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
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400189}
190
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400191type bazelRunner interface {
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000192 issueBazelCommand(cmdRequest bazel.CmdRequest, paths *bazelPaths, eventHandler *metrics.EventHandler) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400193}
194
195type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000196 homeDir string
197 bazelPath string
198 outputBase string
199 workspaceDir string
200 soongOutDir string
201 metricsDir string
202 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400203}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400204
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400205// A context object which tracks queued requests that need to be made to Bazel,
206// and their results after the requests have been made.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800207type mixedBuildBazelContext struct {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400208 bazelRunner
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500209 paths *bazelPaths
210 // cquery requests that have not yet been issued to Bazel. This list is maintained
211 // in a sorted state, and is guaranteed to have no duplicates.
212 requests []cqueryKey
213 requestMutex sync.Mutex // requests can be written in parallel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400214
215 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500216
217 // Build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500218 buildStatements []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400219
220 // Depsets which should be used for Bazel's build statements.
221 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400222
223 // Per-module allowlist/denylist functionality to control whether analysis of
224 // modules are handled by Bazel. For modules which do not have a Bazel definition
225 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
226 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
227 // Per-module denylist to opt modules out of bazel handling.
228 bazelDisabledModules map[string]bool
229 // Per-module allowlist to opt modules in to bazel handling.
230 bazelEnabledModules map[string]bool
Yu Liue4312402023-01-18 09:15:31 -0800231 // DCLA modules are enabled when used in apex.
232 bazelDclaEnabledModules map[string]bool
Cole Faustb85d1a12022-11-08 18:14:01 -0800233
234 targetProduct string
235 targetBuildVariant string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400236}
237
Sasha Smundak39a301c2022-12-29 17:11:49 -0800238var _ BazelContext = &mixedBuildBazelContext{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400239
240// A bazel context to use when Bazel is disabled.
241type noopBazelContext struct{}
242
243var _ BazelContext = noopBazelContext{}
244
245// A bazel context to use for tests.
246type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400247 OutputBaseDir string
248
Spandan Dasbd156812023-06-05 22:43:13 +0000249 LabelToOutputFiles map[string][]string
250 LabelToCcInfo map[string]cquery.CcInfo
251 LabelToPythonBinary map[string]string
252 LabelToApexInfo map[string]cquery.ApexInfo
253 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
254 LabelToPrebuiltFileInfo map[string]cquery.PrebuiltFileInfo
Yu Liue4312402023-01-18 09:15:31 -0800255
256 BazelRequests map[string]bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400257}
258
Yu Liue4312402023-01-18 09:15:31 -0800259func (m MockBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
260 key := BuildMockBazelContextRequestKey(label, requestType, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
261 if m.BazelRequests == nil {
262 m.BazelRequests = make(map[string]bool)
263 }
264 m.BazelRequests[key] = true
Chris Parsons8d6e4332021-02-22 16:13:50 -0500265}
266
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700267func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500268 result, ok := m.LabelToOutputFiles[label]
269 if !ok {
270 return []string{}, fmt.Errorf("no target with label %q in LabelToOutputFiles", label)
271 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400272 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400273}
274
Yu Liue4312402023-01-18 09:15:31 -0800275func (m MockBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500276 result, ok := m.LabelToCcInfo[label]
277 if !ok {
Yu Liue4312402023-01-18 09:15:31 -0800278 key := BuildMockBazelContextResultKey(label, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
279 result, ok = m.LabelToCcInfo[key]
280 if !ok {
281 return cquery.CcInfo{}, fmt.Errorf("no target with label %q in LabelToCcInfo", label)
282 }
Sam Delmericoce39f832023-01-23 14:04:24 -0500283 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400284 return result, nil
285}
286
Liz Kammerbe6a7122022-11-04 16:05:11 -0400287func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500288 result, ok := m.LabelToApexInfo[label]
289 if !ok {
290 return cquery.ApexInfo{}, fmt.Errorf("no target with label %q in LabelToApexInfo", label)
291 }
Liz Kammer0e255ef2022-11-04 16:07:04 -0400292 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700293}
294
Sasha Smundakedd16662022-10-07 14:44:50 -0700295func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500296 result, ok := m.LabelToCcBinary[label]
297 if !ok {
298 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no target with label %q in LabelToCcBinary", label)
299 }
Sasha Smundakedd16662022-10-07 14:44:50 -0700300 return result, nil
301}
302
Spandan Dasbd156812023-06-05 22:43:13 +0000303func (m MockBazelContext) GetPrebuiltFileInfo(label string, _ configKey) (cquery.PrebuiltFileInfo, error) {
304 result, ok := m.LabelToPrebuiltFileInfo[label]
305 if !ok {
306 return cquery.PrebuiltFileInfo{}, fmt.Errorf("no target with label %q in LabelToPrebuiltFileInfo", label)
307 }
308 return result, nil
309}
310
Liz Kammer690fbac2023-02-10 11:11:17 -0500311func (m MockBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400312 panic("unimplemented")
313}
314
Yu Liue4312402023-01-18 09:15:31 -0800315func (m MockBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400316 return true
317}
318
Yu Liubfb23622023-02-22 10:42:15 -0800319func (m MockBazelContext) IsModuleDclaAllowed(_ string) bool {
320 return true
321}
322
Liz Kammera92e8442021-04-07 20:25:21 -0400323func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500324
Liz Kammera4655a92023-02-10 17:17:28 -0500325func (m MockBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
326 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500327}
328
Chris Parsons1a7aca02022-04-25 22:35:15 -0400329func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
330 return []bazel.AqueryDepset{}
331}
332
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400333var _ BazelContext = MockBazelContext{}
334
Yu Liue4312402023-01-18 09:15:31 -0800335func BuildMockBazelContextRequestKey(label string, request cqueryRequest, arch string, osType OsType, apexKey ApexConfigKey) string {
336 cfgKey := configKey{
337 arch: arch,
338 osType: osType,
339 apexKey: apexKey,
340 }
341
342 return strings.Join([]string{label, request.Name(), cfgKey.String()}, "_")
343}
344
345func BuildMockBazelContextResultKey(label string, arch string, osType OsType, apexKey ApexConfigKey) string {
346 cfgKey := configKey{
347 arch: arch,
348 osType: osType,
349 apexKey: apexKey,
350 }
351
352 return strings.Join([]string{label, cfgKey.String()}, "_")
353}
354
Sasha Smundak39a301c2022-12-29 17:11:49 -0800355func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400356 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400357 bazelCtx.requestMutex.Lock()
358 defer bazelCtx.requestMutex.Unlock()
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500359
360 // Insert key into requests, maintaining the sort, and only if it's not duplicate.
361 keyString := key.String()
362 foundEqual := false
363 notLessThanKeyString := func(i int) bool {
364 s := bazelCtx.requests[i].String()
365 v := strings.Compare(s, keyString)
366 if v == 0 {
367 foundEqual = true
368 }
369 return v >= 0
370 }
371 targetIndex := sort.Search(len(bazelCtx.requests), notLessThanKeyString)
372 if foundEqual {
373 return
374 }
375
376 if targetIndex == len(bazelCtx.requests) {
377 bazelCtx.requests = append(bazelCtx.requests, key)
378 } else {
379 bazelCtx.requests = append(bazelCtx.requests[:targetIndex+1], bazelCtx.requests[targetIndex:]...)
380 bazelCtx.requests[targetIndex] = key
381 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400382}
383
Sasha Smundak39a301c2022-12-29 17:11:49 -0800384func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400385 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400386 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500387 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400388
Chris Parsonsf874e462022-05-10 13:50:12 -0400389 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400390 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400391 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400392}
393
Sasha Smundak39a301c2022-12-29 17:11:49 -0800394func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400395 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400396 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000397 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400398 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000399 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400400 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 +0000401}
402
Sasha Smundak39a301c2022-12-29 17:11:49 -0800403func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400404 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700405 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500406 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700407 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400408 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700409}
410
Sasha Smundak39a301c2022-12-29 17:11:49 -0800411func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700412 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
413 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500414 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700415 }
416 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
417}
418
Spandan Dasbd156812023-06-05 22:43:13 +0000419func (bazelCtx *mixedBuildBazelContext) GetPrebuiltFileInfo(label string, cfgKey configKey) (cquery.PrebuiltFileInfo, error) {
420 key := makeCqueryKey(label, cquery.GetPrebuiltFileInfo, cfgKey)
421 if rawString, ok := bazelCtx.results[key]; ok {
422 return cquery.GetPrebuiltFileInfo.ParseResult(strings.TrimSpace(rawString))
423 }
424 return cquery.PrebuiltFileInfo{}, fmt.Errorf("no bazel response for %s", key)
425}
426
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700427func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500428 panic("unimplemented")
429}
430
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700431func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500432 panic("unimplemented")
433}
434
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700435func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400436 panic("unimplemented")
437}
438
Liz Kammerbe6a7122022-11-04 16:05:11 -0400439func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700440 panic("unimplemented")
441}
442
Sasha Smundakedd16662022-10-07 14:44:50 -0700443func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
444 //TODO implement me
445 panic("implement me")
446}
447
Spandan Dasbd156812023-06-05 22:43:13 +0000448func (n noopBazelContext) GetPrebuiltFileInfo(_ string, _ configKey) (cquery.PrebuiltFileInfo, error) {
449 panic("implement me")
450}
451
Liz Kammer690fbac2023-02-10 11:11:17 -0500452func (n noopBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400453 panic("unimplemented")
454}
455
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500456func (m noopBazelContext) OutputBase() string {
457 return ""
458}
459
Yu Liue4312402023-01-18 09:15:31 -0800460func (n noopBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400461 return false
462}
463
Yu Liubfb23622023-02-22 10:42:15 -0800464func (n noopBazelContext) IsModuleDclaAllowed(_ string) bool {
465 return false
466}
467
Liz Kammera4655a92023-02-10 17:17:28 -0500468func (m noopBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
469 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500470}
471
Chris Parsons1a7aca02022-04-25 22:35:15 -0400472func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
473 return []bazel.AqueryDepset{}
474}
475
Yu Liu6a7940c2023-05-09 17:12:22 -0700476func AddToStringSet(set map[string]bool, items []string) {
Yu Liue4312402023-01-18 09:15:31 -0800477 for _, item := range items {
478 set[item] = true
479 }
480}
481
Cole Faust705968d2022-12-14 11:32:05 -0800482func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400483 disabledModules := map[string]bool{}
484 enabledModules := map[string]bool{}
485
Cole Faust705968d2022-12-14 11:32:05 -0800486 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400487 case BazelProdMode:
Yu Liu6a7940c2023-05-09 17:12:22 -0700488 AddToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800489 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000490 enabledModules[enabledAdHocModule] = true
491 }
MarkDacekb78465d2022-10-18 20:10:16 +0000492 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400493 // Staging mode includes all prod modules plus all staging modules.
Yu Liu6a7940c2023-05-09 17:12:22 -0700494 AddToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
495 AddToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800496 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000497 enabledModules[enabledAdHocModule] = true
498 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400499 default:
Chris Parsons21f80272023-06-15 04:02:28 +0000500 panic("Expected BazelProdMode or BazelStagingMode")
Cole Faust705968d2022-12-14 11:32:05 -0800501 }
502 return enabledModules, disabledModules
503}
504
505func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
506 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
507 enabledList := make([]string, 0, len(enabledModules))
508 for module := range enabledModules {
509 if !disabledModules[module] {
510 enabledList = append(enabledList, module)
511 }
512 }
513 sort.Strings(enabledList)
514 return enabledList
515}
516
517func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons21f80272023-06-15 04:02:28 +0000518 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400519 return noopBazelContext{}, nil
520 }
521
Cole Faust705968d2022-12-14 11:32:05 -0800522 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
523
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800524 paths := bazelPaths{
525 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400526 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800527 var missing []string
528 vars := []struct {
529 name string
530 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000531
532 // True if the environment variable needs to be tracked so that changes to the variable
533 // cause the ninja file to be regenerated, false otherwise. False should only be set for
534 // environment variables that have no effect on the generated ninja file.
535 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800536 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000537 {"BAZEL_HOME", &paths.homeDir, true},
538 {"BAZEL_PATH", &paths.bazelPath, true},
539 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
540 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
541 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
542 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800543 }
544 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000545 if v.track {
546 if s := c.Getenv(v.name); len(s) > 1 {
547 *v.ptr = s
548 continue
549 }
550 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800551 *v.ptr = s
552 } else {
553 missing = append(missing, v.name)
554 }
555 }
556 if len(missing) > 0 {
557 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
558 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800559
560 targetBuildVariant := "user"
561 if c.Eng() {
562 targetBuildVariant = "eng"
563 } else if c.Debuggable() {
564 targetBuildVariant = "userdebug"
565 }
566 targetProduct := "unknown"
567 if c.HasDeviceProduct() {
568 targetProduct = c.DeviceProduct()
569 }
Yu Liue4312402023-01-18 09:15:31 -0800570 dclaMixedBuildsEnabledList := []string{}
571 if c.BuildMode == BazelProdMode {
572 dclaMixedBuildsEnabledList = allowlists.ProdDclaMixedBuildsEnabledList
573 } else if c.BuildMode == BazelStagingMode {
574 dclaMixedBuildsEnabledList = append(allowlists.ProdDclaMixedBuildsEnabledList,
575 allowlists.StagingDclaMixedBuildsEnabledList...)
576 }
577 dclaEnabledModules := map[string]bool{}
Yu Liu6a7940c2023-05-09 17:12:22 -0700578 AddToStringSet(dclaEnabledModules, dclaMixedBuildsEnabledList)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800579 return &mixedBuildBazelContext{
Chris Parsons9402ca82023-02-23 17:28:06 -0500580 bazelRunner: &builtinBazelRunner{c.UseBazelProxy, absolutePath(c.outDir)},
Yu Liue4312402023-01-18 09:15:31 -0800581 paths: &paths,
Yu Liue4312402023-01-18 09:15:31 -0800582 bazelEnabledModules: enabledModules,
583 bazelDisabledModules: disabledModules,
584 bazelDclaEnabledModules: dclaEnabledModules,
585 targetProduct: targetProduct,
586 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400587 }, nil
588}
589
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400590func (p *bazelPaths) BazelMetricsDir() string {
591 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000592}
593
Yu Liue4312402023-01-18 09:15:31 -0800594func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string, withinApex bool) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400595 if context.bazelDisabledModules[moduleName] {
596 return false
597 }
598 if context.bazelEnabledModules[moduleName] {
599 return true
600 }
Yu Liubfb23622023-02-22 10:42:15 -0800601 if withinApex && context.IsModuleDclaAllowed(moduleName) {
Yu Liue4312402023-01-18 09:15:31 -0800602 return true
603 }
604
Chris Parsons21f80272023-06-15 04:02:28 +0000605 return false
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400606}
607
Yu Liubfb23622023-02-22 10:42:15 -0800608func (context *mixedBuildBazelContext) IsModuleDclaAllowed(moduleName string) bool {
609 return context.bazelDclaEnabledModules[moduleName]
610}
611
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400612func pwdPrefix() string {
613 // Darwin doesn't have /proc
614 if runtime.GOOS != "darwin" {
615 return "PWD=/proc/self/cwd"
616 }
617 return ""
618}
619
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400620type bazelCommand struct {
621 command string
622 // query or label
623 expression string
624}
625
Chris Parsons9402ca82023-02-23 17:28:06 -0500626type builtinBazelRunner struct {
627 useBazelProxy bool
628 outDir string
629}
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400630
Chris Parsons808d84c2021-03-09 20:43:32 -0500631// Issues the given bazel command with given build label and additional flags.
632// Returns (stdout, stderr, error). The first and second return values are strings
633// containing the stdout and stderr of the run command, and an error is returned if
634// the invocation returned an error code.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000635func (r *builtinBazelRunner) issueBazelCommand(cmdRequest bazel.CmdRequest, paths *bazelPaths, eventHandler *metrics.EventHandler) (string, string, error) {
Chris Parsons9402ca82023-02-23 17:28:06 -0500636 if r.useBazelProxy {
637 eventHandler.Begin("client_proxy")
638 defer eventHandler.End("client_proxy")
639 proxyClient := bazel.NewProxyClient(r.outDir)
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000640 resp, err := proxyClient.IssueCommand(cmdRequest)
Chris Parsons9402ca82023-02-23 17:28:06 -0500641
642 if err != nil {
643 return "", "", err
644 }
645 if len(resp.ErrorString) > 0 {
646 return "", "", fmt.Errorf(resp.ErrorString)
647 }
648 return resp.Stdout, resp.Stderr, nil
Jason Wu52cd1942022-09-08 15:37:57 +0000649 } else {
Chris Parsons9402ca82023-02-23 17:28:06 -0500650 eventHandler.Begin("bazel command")
651 defer eventHandler.End("bazel command")
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000652
653 stdout, stderr, err := bazel.ExecBazel(paths.bazelPath, absolutePath(paths.syntheticWorkspaceDir()), cmdRequest)
654 return string(stdout), string(stderr), err
Jason Wu52cd1942022-09-08 15:37:57 +0000655 }
656}
657
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000658func (context *mixedBuildBazelContext) createBazelCommand(config Config, runName bazel.RunName, command bazelCommand,
659 extraFlags ...string) bazel.CmdRequest {
Cole Faust319abae2023-06-06 15:12:49 -0700660 if runtime.GOOS != "linux" && runtime.GOOS != "darwin" {
661 panic("Unknown GOOS: " + runtime.GOOS)
662 }
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000663 cmdFlags := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000664 "--output_base=" + absolutePath(context.paths.outputBase),
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000665 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700666 command.expression,
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000667 "--profile=" + shared.BazelMetricsFilename(context.paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400668
Cole Faust319abae2023-06-06 15:12:49 -0700669 "--host_platform=@soong_injection//product_config_platforms:mixed_builds_product-" + context.targetBuildVariant + "_" + runtime.GOOS + "_x86_64",
670 // Don't specify --platforms, because on some products/branches (like kernel-build-tools)
671 // the main platform for mixed_builds_product-variant doesn't exist because an arch isn't
672 // specified in product config. The derivative platforms that config_node transitions into
673 // will still work.
Jingwen Chen583ab212023-05-30 09:45:23 +0000674
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700675 // Suppress noise
676 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500677 "--noshow_progress",
678 "--norun_validations",
679 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400680 cmdFlags = append(cmdFlags, extraFlags...)
681
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700682 extraEnv := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000683 "HOME=" + context.paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200684 pwdPrefix(),
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000685 "BUILD_DIR=" + absolutePath(context.paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700686 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000687 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000688 "OUT_DIR=" + absolutePath(context.paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500689 // Disables local host detection of gcc; toolchain information is defined
690 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700691 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
692 }
Cole Faust8a161be2023-06-14 15:45:12 -0700693 capturedEnvVars, err := starlark_import.GetStarlarkValue[[]string]("captured_env_vars")
694 if err != nil {
695 panic(err)
696 }
697 for _, envvar := range capturedEnvVars {
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500698 val := config.Getenv(envvar)
699 if val == "" {
700 continue
701 }
702 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
703 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000704 envVars := append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400705
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000706 return bazel.CmdRequest{cmdFlags, envVars}
Jason Wu52cd1942022-09-08 15:37:57 +0000707}
708
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000709func (context *mixedBuildBazelContext) printableCqueryCommand(bazelCmd bazel.CmdRequest) string {
710 args := append([]string{context.paths.bazelPath}, bazelCmd.Argv...)
711 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(args, "\" \"") + "\""
Jason Wu52cd1942022-09-08 15:37:57 +0000712 return outputString
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400713}
714
Sasha Smundak39a301c2022-12-29 17:11:49 -0800715func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500716 // TODO(cparsons): Define configuration transitions programmatically based
717 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400718 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500719#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400720# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500721#####################################################
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400722def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800723 if attr.os == "android" and attr.arch == "target":
Cole Faust319abae2023-06-06 15:12:49 -0700724 target = "mixed_builds_product-{VARIANT}"
Cole Faustb85d1a12022-11-08 18:14:01 -0800725 else:
Cole Faust319abae2023-06-06 15:12:49 -0700726 target = "mixed_builds_product-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Yu Liue4312402023-01-18 09:15:31 -0800727 apex_name = ""
728 if attr.within_apex:
729 # //build/bazel/rules/apex:apex_name has to be set to a non_empty value,
730 # otherwise //build/bazel/rules/apex:non_apex will be true and the
731 # "-D__ANDROID_APEX__" compiler flag will be missing. Apex_name is used
732 # in some validation on bazel side which don't really apply in mixed
733 # build because soong will do the work, so we just set it to a fixed
734 # value here.
735 apex_name = "dcla_apex"
736 outputs = {
Jingwen Chen583ab212023-05-30 09:45:23 +0000737 "//command_line_option:platforms": "@soong_injection//product_config_platforms:%s" % target,
Yu Liue4312402023-01-18 09:15:31 -0800738 "@//build/bazel/rules/apex:within_apex": attr.within_apex,
739 "@//build/bazel/rules/apex:min_sdk_version": attr.apex_sdk_version,
740 "@//build/bazel/rules/apex:apex_name": apex_name,
Spandan Das40b79f82023-06-25 20:56:06 +0000741 "@//build/bazel/rules/apex:api_domain": attr.api_domain,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500742 }
743
Yu Liue4312402023-01-18 09:15:31 -0800744 return outputs
745
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400746_config_node_transition = transition(
747 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500748 inputs = [],
749 outputs = [
750 "//command_line_option:platforms",
Yu Liue4312402023-01-18 09:15:31 -0800751 "@//build/bazel/rules/apex:within_apex",
752 "@//build/bazel/rules/apex:min_sdk_version",
753 "@//build/bazel/rules/apex:apex_name",
Spandan Das40b79f82023-06-25 20:56:06 +0000754 "@//build/bazel/rules/apex:api_domain",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500755 ],
756)
757
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400758def _passthrough_rule_impl(ctx):
759 return [DefaultInfo(files = depset(ctx.files.deps))]
760
761config_node = rule(
762 implementation = _passthrough_rule_impl,
763 attrs = {
Yu Liue4312402023-01-18 09:15:31 -0800764 "arch" : attr.string(mandatory = True),
765 "os" : attr.string(mandatory = True),
766 "within_apex" : attr.bool(default = False),
767 "apex_sdk_version" : attr.string(mandatory = True),
Spandan Das40b79f82023-06-25 20:56:06 +0000768 "api_domain" : attr.string(mandatory = True),
Yu Liue4312402023-01-18 09:15:31 -0800769 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400770 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
771 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500772)
773
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400774
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500775# Rule representing the root of the build, to depend on all Bazel targets that
776# are required for the build. Building this target will build the entire Bazel
777# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400778mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400779 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500780 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400781 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500782 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400783)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500784
785def _phony_root_impl(ctx):
786 return []
787
788# Rule to depend on other targets but build nothing.
789# This is useful as follows: building a target of this rule will generate
790# symlink forests for all dependencies of the target, without executing any
791# actions of the build.
792phony_root = rule(
793 implementation = _phony_root_impl,
794 attrs = {"deps" : attr.label_list()},
795)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400796`
Cole Faustb85d1a12022-11-08 18:14:01 -0800797
798 productReplacer := strings.NewReplacer(
799 "{PRODUCT}", context.targetProduct,
800 "{VARIANT}", context.targetBuildVariant)
801
802 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400803}
804
Sasha Smundak39a301c2022-12-29 17:11:49 -0800805func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500806 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
807 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400808 formatString := `
809# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400810load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
811
812%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400813
814mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400815 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000816 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400817)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500818
819phony_root(name = "phonyroot",
820 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000821 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500822)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400823`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400824 configNodeFormatString := `
825config_node(name = "%s",
826 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400827 os = "%s",
Yu Liue4312402023-01-18 09:15:31 -0800828 within_apex = %s,
829 apex_sdk_version = "%s",
Spandan Das40b79f82023-06-25 20:56:06 +0000830 api_domain = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400831 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000832 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400833)
834`
835
836 configNodesSection := ""
837
Chris Parsons787fb362021-10-14 18:43:51 -0400838 labelsByConfig := map[string][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500839
840 for _, val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200841 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400842 configString := getConfigString(val)
843 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400844 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400845
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500846 // Configs need to be sorted to maintain determinism of the BUILD file.
847 sortedConfigs := make([]string, 0, len(labelsByConfig))
848 for val := range labelsByConfig {
849 sortedConfigs = append(sortedConfigs, val)
850 }
851 sort.Slice(sortedConfigs, func(i, j int) bool { return sortedConfigs[i] < sortedConfigs[j] })
852
Jingwen Chen1e347862021-09-02 12:11:49 +0000853 allLabels := []string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500854 for _, configString := range sortedConfigs {
855 labels := labelsByConfig[configString]
Chris Parsons787fb362021-10-14 18:43:51 -0400856 configTokens := strings.Split(configString, "|")
Yu Liue4312402023-01-18 09:15:31 -0800857 if len(configTokens) < 2 {
Chris Parsons787fb362021-10-14 18:43:51 -0400858 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000859 }
Chris Parsons787fb362021-10-14 18:43:51 -0400860 archString := configTokens[0]
861 osString := configTokens[1]
Yu Liue4312402023-01-18 09:15:31 -0800862 withinApex := "False"
863 apexSdkVerString := ""
Spandan Das40b79f82023-06-25 20:56:06 +0000864 apiDomainString := ""
865 if osString == "android" {
866 // api domains are meaningful only for device variants
867 apiDomainString = "system"
868 }
Chris Parsons787fb362021-10-14 18:43:51 -0400869 targetString := fmt.Sprintf("%s_%s", osString, archString)
Yu Liue4312402023-01-18 09:15:31 -0800870 if len(configTokens) > 2 {
871 targetString += "_" + configTokens[2]
872 if configTokens[2] == withinApexToString(true) {
873 withinApex = "True"
874 }
875 }
876 if len(configTokens) > 3 {
877 targetString += "_" + configTokens[3]
878 apexSdkVerString = configTokens[3]
879 }
Spandan Das40b79f82023-06-25 20:56:06 +0000880 if len(configTokens) > 4 {
881 apiDomainString = configTokens[4]
882 targetString += "_" + apiDomainString
883 }
Chris Parsons787fb362021-10-14 18:43:51 -0400884 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
885 labelsString := strings.Join(labels, ",\n ")
Spandan Das40b79f82023-06-25 20:56:06 +0000886 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, withinApex, apexSdkVerString, apiDomainString,
Yu Liue4312402023-01-18 09:15:31 -0800887 labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400888 }
889
Jingwen Chen1e347862021-09-02 12:11:49 +0000890 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400891}
892
Chris Parsons944e7d02021-03-11 11:08:46 -0500893func indent(original string) string {
894 result := ""
895 for _, line := range strings.Split(original, "\n") {
896 result += " " + line + "\n"
897 }
898 return result
899}
900
Chris Parsons808d84c2021-03-09 20:43:32 -0500901// Returns the file contents of the buildroot.cquery file that should be used for the cquery
902// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800903// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500904// and grouped by their request type. The data retrieved for each label depends on its
905// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800906func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400907 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons38851d82023-03-15 00:19:32 -0400908 requestTypes := []cqueryRequest{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500909 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500910 cqueryId := getCqueryId(val)
911 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
Chris Parsons38851d82023-03-15 00:19:32 -0400912 if _, seenKey := requestTypeToCqueryIdEntries[val.requestType]; !seenKey {
913 requestTypes = append(requestTypes, val.requestType)
914 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500915 requestTypeToCqueryIdEntries[val.requestType] =
916 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
917 }
918 labelRegistrationMapSection := ""
919 functionDefSection := ""
920 mainSwitchSection := ""
921
922 mapDeclarationFormatString := `
923%s = {
924 %s
925}
926`
927 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800928def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500929%s
930`
931 mainSwitchSectionFormatString := `
932 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800933 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500934`
935
Chris Parsons38851d82023-03-15 00:19:32 -0400936 for _, requestType := range requestTypes {
Chris Parsons944e7d02021-03-11 11:08:46 -0500937 labelMapName := requestType.Name() + "_Labels"
938 functionName := requestType.Name() + "_Fn"
939 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
940 labelMapName,
941 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
942 functionDefSection += fmt.Sprintf(functionDefFormatString,
943 functionName,
944 indent(requestType.StarlarkFunctionBody()))
945 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
946 labelMapName, functionName)
947 }
948
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400949 formatString := `
950# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400951
Cole Faustb85d1a12022-11-08 18:14:01 -0800952{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500953
Cole Faustb85d1a12022-11-08 18:14:01 -0800954{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500955
956def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400957 # TODO(b/199363072): filegroups and file targets aren't associated with any
958 # specific platform architecture in mixed builds. This is consistent with how
959 # Soong treats filegroups, but it may not be the case with manually-written
960 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500961 buildoptions = build_options(target)
Yu Liue4312402023-01-18 09:15:31 -0800962
Jingwen Chen8f222742021-10-07 12:02:23 +0000963 if buildoptions == None:
964 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400965 # any specific platform architecture in mixed builds, so use the host.
966 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -0800967 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500968 if len(platforms) != 1:
969 # An individual configured target should have only one platform architecture.
970 # Note that it's fine for there to be multiple architectures for the same label,
971 # but each is its own configured target.
972 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -0800973 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -0500974 if platform_name == "host":
975 return "HOST"
Cole Faust319abae2023-06-06 15:12:49 -0700976 if not platform_name.startswith("mixed_builds_product-{TARGET_BUILD_VARIANT}"):
977 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))
978 platform_name = platform_name.removeprefix("mixed_builds_product-{TARGET_BUILD_VARIANT}").removeprefix("_")
Yu Liue4312402023-01-18 09:15:31 -0800979 config_key = ""
Cole Faustb85d1a12022-11-08 18:14:01 -0800980 if not platform_name:
Yu Liue4312402023-01-18 09:15:31 -0800981 config_key = "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400982 elif platform_name.startswith("android_"):
Yu Liue4312402023-01-18 09:15:31 -0800983 config_key = platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400984 elif platform_name.startswith("linux_"):
Yu Liue4312402023-01-18 09:15:31 -0800985 config_key = platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400986 else:
Cole Faust319abae2023-06-06 15:12:49 -0700987 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 -0500988
Yu Liue4312402023-01-18 09:15:31 -0800989 within_apex = buildoptions.get("//build/bazel/rules/apex:within_apex")
990 apex_sdk_version = buildoptions.get("//build/bazel/rules/apex:min_sdk_version")
Spandan Das40b79f82023-06-25 20:56:06 +0000991 api_domain = buildoptions.get("//build/bazel/rules/apex:api_domain")
Yu Liue4312402023-01-18 09:15:31 -0800992
993 if within_apex:
994 config_key += "|within_apex"
995 if apex_sdk_version != None and len(apex_sdk_version) > 0:
996 config_key += "|" + apex_sdk_version
Spandan Das40b79f82023-06-25 20:56:06 +0000997 if api_domain != None and len(api_domain) > 0:
998 config_key += "|" + api_domain
Yu Liue4312402023-01-18 09:15:31 -0800999
1000 return config_key
1001
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001002def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -05001003 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -05001004
Chris Parsons86dc2c22022-09-28 14:58:41 -04001005 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
1006 if id_string.startswith("//"):
1007 id_string = "@" + id_string
1008
Cole Faustb85d1a12022-11-08 18:14:01 -08001009 {MAIN_SWITCH_SECTION}
1010
Chris Parsons944e7d02021-03-11 11:08:46 -05001011 # This target was not requested via cquery, and thus must be a dependency
1012 # of a requested target.
1013 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001014`
Cole Faustb85d1a12022-11-08 18:14:01 -08001015 replacer := strings.NewReplacer(
1016 "{TARGET_PRODUCT}", context.targetProduct,
1017 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
1018 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
1019 "{FUNCTION_DEF_SECTION}", functionDefSection,
1020 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001021
Cole Faustb85d1a12022-11-08 18:14:01 -08001022 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001023}
1024
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001025// Returns a path containing build-related metadata required for interfacing
1026// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001027func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001028 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -05001029}
1030
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001031// Returns the path where the contents of the @soong_injection repository live.
1032// It is used by Soong to tell Bazel things it cannot over the command line.
1033func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001034 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001035}
1036
1037// Returns the path of the synthetic Bazel workspace that contains a symlink
1038// forest composed the whole source tree and BUILD files generated by bp2build.
1039func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001040 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001041}
1042
Jingwen Chen8c523582021-06-01 11:19:53 +00001043// Returns the path to the top level out dir ($OUT_DIR).
1044func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001045 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +00001046}
1047
Sasha Smundak4975c822022-11-16 15:28:18 -08001048const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
1049
1050var (
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001051 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
1052 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
1053 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
1054 allBazelCommands = []bazelCommand{aqueryCmd, cqueryCmd, buildCmd}
Sasha Smundak4975c822022-11-16 15:28:18 -08001055)
1056
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001057// Issues commands to Bazel to receive results for all cquery requests
1058// queued in the BazelContext.
Liz Kammer690fbac2023-02-10 11:11:17 -05001059func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx invokeBazelContext) error {
1060 eventHandler := ctx.GetEventHandler()
1061 eventHandler.Begin("bazel")
1062 defer eventHandler.End("bazel")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001063
Sasha Smundak4975c822022-11-16 15:28:18 -08001064 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
1065 if err := os.MkdirAll(metricsDir, 0777); err != nil {
1066 return err
1067 }
1068 }
1069 context.results = make(map[cqueryKey]string)
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001070 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001071 return err
1072 }
1073 if err := context.runAquery(config, ctx); err != nil {
1074 return err
1075 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001076 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001077 return err
1078 }
1079
1080 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001081 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -08001082 return nil
1083}
1084
Liz Kammer690fbac2023-02-10 11:11:17 -05001085func (context *mixedBuildBazelContext) runCquery(config Config, ctx invokeBazelContext) error {
1086 eventHandler := ctx.GetEventHandler()
1087 eventHandler.Begin("cquery")
1088 defer eventHandler.End("cquery")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001089 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +02001090 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
1091 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
1092 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -05001093 if err != nil {
1094 return err
1095 }
1096 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001097 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001098 return err
1099 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001100 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001101 return err
1102 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001103 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001104 return err
1105 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001106 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001107 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001108 return err
1109 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001110
Yu Liue4312402023-01-18 09:15:31 -08001111 extraFlags := []string{"--output=starlark", "--starlark:file=" + absolutePath(cqueryFileRelpath)}
1112 if Bool(config.productVariables.ClangCoverage) {
1113 extraFlags = append(extraFlags, "--collect_code_coverage")
1114 }
1115
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001116 cqueryCmdRequest := context.createBazelCommand(config, bazel.CqueryBuildRootRunName, cqueryCmd, extraFlags...)
1117 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCmdRequest, context.paths, eventHandler)
Wei Licbd181c2022-11-16 08:59:23 -08001118 if cqueryErr != nil {
1119 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001120 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001121 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", context.printableCqueryCommand(cqueryCmdRequest))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001122 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001123 return err
1124 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001125 cqueryResults := map[string]string{}
1126 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1127 if strings.Contains(outputLine, ">>") {
1128 splitLine := strings.SplitN(outputLine, ">>", 2)
1129 cqueryResults[splitLine[0]] = splitLine[1]
1130 }
1131 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001132 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001133 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001134 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001135 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001136 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001137 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001138 }
1139 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001140 return nil
1141}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001142
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001143func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1144 oldContents, err := os.ReadFile(path)
1145 if err != nil || !bytes.Equal(contents, oldContents) {
1146 err = os.WriteFile(path, contents, perm)
1147 }
1148 return nil
1149}
1150
Liz Kammer690fbac2023-02-10 11:11:17 -05001151func (context *mixedBuildBazelContext) runAquery(config Config, ctx invokeBazelContext) error {
1152 eventHandler := ctx.GetEventHandler()
1153 eventHandler.Begin("aquery")
1154 defer eventHandler.End("aquery")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001155 // Issue an aquery command to retrieve action information about the bazel build tree.
1156 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001157 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1158 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001159 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001160 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001161 extraFlags = append(extraFlags, "--collect_code_coverage")
1162 paths := make([]string, 0, 2)
1163 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001164 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001165 // TODO(b/259404593) convert path wildcard to regex values
1166 if p[i] == "*" {
1167 p[i] = ".*"
1168 }
1169 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001170 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1171 }
1172 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1173 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1174 }
1175 if len(paths) > 0 {
1176 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001177 }
1178 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001179 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.AqueryBuildRootRunName, aqueryCmd,
1180 extraFlags...), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001181 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001182 return err
1183 }
Liz Kammer690fbac2023-02-10 11:11:17 -05001184 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001185 return err
1186}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001187
Liz Kammer690fbac2023-02-10 11:11:17 -05001188func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx invokeBazelContext) error {
1189 eventHandler := ctx.GetEventHandler()
1190 eventHandler.Begin("symlinks")
1191 defer eventHandler.End("symlinks")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001192 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1193 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1194 // but some of symlinks may be required to resolve source dependencies of the build.
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001195 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.BazelBuildPhonyRootRunName, buildCmd), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001196 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001197}
Chris Parsonsa798d962020-10-12 23:44:08 -04001198
Liz Kammera4655a92023-02-10 17:17:28 -05001199func (context *mixedBuildBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001200 return context.buildStatements
1201}
1202
Sasha Smundak39a301c2022-12-29 17:11:49 -08001203func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001204 return context.depsets
1205}
1206
Sasha Smundak39a301c2022-12-29 17:11:49 -08001207func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001208 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001209}
1210
Chris Parsonsa798d962020-10-12 23:44:08 -04001211// Singleton used for registering BUILD file ninja dependencies (needed
1212// for correctness of builds which use Bazel.
1213func BazelSingleton() Singleton {
1214 return &bazelSingleton{}
1215}
1216
1217type bazelSingleton struct{}
1218
1219func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001220 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001221 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001222 return
1223 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001224
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001225 // Add ninja file dependencies for files which all bazel invocations require.
1226 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001227 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001228 ctx.AddNinjaFileDeps(bazelBuildList)
1229
Sasha Smundak0e87b182022-12-01 11:46:11 -08001230 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001231 if err != nil {
1232 ctx.Errorf(err.Error())
1233 }
1234 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1235 for _, file := range files {
1236 ctx.AddNinjaFileDeps(file)
1237 }
1238
Chris Parsons1a7aca02022-04-25 22:35:15 -04001239 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1240 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001241 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001242 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1243 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001244 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1245 }
1246 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001247 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1248 if artifactPath == "bazel-out/volatile-status.txt" {
1249 // See https://bazel.build/docs/user-manual#workspace-status
1250 orderOnlies = append(orderOnlies, pathInBazelOut)
1251 } else {
1252 outputs = append(outputs, pathInBazelOut)
1253 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001254 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001255 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001256 ctx.Build(pctx, BuildParams{
1257 Rule: blueprint.Phony,
1258 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1259 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001260 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001261 })
1262 }
1263
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001264 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1265 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001266 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Liz Kammera4655a92023-02-10 17:17:28 -05001267 // nil build statements are a valid case where we do not create an action because it is
1268 // unnecessary or handled by other processing
1269 if buildStatement == nil {
1270 continue
1271 }
Sasha Smundak1da064c2022-06-08 16:36:16 -07001272 if len(buildStatement.Command) > 0 {
1273 rule := NewRuleBuilder(pctx, ctx)
1274 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1275 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1276 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1277 continue
1278 }
1279 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1280 // and thus require special treatment. If BuildStatement were an interface implementing
1281 // buildRule(ctx) function, the code here would just call it.
1282 // Unfortunately, the BuildStatement is defined in
1283 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1284 // because this would cause circular dependency. So, until we move aquery processing
1285 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001286 switch buildStatement.Mnemonic {
1287 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001288 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1289 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001290 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001291 // build-runfiles arguments are the manifest file and the target directory
1292 // where it creates the symlink tree according to this manifest (and then
1293 // writes the MANIFEST file to it).
1294 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1295 outManifestPath := outManifest.String()
1296 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1297 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1298 }
1299 outDir := filepath.Dir(outManifestPath)
1300 ctx.Build(pctx, BuildParams{
1301 Rule: buildRunfilesRule,
1302 Output: outManifest,
1303 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1304 Description: "symlink tree for " + outDir,
1305 Args: map[string]string{
1306 "outDir": outDir,
1307 },
1308 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001309 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001310 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001311 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001312 }
1313}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001314
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001315// Register bazel-owned build statements (obtained from the aquery invocation).
Liz Kammera4655a92023-02-10 17:17:28 -05001316func createCommand(cmd *RuleBuilderCommand, buildStatement *bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001317 // executionRoot is the action cwd.
1318 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1319
1320 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1321 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001322 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001323 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001324 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001325 }
1326 cmd.Text("&&")
1327 }
1328
1329 for _, pair := range buildStatement.Env {
1330 // Set per-action env variables, if any.
1331 cmd.Flag(pair.Key + "=" + pair.Value)
1332 }
1333
1334 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001335 if len(buildStatement.Command) > 16*1024 {
1336 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1337 WriteFileRule(ctx, commandFile, buildStatement.Command)
1338
1339 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1340 } else {
1341 cmd.Text(buildStatement.Command)
1342 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001343
1344 for _, outputPath := range buildStatement.OutputPaths {
1345 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1346 }
1347 for _, inputPath := range buildStatement.InputPaths {
1348 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1349 }
1350 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1351 otherDepsetName := bazelDepsetName(inputDepsetHash)
1352 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1353 }
1354
1355 if depfile := buildStatement.Depfile; depfile != nil {
1356 // The paths in depfile are relative to `executionRoot`.
1357 // Hence, they need to be corrected by replacing "bazel-out"
1358 // with the full `bazelOutDir`.
1359 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1360 // would be deemed missing.
1361 // (Note: The regexp uses a capture group because the version of sed
1362 // does not support a look-behind pattern.)
1363 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1364 bazelOutDir, *depfile)
1365 cmd.Text(replacement)
1366 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1367 }
1368
1369 for _, symlinkPath := range buildStatement.SymlinkPaths {
1370 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1371 }
1372}
1373
Chris Parsons8d6e4332021-02-22 16:13:50 -05001374func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001375 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001376}
1377
Chris Parsons787fb362021-10-14 18:43:51 -04001378func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001379 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001380 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001381 if key.configKey.osType.Class == Device {
1382 // For the generic Android, the expected result is "target|android", which
1383 // corresponds to the product_variable_config named "android_target" in
1384 // build/bazel/platforms/BUILD.bazel.
1385 arch = "target"
1386 } else {
1387 // Use host platform, which is currently hardcoded to be x86_64.
1388 arch = "x86_64"
1389 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001390 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001391 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001392 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001393 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001394 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001395 }
Yu Liue4312402023-01-18 09:15:31 -08001396 keyString := arch + "|" + osName
1397 if key.configKey.apexKey.WithinApex {
1398 keyString += "|" + withinApexToString(key.configKey.apexKey.WithinApex)
1399 }
1400
1401 if len(key.configKey.apexKey.ApexSdkVersion) > 0 {
1402 keyString += "|" + key.configKey.apexKey.ApexSdkVersion
1403 }
1404
Spandan Das40b79f82023-06-25 20:56:06 +00001405 if len(key.configKey.apexKey.ApiDomain) > 0 {
1406 keyString += "|" + key.configKey.apexKey.ApiDomain
1407 }
1408
Yu Liue4312402023-01-18 09:15:31 -08001409 return keyString
Chris Parsons787fb362021-10-14 18:43:51 -04001410}
1411
Chris Parsonsf874e462022-05-10 13:50:12 -04001412func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001413 return configKey{
1414 // use string because Arch is not a valid key in go
1415 arch: ctx.Arch().String(),
1416 osType: ctx.Os(),
1417 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001418}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001419
Yu Liue4312402023-01-18 09:15:31 -08001420func GetConfigKeyApexVariant(ctx BaseModuleContext, apexKey *ApexConfigKey) configKey {
1421 configKey := GetConfigKey(ctx)
1422
1423 if apexKey != nil {
1424 configKey.apexKey = ApexConfigKey{
1425 WithinApex: apexKey.WithinApex,
1426 ApexSdkVersion: apexKey.ApexSdkVersion,
Spandan Das40b79f82023-06-25 20:56:06 +00001427 ApiDomain: apexKey.ApiDomain,
Yu Liue4312402023-01-18 09:15:31 -08001428 }
1429 }
1430
1431 return configKey
1432}
1433
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001434func bazelDepsetName(contentHash string) string {
1435 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001436}