blob: 77a9f248611099dbb44a9e82c4e171d47084ba9b [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
95}
96
97func (c ApexConfigKey) String() string {
98 return fmt.Sprintf("%s_%s", withinApexToString(c.WithinApex), c.ApexSdkVersion)
99}
100
101func withinApexToString(withinApex bool) string {
102 if withinApex {
103 return "within_apex"
104 }
105 return ""
Chris Parsons787fb362021-10-14 18:43:51 -0400106}
107
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700108func (c configKey) String() string {
Yu Liue4312402023-01-18 09:15:31 -0800109 return fmt.Sprintf("%s::%s::%s", c.arch, c.osType, c.apexKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700110}
111
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400112// Map key to describe bazel cquery requests.
113type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400114 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400115 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400116 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400117}
118
Chris Parsons86dc2c22022-09-28 14:58:41 -0400119func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
120 if strings.HasPrefix(label, "//") {
121 // Normalize Bazel labels to specify main repository explicitly.
122 label = "@" + label
123 }
124 return cqueryKey{label, cqueryRequest, cfgKey}
125}
126
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700127func (c cqueryKey) String() string {
128 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700129}
130
Liz Kammer690fbac2023-02-10 11:11:17 -0500131type invokeBazelContext interface {
132 GetEventHandler() *metrics.EventHandler
133}
134
Chris Parsonsf874e462022-05-10 13:50:12 -0400135// BazelContext is a context object useful for interacting with Bazel during
136// the course of a build. Use of Bazel to evaluate part of the build graph
137// is referred to as a "mixed build". (Some modules are managed by Soong,
138// some are managed by Bazel). To facilitate interop between these build
139// subgraphs, Soong may make requests to Bazel and evaluate their responses
140// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400141type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400142 // Add a cquery request to the bazel request queue. All queued requests
143 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
144 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
145
146 // ** Cquery Results Retrieval Functions
147 // The below functions pertain to retrieving cquery results from a prior
148 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400149
150 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400151 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500152
Chris Parsons944e7d02021-03-11 11:08:46 -0500153 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400154 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400155
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700156 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400157 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700158
Sasha Smundakedd16662022-10-07 14:44:50 -0700159 // Returns the results of the GetCcUnstrippedInfo query
160 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
161
Spandan Dasbd156812023-06-05 22:43:13 +0000162 // Returns the results of the GetPrebuiltFileInfo query
163 GetPrebuiltFileInfo(label string, cfgKey configKey) (cquery.PrebuiltFileInfo, error)
164
Chris Parsonsf874e462022-05-10 13:50:12 -0400165 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400166
167 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800168 // queued in the BazelContext. The ctx argument is optional and is only
169 // used for performance data collection
Liz Kammer690fbac2023-02-10 11:11:17 -0500170 InvokeBazel(config Config, ctx invokeBazelContext) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400171
Chris Parsonsad876012022-08-20 14:48:32 -0400172 // Returns true if Bazel handling is enabled for the module with the given name.
173 // Note that this only implies "bazel mixed build" allowlisting. The caller
174 // should independently verify the module is eligible for Bazel handling
175 // (for example, that it is MixedBuildBuildable).
Yu Liue4312402023-01-18 09:15:31 -0800176 IsModuleNameAllowed(moduleName string, withinApex bool) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500177
Yu Liubfb23622023-02-22 10:42:15 -0800178 IsModuleDclaAllowed(moduleName string) bool
179
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500180 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
181 OutputBase() string
182
183 // Returns build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500184 BuildStatementsToRegister() []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400185
186 // Returns the depsets defined in Bazel's aquery response.
187 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400188}
189
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400190type bazelRunner interface {
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000191 issueBazelCommand(cmdRequest bazel.CmdRequest, paths *bazelPaths, eventHandler *metrics.EventHandler) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400192}
193
194type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000195 homeDir string
196 bazelPath string
197 outputBase string
198 workspaceDir string
199 soongOutDir string
200 metricsDir string
201 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400202}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400203
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400204// A context object which tracks queued requests that need to be made to Bazel,
205// and their results after the requests have been made.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800206type mixedBuildBazelContext struct {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400207 bazelRunner
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500208 paths *bazelPaths
209 // cquery requests that have not yet been issued to Bazel. This list is maintained
210 // in a sorted state, and is guaranteed to have no duplicates.
211 requests []cqueryKey
212 requestMutex sync.Mutex // requests can be written in parallel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400213
214 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500215
216 // Build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500217 buildStatements []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400218
219 // Depsets which should be used for Bazel's build statements.
220 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400221
222 // Per-module allowlist/denylist functionality to control whether analysis of
223 // modules are handled by Bazel. For modules which do not have a Bazel definition
224 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
225 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
226 // Per-module denylist to opt modules out of bazel handling.
227 bazelDisabledModules map[string]bool
228 // Per-module allowlist to opt modules in to bazel handling.
229 bazelEnabledModules map[string]bool
Yu Liue4312402023-01-18 09:15:31 -0800230 // DCLA modules are enabled when used in apex.
231 bazelDclaEnabledModules map[string]bool
Chris Parsonsad876012022-08-20 14:48:32 -0400232 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
233 modulesDefaultToBazel bool
Cole Faustb85d1a12022-11-08 18:14:01 -0800234
235 targetProduct string
236 targetBuildVariant string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400237}
238
Sasha Smundak39a301c2022-12-29 17:11:49 -0800239var _ BazelContext = &mixedBuildBazelContext{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400240
241// A bazel context to use when Bazel is disabled.
242type noopBazelContext struct{}
243
244var _ BazelContext = noopBazelContext{}
245
246// A bazel context to use for tests.
247type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400248 OutputBaseDir string
249
Spandan Dasbd156812023-06-05 22:43:13 +0000250 LabelToOutputFiles map[string][]string
251 LabelToCcInfo map[string]cquery.CcInfo
252 LabelToPythonBinary map[string]string
253 LabelToApexInfo map[string]cquery.ApexInfo
254 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
255 LabelToPrebuiltFileInfo map[string]cquery.PrebuiltFileInfo
Yu Liue4312402023-01-18 09:15:31 -0800256
257 BazelRequests map[string]bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400258}
259
Yu Liue4312402023-01-18 09:15:31 -0800260func (m MockBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
261 key := BuildMockBazelContextRequestKey(label, requestType, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
262 if m.BazelRequests == nil {
263 m.BazelRequests = make(map[string]bool)
264 }
265 m.BazelRequests[key] = true
Chris Parsons8d6e4332021-02-22 16:13:50 -0500266}
267
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700268func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500269 result, ok := m.LabelToOutputFiles[label]
270 if !ok {
271 return []string{}, fmt.Errorf("no target with label %q in LabelToOutputFiles", label)
272 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400273 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400274}
275
Yu Liue4312402023-01-18 09:15:31 -0800276func (m MockBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500277 result, ok := m.LabelToCcInfo[label]
278 if !ok {
Yu Liue4312402023-01-18 09:15:31 -0800279 key := BuildMockBazelContextResultKey(label, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
280 result, ok = m.LabelToCcInfo[key]
281 if !ok {
282 return cquery.CcInfo{}, fmt.Errorf("no target with label %q in LabelToCcInfo", label)
283 }
Sam Delmericoce39f832023-01-23 14:04:24 -0500284 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400285 return result, nil
286}
287
Liz Kammerbe6a7122022-11-04 16:05:11 -0400288func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500289 result, ok := m.LabelToApexInfo[label]
290 if !ok {
291 return cquery.ApexInfo{}, fmt.Errorf("no target with label %q in LabelToApexInfo", label)
292 }
Liz Kammer0e255ef2022-11-04 16:07:04 -0400293 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700294}
295
Sasha Smundakedd16662022-10-07 14:44:50 -0700296func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500297 result, ok := m.LabelToCcBinary[label]
298 if !ok {
299 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no target with label %q in LabelToCcBinary", label)
300 }
Sasha Smundakedd16662022-10-07 14:44:50 -0700301 return result, nil
302}
303
Spandan Dasbd156812023-06-05 22:43:13 +0000304func (m MockBazelContext) GetPrebuiltFileInfo(label string, _ configKey) (cquery.PrebuiltFileInfo, error) {
305 result, ok := m.LabelToPrebuiltFileInfo[label]
306 if !ok {
307 return cquery.PrebuiltFileInfo{}, fmt.Errorf("no target with label %q in LabelToPrebuiltFileInfo", label)
308 }
309 return result, nil
310}
311
Liz Kammer690fbac2023-02-10 11:11:17 -0500312func (m MockBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400313 panic("unimplemented")
314}
315
Yu Liue4312402023-01-18 09:15:31 -0800316func (m MockBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400317 return true
318}
319
Yu Liubfb23622023-02-22 10:42:15 -0800320func (m MockBazelContext) IsModuleDclaAllowed(_ string) bool {
321 return true
322}
323
Liz Kammera92e8442021-04-07 20:25:21 -0400324func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500325
Liz Kammera4655a92023-02-10 17:17:28 -0500326func (m MockBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
327 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500328}
329
Chris Parsons1a7aca02022-04-25 22:35:15 -0400330func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
331 return []bazel.AqueryDepset{}
332}
333
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400334var _ BazelContext = MockBazelContext{}
335
Yu Liue4312402023-01-18 09:15:31 -0800336func BuildMockBazelContextRequestKey(label string, request cqueryRequest, arch string, osType OsType, apexKey ApexConfigKey) string {
337 cfgKey := configKey{
338 arch: arch,
339 osType: osType,
340 apexKey: apexKey,
341 }
342
343 return strings.Join([]string{label, request.Name(), cfgKey.String()}, "_")
344}
345
346func BuildMockBazelContextResultKey(label string, arch string, osType OsType, apexKey ApexConfigKey) string {
347 cfgKey := configKey{
348 arch: arch,
349 osType: osType,
350 apexKey: apexKey,
351 }
352
353 return strings.Join([]string{label, cfgKey.String()}, "_")
354}
355
Sasha Smundak39a301c2022-12-29 17:11:49 -0800356func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400357 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400358 bazelCtx.requestMutex.Lock()
359 defer bazelCtx.requestMutex.Unlock()
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500360
361 // Insert key into requests, maintaining the sort, and only if it's not duplicate.
362 keyString := key.String()
363 foundEqual := false
364 notLessThanKeyString := func(i int) bool {
365 s := bazelCtx.requests[i].String()
366 v := strings.Compare(s, keyString)
367 if v == 0 {
368 foundEqual = true
369 }
370 return v >= 0
371 }
372 targetIndex := sort.Search(len(bazelCtx.requests), notLessThanKeyString)
373 if foundEqual {
374 return
375 }
376
377 if targetIndex == len(bazelCtx.requests) {
378 bazelCtx.requests = append(bazelCtx.requests, key)
379 } else {
380 bazelCtx.requests = append(bazelCtx.requests[:targetIndex+1], bazelCtx.requests[targetIndex:]...)
381 bazelCtx.requests[targetIndex] = key
382 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400383}
384
Sasha Smundak39a301c2022-12-29 17:11:49 -0800385func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400386 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400387 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500388 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400389
Chris Parsonsf874e462022-05-10 13:50:12 -0400390 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400391 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400392 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400393}
394
Sasha Smundak39a301c2022-12-29 17:11:49 -0800395func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400396 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400397 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000398 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400399 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000400 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400401 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 +0000402}
403
Sasha Smundak39a301c2022-12-29 17:11:49 -0800404func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400405 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700406 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500407 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700408 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400409 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700410}
411
Sasha Smundak39a301c2022-12-29 17:11:49 -0800412func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700413 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
414 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500415 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700416 }
417 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
418}
419
Spandan Dasbd156812023-06-05 22:43:13 +0000420func (bazelCtx *mixedBuildBazelContext) GetPrebuiltFileInfo(label string, cfgKey configKey) (cquery.PrebuiltFileInfo, error) {
421 key := makeCqueryKey(label, cquery.GetPrebuiltFileInfo, cfgKey)
422 if rawString, ok := bazelCtx.results[key]; ok {
423 return cquery.GetPrebuiltFileInfo.ParseResult(strings.TrimSpace(rawString))
424 }
425 return cquery.PrebuiltFileInfo{}, fmt.Errorf("no bazel response for %s", key)
426}
427
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700428func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500429 panic("unimplemented")
430}
431
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700432func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500433 panic("unimplemented")
434}
435
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700436func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400437 panic("unimplemented")
438}
439
Liz Kammerbe6a7122022-11-04 16:05:11 -0400440func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700441 panic("unimplemented")
442}
443
Sasha Smundakedd16662022-10-07 14:44:50 -0700444func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
445 //TODO implement me
446 panic("implement me")
447}
448
Spandan Dasbd156812023-06-05 22:43:13 +0000449func (n noopBazelContext) GetPrebuiltFileInfo(_ string, _ configKey) (cquery.PrebuiltFileInfo, error) {
450 panic("implement me")
451}
452
Liz Kammer690fbac2023-02-10 11:11:17 -0500453func (n noopBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400454 panic("unimplemented")
455}
456
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500457func (m noopBazelContext) OutputBase() string {
458 return ""
459}
460
Yu Liue4312402023-01-18 09:15:31 -0800461func (n noopBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400462 return false
463}
464
Yu Liubfb23622023-02-22 10:42:15 -0800465func (n noopBazelContext) IsModuleDclaAllowed(_ string) bool {
466 return false
467}
468
Liz Kammera4655a92023-02-10 17:17:28 -0500469func (m noopBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
470 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500471}
472
Chris Parsons1a7aca02022-04-25 22:35:15 -0400473func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
474 return []bazel.AqueryDepset{}
475}
476
Yu Liu6a7940c2023-05-09 17:12:22 -0700477func AddToStringSet(set map[string]bool, items []string) {
Yu Liue4312402023-01-18 09:15:31 -0800478 for _, item := range items {
479 set[item] = true
480 }
481}
482
Cole Faust705968d2022-12-14 11:32:05 -0800483func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400484 disabledModules := map[string]bool{}
485 enabledModules := map[string]bool{}
486
Cole Faust705968d2022-12-14 11:32:05 -0800487 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400488 case BazelProdMode:
Yu Liu6a7940c2023-05-09 17:12:22 -0700489 AddToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800490 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000491 enabledModules[enabledAdHocModule] = true
492 }
MarkDacekb78465d2022-10-18 20:10:16 +0000493 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400494 // Staging mode includes all prod modules plus all staging modules.
Yu Liu6a7940c2023-05-09 17:12:22 -0700495 AddToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
496 AddToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800497 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000498 enabledModules[enabledAdHocModule] = true
499 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400500 case BazelDevMode:
Yu Liu6a7940c2023-05-09 17:12:22 -0700501 AddToStringSet(disabledModules, allowlists.MixedBuildsDisabledList)
Chris Parsonsef615e52022-08-18 22:04:11 -0400502 default:
Cole Faust705968d2022-12-14 11:32:05 -0800503 panic("Expected BazelProdMode, BazelStagingMode, or BazelDevMode")
504 }
505 return enabledModules, disabledModules
506}
507
508func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
509 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
510 enabledList := make([]string, 0, len(enabledModules))
511 for module := range enabledModules {
512 if !disabledModules[module] {
513 enabledList = append(enabledList, module)
514 }
515 }
516 sort.Strings(enabledList)
517 return enabledList
518}
519
520func NewBazelContext(c *config) (BazelContext, error) {
521 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode && c.BuildMode != BazelDevMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400522 return noopBazelContext{}, nil
523 }
524
Cole Faust705968d2022-12-14 11:32:05 -0800525 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
526
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800527 paths := bazelPaths{
528 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400529 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800530 var missing []string
531 vars := []struct {
532 name string
533 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000534
535 // True if the environment variable needs to be tracked so that changes to the variable
536 // cause the ninja file to be regenerated, false otherwise. False should only be set for
537 // environment variables that have no effect on the generated ninja file.
538 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800539 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000540 {"BAZEL_HOME", &paths.homeDir, true},
541 {"BAZEL_PATH", &paths.bazelPath, true},
542 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
543 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
544 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
545 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800546 }
547 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000548 if v.track {
549 if s := c.Getenv(v.name); len(s) > 1 {
550 *v.ptr = s
551 continue
552 }
553 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800554 *v.ptr = s
555 } else {
556 missing = append(missing, v.name)
557 }
558 }
559 if len(missing) > 0 {
560 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
561 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800562
563 targetBuildVariant := "user"
564 if c.Eng() {
565 targetBuildVariant = "eng"
566 } else if c.Debuggable() {
567 targetBuildVariant = "userdebug"
568 }
569 targetProduct := "unknown"
570 if c.HasDeviceProduct() {
571 targetProduct = c.DeviceProduct()
572 }
Yu Liue4312402023-01-18 09:15:31 -0800573 dclaMixedBuildsEnabledList := []string{}
574 if c.BuildMode == BazelProdMode {
575 dclaMixedBuildsEnabledList = allowlists.ProdDclaMixedBuildsEnabledList
576 } else if c.BuildMode == BazelStagingMode {
577 dclaMixedBuildsEnabledList = append(allowlists.ProdDclaMixedBuildsEnabledList,
578 allowlists.StagingDclaMixedBuildsEnabledList...)
579 }
580 dclaEnabledModules := map[string]bool{}
Yu Liu6a7940c2023-05-09 17:12:22 -0700581 AddToStringSet(dclaEnabledModules, dclaMixedBuildsEnabledList)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800582 return &mixedBuildBazelContext{
Chris Parsons9402ca82023-02-23 17:28:06 -0500583 bazelRunner: &builtinBazelRunner{c.UseBazelProxy, absolutePath(c.outDir)},
Yu Liue4312402023-01-18 09:15:31 -0800584 paths: &paths,
585 modulesDefaultToBazel: c.BuildMode == BazelDevMode,
586 bazelEnabledModules: enabledModules,
587 bazelDisabledModules: disabledModules,
588 bazelDclaEnabledModules: dclaEnabledModules,
589 targetProduct: targetProduct,
590 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400591 }, nil
592}
593
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400594func (p *bazelPaths) BazelMetricsDir() string {
595 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000596}
597
Yu Liue4312402023-01-18 09:15:31 -0800598func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string, withinApex bool) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400599 if context.bazelDisabledModules[moduleName] {
600 return false
601 }
602 if context.bazelEnabledModules[moduleName] {
603 return true
604 }
Yu Liubfb23622023-02-22 10:42:15 -0800605 if withinApex && context.IsModuleDclaAllowed(moduleName) {
Yu Liue4312402023-01-18 09:15:31 -0800606 return true
607 }
608
Chris Parsonsad876012022-08-20 14:48:32 -0400609 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400610}
611
Yu Liubfb23622023-02-22 10:42:15 -0800612func (context *mixedBuildBazelContext) IsModuleDclaAllowed(moduleName string) bool {
613 return context.bazelDclaEnabledModules[moduleName]
614}
615
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400616func pwdPrefix() string {
617 // Darwin doesn't have /proc
618 if runtime.GOOS != "darwin" {
619 return "PWD=/proc/self/cwd"
620 }
621 return ""
622}
623
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400624type bazelCommand struct {
625 command string
626 // query or label
627 expression string
628}
629
Chris Parsons9402ca82023-02-23 17:28:06 -0500630type builtinBazelRunner struct {
631 useBazelProxy bool
632 outDir string
633}
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400634
Chris Parsons808d84c2021-03-09 20:43:32 -0500635// Issues the given bazel command with given build label and additional flags.
636// Returns (stdout, stderr, error). The first and second return values are strings
637// containing the stdout and stderr of the run command, and an error is returned if
638// the invocation returned an error code.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000639func (r *builtinBazelRunner) issueBazelCommand(cmdRequest bazel.CmdRequest, paths *bazelPaths, eventHandler *metrics.EventHandler) (string, string, error) {
Chris Parsons9402ca82023-02-23 17:28:06 -0500640 if r.useBazelProxy {
641 eventHandler.Begin("client_proxy")
642 defer eventHandler.End("client_proxy")
643 proxyClient := bazel.NewProxyClient(r.outDir)
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000644 resp, err := proxyClient.IssueCommand(cmdRequest)
Chris Parsons9402ca82023-02-23 17:28:06 -0500645
646 if err != nil {
647 return "", "", err
648 }
649 if len(resp.ErrorString) > 0 {
650 return "", "", fmt.Errorf(resp.ErrorString)
651 }
652 return resp.Stdout, resp.Stderr, nil
Jason Wu52cd1942022-09-08 15:37:57 +0000653 } else {
Chris Parsons9402ca82023-02-23 17:28:06 -0500654 eventHandler.Begin("bazel command")
655 defer eventHandler.End("bazel command")
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000656
657 stdout, stderr, err := bazel.ExecBazel(paths.bazelPath, absolutePath(paths.syntheticWorkspaceDir()), cmdRequest)
658 return string(stdout), string(stderr), err
Jason Wu52cd1942022-09-08 15:37:57 +0000659 }
660}
661
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000662func (context *mixedBuildBazelContext) createBazelCommand(config Config, runName bazel.RunName, command bazelCommand,
663 extraFlags ...string) bazel.CmdRequest {
Cole Faust319abae2023-06-06 15:12:49 -0700664 if runtime.GOOS != "linux" && runtime.GOOS != "darwin" {
665 panic("Unknown GOOS: " + runtime.GOOS)
666 }
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000667 cmdFlags := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000668 "--output_base=" + absolutePath(context.paths.outputBase),
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000669 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700670 command.expression,
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000671 "--profile=" + shared.BazelMetricsFilename(context.paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400672
Cole Faust319abae2023-06-06 15:12:49 -0700673 "--host_platform=@soong_injection//product_config_platforms:mixed_builds_product-" + context.targetBuildVariant + "_" + runtime.GOOS + "_x86_64",
674 // Don't specify --platforms, because on some products/branches (like kernel-build-tools)
675 // the main platform for mixed_builds_product-variant doesn't exist because an arch isn't
676 // specified in product config. The derivative platforms that config_node transitions into
677 // will still work.
Jingwen Chen583ab212023-05-30 09:45:23 +0000678
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700679 // Suppress noise
680 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500681 "--noshow_progress",
682 "--norun_validations",
683 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400684 cmdFlags = append(cmdFlags, extraFlags...)
685
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700686 extraEnv := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000687 "HOME=" + context.paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200688 pwdPrefix(),
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000689 "BUILD_DIR=" + absolutePath(context.paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700690 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000691 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000692 "OUT_DIR=" + absolutePath(context.paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500693 // Disables local host detection of gcc; toolchain information is defined
694 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700695 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
696 }
Cole Faust8a161be2023-06-14 15:45:12 -0700697 capturedEnvVars, err := starlark_import.GetStarlarkValue[[]string]("captured_env_vars")
698 if err != nil {
699 panic(err)
700 }
701 for _, envvar := range capturedEnvVars {
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500702 val := config.Getenv(envvar)
703 if val == "" {
704 continue
705 }
706 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
707 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000708 envVars := append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400709
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000710 return bazel.CmdRequest{cmdFlags, envVars}
Jason Wu52cd1942022-09-08 15:37:57 +0000711}
712
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000713func (context *mixedBuildBazelContext) printableCqueryCommand(bazelCmd bazel.CmdRequest) string {
714 args := append([]string{context.paths.bazelPath}, bazelCmd.Argv...)
715 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(args, "\" \"") + "\""
Jason Wu52cd1942022-09-08 15:37:57 +0000716 return outputString
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400717}
718
Sasha Smundak39a301c2022-12-29 17:11:49 -0800719func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500720 // TODO(cparsons): Define configuration transitions programmatically based
721 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400722 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500723#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400724# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500725#####################################################
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400726def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800727 if attr.os == "android" and attr.arch == "target":
Cole Faust319abae2023-06-06 15:12:49 -0700728 target = "mixed_builds_product-{VARIANT}"
Cole Faustb85d1a12022-11-08 18:14:01 -0800729 else:
Cole Faust319abae2023-06-06 15:12:49 -0700730 target = "mixed_builds_product-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Yu Liue4312402023-01-18 09:15:31 -0800731 apex_name = ""
732 if attr.within_apex:
733 # //build/bazel/rules/apex:apex_name has to be set to a non_empty value,
734 # otherwise //build/bazel/rules/apex:non_apex will be true and the
735 # "-D__ANDROID_APEX__" compiler flag will be missing. Apex_name is used
736 # in some validation on bazel side which don't really apply in mixed
737 # build because soong will do the work, so we just set it to a fixed
738 # value here.
739 apex_name = "dcla_apex"
740 outputs = {
Jingwen Chen583ab212023-05-30 09:45:23 +0000741 "//command_line_option:platforms": "@soong_injection//product_config_platforms:%s" % target,
Yu Liue4312402023-01-18 09:15:31 -0800742 "@//build/bazel/rules/apex:within_apex": attr.within_apex,
743 "@//build/bazel/rules/apex:min_sdk_version": attr.apex_sdk_version,
744 "@//build/bazel/rules/apex:apex_name": apex_name,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500745 }
746
Yu Liue4312402023-01-18 09:15:31 -0800747 return outputs
748
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400749_config_node_transition = transition(
750 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500751 inputs = [],
752 outputs = [
753 "//command_line_option:platforms",
Yu Liue4312402023-01-18 09:15:31 -0800754 "@//build/bazel/rules/apex:within_apex",
755 "@//build/bazel/rules/apex:min_sdk_version",
756 "@//build/bazel/rules/apex:apex_name",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500757 ],
758)
759
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400760def _passthrough_rule_impl(ctx):
761 return [DefaultInfo(files = depset(ctx.files.deps))]
762
763config_node = rule(
764 implementation = _passthrough_rule_impl,
765 attrs = {
Yu Liue4312402023-01-18 09:15:31 -0800766 "arch" : attr.string(mandatory = True),
767 "os" : attr.string(mandatory = True),
768 "within_apex" : attr.bool(default = False),
769 "apex_sdk_version" : attr.string(mandatory = True),
770 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400771 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
772 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500773)
774
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400775
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500776# Rule representing the root of the build, to depend on all Bazel targets that
777# are required for the build. Building this target will build the entire Bazel
778# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400779mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400780 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500781 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400782 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500783 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400784)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500785
786def _phony_root_impl(ctx):
787 return []
788
789# Rule to depend on other targets but build nothing.
790# This is useful as follows: building a target of this rule will generate
791# symlink forests for all dependencies of the target, without executing any
792# actions of the build.
793phony_root = rule(
794 implementation = _phony_root_impl,
795 attrs = {"deps" : attr.label_list()},
796)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400797`
Cole Faustb85d1a12022-11-08 18:14:01 -0800798
799 productReplacer := strings.NewReplacer(
800 "{PRODUCT}", context.targetProduct,
801 "{VARIANT}", context.targetBuildVariant)
802
803 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400804}
805
Sasha Smundak39a301c2022-12-29 17:11:49 -0800806func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500807 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
808 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400809 formatString := `
810# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400811load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
812
813%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400814
815mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400816 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000817 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400818)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500819
820phony_root(name = "phonyroot",
821 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000822 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500823)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400824`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400825 configNodeFormatString := `
826config_node(name = "%s",
827 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400828 os = "%s",
Yu Liue4312402023-01-18 09:15:31 -0800829 within_apex = %s,
830 apex_sdk_version = "%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 := ""
Chris Parsons787fb362021-10-14 18:43:51 -0400864 targetString := fmt.Sprintf("%s_%s", osString, archString)
Yu Liue4312402023-01-18 09:15:31 -0800865 if len(configTokens) > 2 {
866 targetString += "_" + configTokens[2]
867 if configTokens[2] == withinApexToString(true) {
868 withinApex = "True"
869 }
870 }
871 if len(configTokens) > 3 {
872 targetString += "_" + configTokens[3]
873 apexSdkVerString = configTokens[3]
874 }
Chris Parsons787fb362021-10-14 18:43:51 -0400875 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
876 labelsString := strings.Join(labels, ",\n ")
Yu Liue4312402023-01-18 09:15:31 -0800877 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, withinApex, apexSdkVerString,
878 labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400879 }
880
Jingwen Chen1e347862021-09-02 12:11:49 +0000881 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400882}
883
Chris Parsons944e7d02021-03-11 11:08:46 -0500884func indent(original string) string {
885 result := ""
886 for _, line := range strings.Split(original, "\n") {
887 result += " " + line + "\n"
888 }
889 return result
890}
891
Chris Parsons808d84c2021-03-09 20:43:32 -0500892// Returns the file contents of the buildroot.cquery file that should be used for the cquery
893// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800894// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500895// and grouped by their request type. The data retrieved for each label depends on its
896// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800897func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400898 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons38851d82023-03-15 00:19:32 -0400899 requestTypes := []cqueryRequest{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500900 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500901 cqueryId := getCqueryId(val)
902 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
Chris Parsons38851d82023-03-15 00:19:32 -0400903 if _, seenKey := requestTypeToCqueryIdEntries[val.requestType]; !seenKey {
904 requestTypes = append(requestTypes, val.requestType)
905 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500906 requestTypeToCqueryIdEntries[val.requestType] =
907 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
908 }
909 labelRegistrationMapSection := ""
910 functionDefSection := ""
911 mainSwitchSection := ""
912
913 mapDeclarationFormatString := `
914%s = {
915 %s
916}
917`
918 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800919def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500920%s
921`
922 mainSwitchSectionFormatString := `
923 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800924 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500925`
926
Chris Parsons38851d82023-03-15 00:19:32 -0400927 for _, requestType := range requestTypes {
Chris Parsons944e7d02021-03-11 11:08:46 -0500928 labelMapName := requestType.Name() + "_Labels"
929 functionName := requestType.Name() + "_Fn"
930 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
931 labelMapName,
932 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
933 functionDefSection += fmt.Sprintf(functionDefFormatString,
934 functionName,
935 indent(requestType.StarlarkFunctionBody()))
936 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
937 labelMapName, functionName)
938 }
939
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400940 formatString := `
941# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400942
Cole Faustb85d1a12022-11-08 18:14:01 -0800943{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500944
Cole Faustb85d1a12022-11-08 18:14:01 -0800945{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500946
947def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400948 # TODO(b/199363072): filegroups and file targets aren't associated with any
949 # specific platform architecture in mixed builds. This is consistent with how
950 # Soong treats filegroups, but it may not be the case with manually-written
951 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500952 buildoptions = build_options(target)
Yu Liue4312402023-01-18 09:15:31 -0800953
Jingwen Chen8f222742021-10-07 12:02:23 +0000954 if buildoptions == None:
955 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400956 # any specific platform architecture in mixed builds, so use the host.
957 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -0800958 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500959 if len(platforms) != 1:
960 # An individual configured target should have only one platform architecture.
961 # Note that it's fine for there to be multiple architectures for the same label,
962 # but each is its own configured target.
963 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -0800964 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -0500965 if platform_name == "host":
966 return "HOST"
Cole Faust319abae2023-06-06 15:12:49 -0700967 if not platform_name.startswith("mixed_builds_product-{TARGET_BUILD_VARIANT}"):
968 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))
969 platform_name = platform_name.removeprefix("mixed_builds_product-{TARGET_BUILD_VARIANT}").removeprefix("_")
Yu Liue4312402023-01-18 09:15:31 -0800970 config_key = ""
Cole Faustb85d1a12022-11-08 18:14:01 -0800971 if not platform_name:
Yu Liue4312402023-01-18 09:15:31 -0800972 config_key = "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400973 elif platform_name.startswith("android_"):
Yu Liue4312402023-01-18 09:15:31 -0800974 config_key = platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400975 elif platform_name.startswith("linux_"):
Yu Liue4312402023-01-18 09:15:31 -0800976 config_key = platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400977 else:
Cole Faust319abae2023-06-06 15:12:49 -0700978 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 -0500979
Yu Liue4312402023-01-18 09:15:31 -0800980 within_apex = buildoptions.get("//build/bazel/rules/apex:within_apex")
981 apex_sdk_version = buildoptions.get("//build/bazel/rules/apex:min_sdk_version")
982
983 if within_apex:
984 config_key += "|within_apex"
985 if apex_sdk_version != None and len(apex_sdk_version) > 0:
986 config_key += "|" + apex_sdk_version
987
988 return config_key
989
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400990def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500991 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500992
Chris Parsons86dc2c22022-09-28 14:58:41 -0400993 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
994 if id_string.startswith("//"):
995 id_string = "@" + id_string
996
Cole Faustb85d1a12022-11-08 18:14:01 -0800997 {MAIN_SWITCH_SECTION}
998
Chris Parsons944e7d02021-03-11 11:08:46 -0500999 # This target was not requested via cquery, and thus must be a dependency
1000 # of a requested target.
1001 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001002`
Cole Faustb85d1a12022-11-08 18:14:01 -08001003 replacer := strings.NewReplacer(
1004 "{TARGET_PRODUCT}", context.targetProduct,
1005 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
1006 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
1007 "{FUNCTION_DEF_SECTION}", functionDefSection,
1008 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001009
Cole Faustb85d1a12022-11-08 18:14:01 -08001010 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001011}
1012
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001013// Returns a path containing build-related metadata required for interfacing
1014// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001015func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001016 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -05001017}
1018
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001019// Returns the path where the contents of the @soong_injection repository live.
1020// It is used by Soong to tell Bazel things it cannot over the command line.
1021func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001022 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001023}
1024
1025// Returns the path of the synthetic Bazel workspace that contains a symlink
1026// forest composed the whole source tree and BUILD files generated by bp2build.
1027func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001028 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001029}
1030
Jingwen Chen8c523582021-06-01 11:19:53 +00001031// Returns the path to the top level out dir ($OUT_DIR).
1032func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001033 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +00001034}
1035
Sasha Smundak4975c822022-11-16 15:28:18 -08001036const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
1037
1038var (
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001039 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
1040 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
1041 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
1042 allBazelCommands = []bazelCommand{aqueryCmd, cqueryCmd, buildCmd}
Sasha Smundak4975c822022-11-16 15:28:18 -08001043)
1044
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001045// Issues commands to Bazel to receive results for all cquery requests
1046// queued in the BazelContext.
Liz Kammer690fbac2023-02-10 11:11:17 -05001047func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx invokeBazelContext) error {
1048 eventHandler := ctx.GetEventHandler()
1049 eventHandler.Begin("bazel")
1050 defer eventHandler.End("bazel")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001051
Sasha Smundak4975c822022-11-16 15:28:18 -08001052 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
1053 if err := os.MkdirAll(metricsDir, 0777); err != nil {
1054 return err
1055 }
1056 }
1057 context.results = make(map[cqueryKey]string)
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001058 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001059 return err
1060 }
1061 if err := context.runAquery(config, ctx); err != nil {
1062 return err
1063 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001064 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001065 return err
1066 }
1067
1068 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001069 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -08001070 return nil
1071}
1072
Liz Kammer690fbac2023-02-10 11:11:17 -05001073func (context *mixedBuildBazelContext) runCquery(config Config, ctx invokeBazelContext) error {
1074 eventHandler := ctx.GetEventHandler()
1075 eventHandler.Begin("cquery")
1076 defer eventHandler.End("cquery")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001077 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +02001078 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
1079 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
1080 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -05001081 if err != nil {
1082 return err
1083 }
1084 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001085 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001086 return err
1087 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001088 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001089 return err
1090 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001091 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001092 return err
1093 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001094 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001095 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001096 return err
1097 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001098
Yu Liue4312402023-01-18 09:15:31 -08001099 extraFlags := []string{"--output=starlark", "--starlark:file=" + absolutePath(cqueryFileRelpath)}
1100 if Bool(config.productVariables.ClangCoverage) {
1101 extraFlags = append(extraFlags, "--collect_code_coverage")
1102 }
1103
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001104 cqueryCmdRequest := context.createBazelCommand(config, bazel.CqueryBuildRootRunName, cqueryCmd, extraFlags...)
1105 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCmdRequest, context.paths, eventHandler)
Wei Licbd181c2022-11-16 08:59:23 -08001106 if cqueryErr != nil {
1107 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001108 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001109 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", context.printableCqueryCommand(cqueryCmdRequest))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001110 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001111 return err
1112 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001113 cqueryResults := map[string]string{}
1114 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1115 if strings.Contains(outputLine, ">>") {
1116 splitLine := strings.SplitN(outputLine, ">>", 2)
1117 cqueryResults[splitLine[0]] = splitLine[1]
1118 }
1119 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001120 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001121 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001122 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001123 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001124 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001125 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001126 }
1127 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001128 return nil
1129}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001130
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001131func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1132 oldContents, err := os.ReadFile(path)
1133 if err != nil || !bytes.Equal(contents, oldContents) {
1134 err = os.WriteFile(path, contents, perm)
1135 }
1136 return nil
1137}
1138
Liz Kammer690fbac2023-02-10 11:11:17 -05001139func (context *mixedBuildBazelContext) runAquery(config Config, ctx invokeBazelContext) error {
1140 eventHandler := ctx.GetEventHandler()
1141 eventHandler.Begin("aquery")
1142 defer eventHandler.End("aquery")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001143 // Issue an aquery command to retrieve action information about the bazel build tree.
1144 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001145 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1146 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001147 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001148 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001149 extraFlags = append(extraFlags, "--collect_code_coverage")
1150 paths := make([]string, 0, 2)
1151 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001152 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001153 // TODO(b/259404593) convert path wildcard to regex values
1154 if p[i] == "*" {
1155 p[i] = ".*"
1156 }
1157 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001158 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1159 }
1160 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1161 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1162 }
1163 if len(paths) > 0 {
1164 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001165 }
1166 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001167 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.AqueryBuildRootRunName, aqueryCmd,
1168 extraFlags...), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001169 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001170 return err
1171 }
Liz Kammer690fbac2023-02-10 11:11:17 -05001172 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001173 return err
1174}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001175
Liz Kammer690fbac2023-02-10 11:11:17 -05001176func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx invokeBazelContext) error {
1177 eventHandler := ctx.GetEventHandler()
1178 eventHandler.Begin("symlinks")
1179 defer eventHandler.End("symlinks")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001180 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1181 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1182 // but some of symlinks may be required to resolve source dependencies of the build.
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001183 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.BazelBuildPhonyRootRunName, buildCmd), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001184 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001185}
Chris Parsonsa798d962020-10-12 23:44:08 -04001186
Liz Kammera4655a92023-02-10 17:17:28 -05001187func (context *mixedBuildBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001188 return context.buildStatements
1189}
1190
Sasha Smundak39a301c2022-12-29 17:11:49 -08001191func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001192 return context.depsets
1193}
1194
Sasha Smundak39a301c2022-12-29 17:11:49 -08001195func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001196 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001197}
1198
Chris Parsonsa798d962020-10-12 23:44:08 -04001199// Singleton used for registering BUILD file ninja dependencies (needed
1200// for correctness of builds which use Bazel.
1201func BazelSingleton() Singleton {
1202 return &bazelSingleton{}
1203}
1204
1205type bazelSingleton struct{}
1206
1207func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001208 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001209 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001210 return
1211 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001212
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001213 // Add ninja file dependencies for files which all bazel invocations require.
1214 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001215 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001216 ctx.AddNinjaFileDeps(bazelBuildList)
1217
Sasha Smundak0e87b182022-12-01 11:46:11 -08001218 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001219 if err != nil {
1220 ctx.Errorf(err.Error())
1221 }
1222 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1223 for _, file := range files {
1224 ctx.AddNinjaFileDeps(file)
1225 }
1226
Chris Parsons1a7aca02022-04-25 22:35:15 -04001227 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1228 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001229 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001230 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1231 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001232 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1233 }
1234 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001235 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1236 if artifactPath == "bazel-out/volatile-status.txt" {
1237 // See https://bazel.build/docs/user-manual#workspace-status
1238 orderOnlies = append(orderOnlies, pathInBazelOut)
1239 } else {
1240 outputs = append(outputs, pathInBazelOut)
1241 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001242 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001243 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001244 ctx.Build(pctx, BuildParams{
1245 Rule: blueprint.Phony,
1246 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1247 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001248 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001249 })
1250 }
1251
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001252 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1253 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001254 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Liz Kammera4655a92023-02-10 17:17:28 -05001255 // nil build statements are a valid case where we do not create an action because it is
1256 // unnecessary or handled by other processing
1257 if buildStatement == nil {
1258 continue
1259 }
Sasha Smundak1da064c2022-06-08 16:36:16 -07001260 if len(buildStatement.Command) > 0 {
1261 rule := NewRuleBuilder(pctx, ctx)
1262 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1263 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1264 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1265 continue
1266 }
1267 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1268 // and thus require special treatment. If BuildStatement were an interface implementing
1269 // buildRule(ctx) function, the code here would just call it.
1270 // Unfortunately, the BuildStatement is defined in
1271 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1272 // because this would cause circular dependency. So, until we move aquery processing
1273 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001274 switch buildStatement.Mnemonic {
1275 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001276 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1277 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001278 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001279 // build-runfiles arguments are the manifest file and the target directory
1280 // where it creates the symlink tree according to this manifest (and then
1281 // writes the MANIFEST file to it).
1282 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1283 outManifestPath := outManifest.String()
1284 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1285 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1286 }
1287 outDir := filepath.Dir(outManifestPath)
1288 ctx.Build(pctx, BuildParams{
1289 Rule: buildRunfilesRule,
1290 Output: outManifest,
1291 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1292 Description: "symlink tree for " + outDir,
1293 Args: map[string]string{
1294 "outDir": outDir,
1295 },
1296 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001297 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001298 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001299 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001300 }
1301}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001302
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001303// Register bazel-owned build statements (obtained from the aquery invocation).
Liz Kammera4655a92023-02-10 17:17:28 -05001304func createCommand(cmd *RuleBuilderCommand, buildStatement *bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001305 // executionRoot is the action cwd.
1306 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1307
1308 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1309 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001310 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001311 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001312 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001313 }
1314 cmd.Text("&&")
1315 }
1316
1317 for _, pair := range buildStatement.Env {
1318 // Set per-action env variables, if any.
1319 cmd.Flag(pair.Key + "=" + pair.Value)
1320 }
1321
1322 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001323 if len(buildStatement.Command) > 16*1024 {
1324 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1325 WriteFileRule(ctx, commandFile, buildStatement.Command)
1326
1327 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1328 } else {
1329 cmd.Text(buildStatement.Command)
1330 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001331
1332 for _, outputPath := range buildStatement.OutputPaths {
1333 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1334 }
1335 for _, inputPath := range buildStatement.InputPaths {
1336 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1337 }
1338 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1339 otherDepsetName := bazelDepsetName(inputDepsetHash)
1340 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1341 }
1342
1343 if depfile := buildStatement.Depfile; depfile != nil {
1344 // The paths in depfile are relative to `executionRoot`.
1345 // Hence, they need to be corrected by replacing "bazel-out"
1346 // with the full `bazelOutDir`.
1347 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1348 // would be deemed missing.
1349 // (Note: The regexp uses a capture group because the version of sed
1350 // does not support a look-behind pattern.)
1351 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1352 bazelOutDir, *depfile)
1353 cmd.Text(replacement)
1354 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1355 }
1356
1357 for _, symlinkPath := range buildStatement.SymlinkPaths {
1358 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1359 }
1360}
1361
Chris Parsons8d6e4332021-02-22 16:13:50 -05001362func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001363 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001364}
1365
Chris Parsons787fb362021-10-14 18:43:51 -04001366func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001367 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001368 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001369 if key.configKey.osType.Class == Device {
1370 // For the generic Android, the expected result is "target|android", which
1371 // corresponds to the product_variable_config named "android_target" in
1372 // build/bazel/platforms/BUILD.bazel.
1373 arch = "target"
1374 } else {
1375 // Use host platform, which is currently hardcoded to be x86_64.
1376 arch = "x86_64"
1377 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001378 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001379 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001380 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001381 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001382 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001383 }
Yu Liue4312402023-01-18 09:15:31 -08001384 keyString := arch + "|" + osName
1385 if key.configKey.apexKey.WithinApex {
1386 keyString += "|" + withinApexToString(key.configKey.apexKey.WithinApex)
1387 }
1388
1389 if len(key.configKey.apexKey.ApexSdkVersion) > 0 {
1390 keyString += "|" + key.configKey.apexKey.ApexSdkVersion
1391 }
1392
1393 return keyString
Chris Parsons787fb362021-10-14 18:43:51 -04001394}
1395
Chris Parsonsf874e462022-05-10 13:50:12 -04001396func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001397 return configKey{
1398 // use string because Arch is not a valid key in go
1399 arch: ctx.Arch().String(),
1400 osType: ctx.Os(),
1401 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001402}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001403
Yu Liue4312402023-01-18 09:15:31 -08001404func GetConfigKeyApexVariant(ctx BaseModuleContext, apexKey *ApexConfigKey) configKey {
1405 configKey := GetConfigKey(ctx)
1406
1407 if apexKey != nil {
1408 configKey.apexKey = ApexConfigKey{
1409 WithinApex: apexKey.WithinApex,
1410 ApexSdkVersion: apexKey.ApexSdkVersion,
1411 }
1412 }
1413
1414 return configKey
1415}
1416
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001417func bazelDepsetName(contentHash string) string {
1418 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001419}