blob: 2e818b1affb159dec8667a5ca496f3382c7f02e1 [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"
Sam Delmericocb3c52c2023-02-03 17:40:08 -050031 "android/soong/starlark_fmt"
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")
Sam Delmericocb3c52c2023-02-03 17:40:08 -050047 allowedBazelEnvironmentVars = []string{
Sam Delmerico700b4d32023-02-10 16:46:28 -050048 // clang-tidy
Sam Delmericocb3c52c2023-02-03 17:40:08 -050049 "ALLOW_LOCAL_TIDY_TRUE",
50 "DEFAULT_TIDY_HEADER_DIRS",
51 "TIDY_TIMEOUT",
52 "WITH_TIDY",
53 "WITH_TIDY_FLAGS",
Sam Delmerico700b4d32023-02-10 16:46:28 -050054 "TIDY_EXTERNAL_VENDOR",
55
Sam Delmericocb3c52c2023-02-03 17:40:08 -050056 "SKIP_ABI_CHECKS",
57 "UNSAFE_DISABLE_APEX_ALLOWED_DEPS_CHECK",
58 "AUTO_ZERO_INITIALIZE",
59 "AUTO_PATTERN_INITIALIZE",
60 "AUTO_UNINITIALIZE",
61 "USE_CCACHE",
62 "LLVM_NEXT",
Sam Delmerico0ffa1f32023-04-19 14:18:20 -040063 "LLVM_PREBUILTS_VERSION",
64 "LLVM_RELEASE_VERSION",
Sam Delmericocb3c52c2023-02-03 17:40:08 -050065 "ALLOW_UNKNOWN_WARNING_OPTION",
66
Zi Wanga4f7dae2023-04-17 20:07:26 -070067 "UNBUNDLED_BUILD_TARGET_SDK_WITH_API_FINGERPRINT",
68
Sam Delmericocb3c52c2023-02-03 17:40:08 -050069 // Overrides the version in the apex_manifest.json. The version is unique for
70 // each branch (internal, aosp, mainline releases, dessert releases). This
71 // enables modules built on an older branch to be installed against a newer
72 // device for development purposes.
73 "OVERRIDE_APEX_MANIFEST_DEFAULT_VERSION",
74 }
Sasha Smundak1da064c2022-06-08 16:36:16 -070075)
76
Liz Kammerc13f7852023-05-17 13:01:48 -040077func registerMixedBuildsMutator(ctx RegisterMutatorsContext) {
78 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
Chris Parsonsf874e462022-05-10 13:50:12 -040079}
80
81func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammerc13f7852023-05-17 13:01:48 -040082 ctx.FinalDepsMutators(registerMixedBuildsMutator)
Chris Parsonsf874e462022-05-10 13:50:12 -040083}
84
85func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
86 if m := ctx.Module(); m.Enabled() {
87 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
MarkDacekf47e1422023-04-19 16:47:36 +000088 mixedBuildEnabled := MixedBuildsEnabled(ctx)
89 queueMixedBuild := mixedBuildMod.IsMixedBuildSupported(ctx) && mixedBuildEnabled == MixedBuildEnabled
MarkDacek9c094ca2023-03-16 19:15:19 +000090 if queueMixedBuild {
Chris Parsonsf874e462022-05-10 13:50:12 -040091 mixedBuildMod.QueueBazelCall(ctx)
92 }
93 }
94 }
95}
96
Liz Kammerf29df7c2021-04-02 13:37:39 -040097type cqueryRequest interface {
98 // Name returns a string name for this request type. Such request type names must be unique,
99 // and must only consist of alphanumeric characters.
100 Name() string
101
102 // StarlarkFunctionBody returns a starlark function body to process this request type.
103 // The returned string is the body of a Starlark function which obtains
104 // all request-relevant information about a target and returns a string containing
105 // this information.
106 // The function should have the following properties:
Cole Faust97d15272022-11-22 14:08:59 -0800107 // - The arguments are `target` (a configured target) and `id_string` (the label + configuration).
Liz Kammerf29df7c2021-04-02 13:37:39 -0400108 // - The return value must be a string.
109 // - The function body should not be indented outside of its own scope.
110 StarlarkFunctionBody() string
111}
112
Chris Parsons787fb362021-10-14 18:43:51 -0400113// Portion of cquery map key to describe target configuration.
114type configKey struct {
Yu Liue4312402023-01-18 09:15:31 -0800115 arch string
116 osType OsType
117 apexKey ApexConfigKey
118}
119
120type ApexConfigKey struct {
121 WithinApex bool
122 ApexSdkVersion string
123}
124
125func (c ApexConfigKey) String() string {
126 return fmt.Sprintf("%s_%s", withinApexToString(c.WithinApex), c.ApexSdkVersion)
127}
128
129func withinApexToString(withinApex bool) string {
130 if withinApex {
131 return "within_apex"
132 }
133 return ""
Chris Parsons787fb362021-10-14 18:43:51 -0400134}
135
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700136func (c configKey) String() string {
Yu Liue4312402023-01-18 09:15:31 -0800137 return fmt.Sprintf("%s::%s::%s", c.arch, c.osType, c.apexKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700138}
139
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400140// Map key to describe bazel cquery requests.
141type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400142 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400143 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400144 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400145}
146
Chris Parsons86dc2c22022-09-28 14:58:41 -0400147func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
148 if strings.HasPrefix(label, "//") {
149 // Normalize Bazel labels to specify main repository explicitly.
150 label = "@" + label
151 }
152 return cqueryKey{label, cqueryRequest, cfgKey}
153}
154
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700155func (c cqueryKey) String() string {
156 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700157}
158
Liz Kammer690fbac2023-02-10 11:11:17 -0500159type invokeBazelContext interface {
160 GetEventHandler() *metrics.EventHandler
161}
162
Chris Parsonsf874e462022-05-10 13:50:12 -0400163// BazelContext is a context object useful for interacting with Bazel during
164// the course of a build. Use of Bazel to evaluate part of the build graph
165// is referred to as a "mixed build". (Some modules are managed by Soong,
166// some are managed by Bazel). To facilitate interop between these build
167// subgraphs, Soong may make requests to Bazel and evaluate their responses
168// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400169type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400170 // Add a cquery request to the bazel request queue. All queued requests
171 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
172 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
173
174 // ** Cquery Results Retrieval Functions
175 // The below functions pertain to retrieving cquery results from a prior
176 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400177
178 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400179 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500180
Chris Parsons944e7d02021-03-11 11:08:46 -0500181 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400182 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400183
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700184 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400185 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700186
Sasha Smundakedd16662022-10-07 14:44:50 -0700187 // Returns the results of the GetCcUnstrippedInfo query
188 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
189
Spandan Dasbd156812023-06-05 22:43:13 +0000190 // Returns the results of the GetPrebuiltFileInfo query
191 GetPrebuiltFileInfo(label string, cfgKey configKey) (cquery.PrebuiltFileInfo, error)
192
Chris Parsonsf874e462022-05-10 13:50:12 -0400193 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400194
195 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800196 // queued in the BazelContext. The ctx argument is optional and is only
197 // used for performance data collection
Liz Kammer690fbac2023-02-10 11:11:17 -0500198 InvokeBazel(config Config, ctx invokeBazelContext) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400199
Chris Parsonsad876012022-08-20 14:48:32 -0400200 // Returns true if Bazel handling is enabled for the module with the given name.
201 // Note that this only implies "bazel mixed build" allowlisting. The caller
202 // should independently verify the module is eligible for Bazel handling
203 // (for example, that it is MixedBuildBuildable).
Yu Liue4312402023-01-18 09:15:31 -0800204 IsModuleNameAllowed(moduleName string, withinApex bool) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500205
Yu Liubfb23622023-02-22 10:42:15 -0800206 IsModuleDclaAllowed(moduleName string) bool
207
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500208 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
209 OutputBase() string
210
211 // Returns build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500212 BuildStatementsToRegister() []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400213
214 // Returns the depsets defined in Bazel's aquery response.
215 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400216}
217
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400218type bazelRunner interface {
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000219 issueBazelCommand(cmdRequest bazel.CmdRequest, paths *bazelPaths, eventHandler *metrics.EventHandler) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400220}
221
222type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000223 homeDir string
224 bazelPath string
225 outputBase string
226 workspaceDir string
227 soongOutDir string
228 metricsDir string
229 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400230}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400231
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400232// A context object which tracks queued requests that need to be made to Bazel,
233// and their results after the requests have been made.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800234type mixedBuildBazelContext struct {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400235 bazelRunner
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500236 paths *bazelPaths
237 // cquery requests that have not yet been issued to Bazel. This list is maintained
238 // in a sorted state, and is guaranteed to have no duplicates.
239 requests []cqueryKey
240 requestMutex sync.Mutex // requests can be written in parallel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400241
242 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500243
244 // Build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500245 buildStatements []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400246
247 // Depsets which should be used for Bazel's build statements.
248 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400249
250 // Per-module allowlist/denylist functionality to control whether analysis of
251 // modules are handled by Bazel. For modules which do not have a Bazel definition
252 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
253 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
254 // Per-module denylist to opt modules out of bazel handling.
255 bazelDisabledModules map[string]bool
256 // Per-module allowlist to opt modules in to bazel handling.
257 bazelEnabledModules map[string]bool
Yu Liue4312402023-01-18 09:15:31 -0800258 // DCLA modules are enabled when used in apex.
259 bazelDclaEnabledModules map[string]bool
Cole Faustb85d1a12022-11-08 18:14:01 -0800260
261 targetProduct string
262 targetBuildVariant string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400263}
264
Sasha Smundak39a301c2022-12-29 17:11:49 -0800265var _ BazelContext = &mixedBuildBazelContext{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400266
267// A bazel context to use when Bazel is disabled.
268type noopBazelContext struct{}
269
270var _ BazelContext = noopBazelContext{}
271
272// A bazel context to use for tests.
273type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400274 OutputBaseDir string
275
Spandan Dasbd156812023-06-05 22:43:13 +0000276 LabelToOutputFiles map[string][]string
277 LabelToCcInfo map[string]cquery.CcInfo
278 LabelToPythonBinary map[string]string
279 LabelToApexInfo map[string]cquery.ApexInfo
280 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
281 LabelToPrebuiltFileInfo map[string]cquery.PrebuiltFileInfo
Yu Liue4312402023-01-18 09:15:31 -0800282
283 BazelRequests map[string]bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400284}
285
Yu Liue4312402023-01-18 09:15:31 -0800286func (m MockBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
287 key := BuildMockBazelContextRequestKey(label, requestType, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
288 if m.BazelRequests == nil {
289 m.BazelRequests = make(map[string]bool)
290 }
291 m.BazelRequests[key] = true
Chris Parsons8d6e4332021-02-22 16:13:50 -0500292}
293
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700294func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500295 result, ok := m.LabelToOutputFiles[label]
296 if !ok {
297 return []string{}, fmt.Errorf("no target with label %q in LabelToOutputFiles", label)
298 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400299 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400300}
301
Yu Liue4312402023-01-18 09:15:31 -0800302func (m MockBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500303 result, ok := m.LabelToCcInfo[label]
304 if !ok {
Yu Liue4312402023-01-18 09:15:31 -0800305 key := BuildMockBazelContextResultKey(label, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
306 result, ok = m.LabelToCcInfo[key]
307 if !ok {
308 return cquery.CcInfo{}, fmt.Errorf("no target with label %q in LabelToCcInfo", label)
309 }
Sam Delmericoce39f832023-01-23 14:04:24 -0500310 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400311 return result, nil
312}
313
Liz Kammerbe6a7122022-11-04 16:05:11 -0400314func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500315 result, ok := m.LabelToApexInfo[label]
316 if !ok {
317 return cquery.ApexInfo{}, fmt.Errorf("no target with label %q in LabelToApexInfo", label)
318 }
Liz Kammer0e255ef2022-11-04 16:07:04 -0400319 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700320}
321
Sasha Smundakedd16662022-10-07 14:44:50 -0700322func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500323 result, ok := m.LabelToCcBinary[label]
324 if !ok {
325 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no target with label %q in LabelToCcBinary", label)
326 }
Sasha Smundakedd16662022-10-07 14:44:50 -0700327 return result, nil
328}
329
Spandan Dasbd156812023-06-05 22:43:13 +0000330func (m MockBazelContext) GetPrebuiltFileInfo(label string, _ configKey) (cquery.PrebuiltFileInfo, error) {
331 result, ok := m.LabelToPrebuiltFileInfo[label]
332 if !ok {
333 return cquery.PrebuiltFileInfo{}, fmt.Errorf("no target with label %q in LabelToPrebuiltFileInfo", label)
334 }
335 return result, nil
336}
337
Liz Kammer690fbac2023-02-10 11:11:17 -0500338func (m MockBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400339 panic("unimplemented")
340}
341
Yu Liue4312402023-01-18 09:15:31 -0800342func (m MockBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400343 return true
344}
345
Yu Liubfb23622023-02-22 10:42:15 -0800346func (m MockBazelContext) IsModuleDclaAllowed(_ string) bool {
347 return true
348}
349
Liz Kammera92e8442021-04-07 20:25:21 -0400350func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500351
Liz Kammera4655a92023-02-10 17:17:28 -0500352func (m MockBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
353 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500354}
355
Chris Parsons1a7aca02022-04-25 22:35:15 -0400356func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
357 return []bazel.AqueryDepset{}
358}
359
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400360var _ BazelContext = MockBazelContext{}
361
Yu Liue4312402023-01-18 09:15:31 -0800362func BuildMockBazelContextRequestKey(label string, request cqueryRequest, arch string, osType OsType, apexKey ApexConfigKey) string {
363 cfgKey := configKey{
364 arch: arch,
365 osType: osType,
366 apexKey: apexKey,
367 }
368
369 return strings.Join([]string{label, request.Name(), cfgKey.String()}, "_")
370}
371
372func BuildMockBazelContextResultKey(label string, arch string, osType OsType, apexKey ApexConfigKey) string {
373 cfgKey := configKey{
374 arch: arch,
375 osType: osType,
376 apexKey: apexKey,
377 }
378
379 return strings.Join([]string{label, cfgKey.String()}, "_")
380}
381
Sasha Smundak39a301c2022-12-29 17:11:49 -0800382func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400383 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400384 bazelCtx.requestMutex.Lock()
385 defer bazelCtx.requestMutex.Unlock()
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500386
387 // Insert key into requests, maintaining the sort, and only if it's not duplicate.
388 keyString := key.String()
389 foundEqual := false
390 notLessThanKeyString := func(i int) bool {
391 s := bazelCtx.requests[i].String()
392 v := strings.Compare(s, keyString)
393 if v == 0 {
394 foundEqual = true
395 }
396 return v >= 0
397 }
398 targetIndex := sort.Search(len(bazelCtx.requests), notLessThanKeyString)
399 if foundEqual {
400 return
401 }
402
403 if targetIndex == len(bazelCtx.requests) {
404 bazelCtx.requests = append(bazelCtx.requests, key)
405 } else {
406 bazelCtx.requests = append(bazelCtx.requests[:targetIndex+1], bazelCtx.requests[targetIndex:]...)
407 bazelCtx.requests[targetIndex] = key
408 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400409}
410
Sasha Smundak39a301c2022-12-29 17:11:49 -0800411func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400412 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400413 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500414 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400415
Chris Parsonsf874e462022-05-10 13:50:12 -0400416 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400417 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400418 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400419}
420
Sasha Smundak39a301c2022-12-29 17:11:49 -0800421func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400422 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400423 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000424 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400425 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000426 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400427 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 +0000428}
429
Sasha Smundak39a301c2022-12-29 17:11:49 -0800430func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400431 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700432 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500433 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700434 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400435 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700436}
437
Sasha Smundak39a301c2022-12-29 17:11:49 -0800438func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700439 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
440 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500441 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700442 }
443 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
444}
445
Spandan Dasbd156812023-06-05 22:43:13 +0000446func (bazelCtx *mixedBuildBazelContext) GetPrebuiltFileInfo(label string, cfgKey configKey) (cquery.PrebuiltFileInfo, error) {
447 key := makeCqueryKey(label, cquery.GetPrebuiltFileInfo, cfgKey)
448 if rawString, ok := bazelCtx.results[key]; ok {
449 return cquery.GetPrebuiltFileInfo.ParseResult(strings.TrimSpace(rawString))
450 }
451 return cquery.PrebuiltFileInfo{}, fmt.Errorf("no bazel response for %s", key)
452}
453
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700454func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500455 panic("unimplemented")
456}
457
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700458func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500459 panic("unimplemented")
460}
461
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700462func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400463 panic("unimplemented")
464}
465
Liz Kammerbe6a7122022-11-04 16:05:11 -0400466func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700467 panic("unimplemented")
468}
469
Sasha Smundakedd16662022-10-07 14:44:50 -0700470func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
471 //TODO implement me
472 panic("implement me")
473}
474
Spandan Dasbd156812023-06-05 22:43:13 +0000475func (n noopBazelContext) GetPrebuiltFileInfo(_ string, _ configKey) (cquery.PrebuiltFileInfo, error) {
476 panic("implement me")
477}
478
Liz Kammer690fbac2023-02-10 11:11:17 -0500479func (n noopBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400480 panic("unimplemented")
481}
482
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500483func (m noopBazelContext) OutputBase() string {
484 return ""
485}
486
Yu Liue4312402023-01-18 09:15:31 -0800487func (n noopBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400488 return false
489}
490
Yu Liubfb23622023-02-22 10:42:15 -0800491func (n noopBazelContext) IsModuleDclaAllowed(_ string) bool {
492 return false
493}
494
Liz Kammera4655a92023-02-10 17:17:28 -0500495func (m noopBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
496 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500497}
498
Chris Parsons1a7aca02022-04-25 22:35:15 -0400499func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
500 return []bazel.AqueryDepset{}
501}
502
Yu Liu6a7940c2023-05-09 17:12:22 -0700503func AddToStringSet(set map[string]bool, items []string) {
Yu Liue4312402023-01-18 09:15:31 -0800504 for _, item := range items {
505 set[item] = true
506 }
507}
508
Cole Faust705968d2022-12-14 11:32:05 -0800509func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400510 disabledModules := map[string]bool{}
511 enabledModules := map[string]bool{}
512
Cole Faust705968d2022-12-14 11:32:05 -0800513 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400514 case BazelProdMode:
Yu Liu6a7940c2023-05-09 17:12:22 -0700515 AddToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800516 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000517 enabledModules[enabledAdHocModule] = true
518 }
MarkDacekb78465d2022-10-18 20:10:16 +0000519 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400520 // Staging mode includes all prod modules plus all staging modules.
Yu Liu6a7940c2023-05-09 17:12:22 -0700521 AddToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
522 AddToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800523 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000524 enabledModules[enabledAdHocModule] = true
525 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400526 default:
Chris Parsons21f80272023-06-15 04:02:28 +0000527 panic("Expected BazelProdMode or BazelStagingMode")
Cole Faust705968d2022-12-14 11:32:05 -0800528 }
529 return enabledModules, disabledModules
530}
531
532func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
533 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
534 enabledList := make([]string, 0, len(enabledModules))
535 for module := range enabledModules {
536 if !disabledModules[module] {
537 enabledList = append(enabledList, module)
538 }
539 }
540 sort.Strings(enabledList)
541 return enabledList
542}
543
544func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsons21f80272023-06-15 04:02:28 +0000545 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400546 return noopBazelContext{}, nil
547 }
548
Cole Faust705968d2022-12-14 11:32:05 -0800549 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
550
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800551 paths := bazelPaths{
552 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400553 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800554 var missing []string
555 vars := []struct {
556 name string
557 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000558
559 // True if the environment variable needs to be tracked so that changes to the variable
560 // cause the ninja file to be regenerated, false otherwise. False should only be set for
561 // environment variables that have no effect on the generated ninja file.
562 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800563 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000564 {"BAZEL_HOME", &paths.homeDir, true},
565 {"BAZEL_PATH", &paths.bazelPath, true},
566 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
567 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
568 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
569 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800570 }
571 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000572 if v.track {
573 if s := c.Getenv(v.name); len(s) > 1 {
574 *v.ptr = s
575 continue
576 }
577 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800578 *v.ptr = s
579 } else {
580 missing = append(missing, v.name)
581 }
582 }
583 if len(missing) > 0 {
584 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
585 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800586
587 targetBuildVariant := "user"
588 if c.Eng() {
589 targetBuildVariant = "eng"
590 } else if c.Debuggable() {
591 targetBuildVariant = "userdebug"
592 }
593 targetProduct := "unknown"
594 if c.HasDeviceProduct() {
595 targetProduct = c.DeviceProduct()
596 }
Yu Liue4312402023-01-18 09:15:31 -0800597 dclaMixedBuildsEnabledList := []string{}
598 if c.BuildMode == BazelProdMode {
599 dclaMixedBuildsEnabledList = allowlists.ProdDclaMixedBuildsEnabledList
600 } else if c.BuildMode == BazelStagingMode {
601 dclaMixedBuildsEnabledList = append(allowlists.ProdDclaMixedBuildsEnabledList,
602 allowlists.StagingDclaMixedBuildsEnabledList...)
603 }
604 dclaEnabledModules := map[string]bool{}
Yu Liu6a7940c2023-05-09 17:12:22 -0700605 AddToStringSet(dclaEnabledModules, dclaMixedBuildsEnabledList)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800606 return &mixedBuildBazelContext{
Chris Parsons9402ca82023-02-23 17:28:06 -0500607 bazelRunner: &builtinBazelRunner{c.UseBazelProxy, absolutePath(c.outDir)},
Yu Liue4312402023-01-18 09:15:31 -0800608 paths: &paths,
Yu Liue4312402023-01-18 09:15:31 -0800609 bazelEnabledModules: enabledModules,
610 bazelDisabledModules: disabledModules,
611 bazelDclaEnabledModules: dclaEnabledModules,
612 targetProduct: targetProduct,
613 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400614 }, nil
615}
616
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400617func (p *bazelPaths) BazelMetricsDir() string {
618 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000619}
620
Yu Liue4312402023-01-18 09:15:31 -0800621func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string, withinApex bool) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400622 if context.bazelDisabledModules[moduleName] {
623 return false
624 }
625 if context.bazelEnabledModules[moduleName] {
626 return true
627 }
Yu Liubfb23622023-02-22 10:42:15 -0800628 if withinApex && context.IsModuleDclaAllowed(moduleName) {
Yu Liue4312402023-01-18 09:15:31 -0800629 return true
630 }
631
Chris Parsons21f80272023-06-15 04:02:28 +0000632 return false
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400633}
634
Yu Liubfb23622023-02-22 10:42:15 -0800635func (context *mixedBuildBazelContext) IsModuleDclaAllowed(moduleName string) bool {
636 return context.bazelDclaEnabledModules[moduleName]
637}
638
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400639func pwdPrefix() string {
640 // Darwin doesn't have /proc
641 if runtime.GOOS != "darwin" {
642 return "PWD=/proc/self/cwd"
643 }
644 return ""
645}
646
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400647type bazelCommand struct {
648 command string
649 // query or label
650 expression string
651}
652
Chris Parsons9402ca82023-02-23 17:28:06 -0500653type builtinBazelRunner struct {
654 useBazelProxy bool
655 outDir string
656}
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400657
Chris Parsons808d84c2021-03-09 20:43:32 -0500658// Issues the given bazel command with given build label and additional flags.
659// Returns (stdout, stderr, error). The first and second return values are strings
660// containing the stdout and stderr of the run command, and an error is returned if
661// the invocation returned an error code.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000662func (r *builtinBazelRunner) issueBazelCommand(cmdRequest bazel.CmdRequest, paths *bazelPaths, eventHandler *metrics.EventHandler) (string, string, error) {
Chris Parsons9402ca82023-02-23 17:28:06 -0500663 if r.useBazelProxy {
664 eventHandler.Begin("client_proxy")
665 defer eventHandler.End("client_proxy")
666 proxyClient := bazel.NewProxyClient(r.outDir)
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000667 resp, err := proxyClient.IssueCommand(cmdRequest)
Chris Parsons9402ca82023-02-23 17:28:06 -0500668
669 if err != nil {
670 return "", "", err
671 }
672 if len(resp.ErrorString) > 0 {
673 return "", "", fmt.Errorf(resp.ErrorString)
674 }
675 return resp.Stdout, resp.Stderr, nil
Jason Wu52cd1942022-09-08 15:37:57 +0000676 } else {
Chris Parsons9402ca82023-02-23 17:28:06 -0500677 eventHandler.Begin("bazel command")
678 defer eventHandler.End("bazel command")
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000679
680 stdout, stderr, err := bazel.ExecBazel(paths.bazelPath, absolutePath(paths.syntheticWorkspaceDir()), cmdRequest)
681 return string(stdout), string(stderr), err
Jason Wu52cd1942022-09-08 15:37:57 +0000682 }
683}
684
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000685func (context *mixedBuildBazelContext) createBazelCommand(config Config, runName bazel.RunName, command bazelCommand,
686 extraFlags ...string) bazel.CmdRequest {
Cole Faust319abae2023-06-06 15:12:49 -0700687 if runtime.GOOS != "linux" && runtime.GOOS != "darwin" {
688 panic("Unknown GOOS: " + runtime.GOOS)
689 }
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000690 cmdFlags := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000691 "--output_base=" + absolutePath(context.paths.outputBase),
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000692 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700693 command.expression,
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000694 "--profile=" + shared.BazelMetricsFilename(context.paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400695
Cole Faust319abae2023-06-06 15:12:49 -0700696 "--host_platform=@soong_injection//product_config_platforms:mixed_builds_product-" + context.targetBuildVariant + "_" + runtime.GOOS + "_x86_64",
697 // Don't specify --platforms, because on some products/branches (like kernel-build-tools)
698 // the main platform for mixed_builds_product-variant doesn't exist because an arch isn't
699 // specified in product config. The derivative platforms that config_node transitions into
700 // will still work.
Jingwen Chen583ab212023-05-30 09:45:23 +0000701
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700702 // Suppress noise
703 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500704 "--noshow_progress",
705 "--norun_validations",
706 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400707 cmdFlags = append(cmdFlags, extraFlags...)
708
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700709 extraEnv := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000710 "HOME=" + context.paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200711 pwdPrefix(),
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000712 "BUILD_DIR=" + absolutePath(context.paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700713 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000714 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000715 "OUT_DIR=" + absolutePath(context.paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500716 // Disables local host detection of gcc; toolchain information is defined
717 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700718 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
719 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500720 for _, envvar := range allowedBazelEnvironmentVars {
721 val := config.Getenv(envvar)
722 if val == "" {
723 continue
724 }
725 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
726 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000727 envVars := append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400728
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000729 return bazel.CmdRequest{cmdFlags, envVars}
Jason Wu52cd1942022-09-08 15:37:57 +0000730}
731
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000732func (context *mixedBuildBazelContext) printableCqueryCommand(bazelCmd bazel.CmdRequest) string {
733 args := append([]string{context.paths.bazelPath}, bazelCmd.Argv...)
734 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(args, "\" \"") + "\""
Jason Wu52cd1942022-09-08 15:37:57 +0000735 return outputString
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400736}
737
Sasha Smundak39a301c2022-12-29 17:11:49 -0800738func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500739 // TODO(cparsons): Define configuration transitions programmatically based
740 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400741 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500742#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400743# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500744#####################################################
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400745def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800746 if attr.os == "android" and attr.arch == "target":
Cole Faust319abae2023-06-06 15:12:49 -0700747 target = "mixed_builds_product-{VARIANT}"
Cole Faustb85d1a12022-11-08 18:14:01 -0800748 else:
Cole Faust319abae2023-06-06 15:12:49 -0700749 target = "mixed_builds_product-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Yu Liue4312402023-01-18 09:15:31 -0800750 apex_name = ""
751 if attr.within_apex:
752 # //build/bazel/rules/apex:apex_name has to be set to a non_empty value,
753 # otherwise //build/bazel/rules/apex:non_apex will be true and the
754 # "-D__ANDROID_APEX__" compiler flag will be missing. Apex_name is used
755 # in some validation on bazel side which don't really apply in mixed
756 # build because soong will do the work, so we just set it to a fixed
757 # value here.
758 apex_name = "dcla_apex"
759 outputs = {
Jingwen Chen583ab212023-05-30 09:45:23 +0000760 "//command_line_option:platforms": "@soong_injection//product_config_platforms:%s" % target,
Yu Liue4312402023-01-18 09:15:31 -0800761 "@//build/bazel/rules/apex:within_apex": attr.within_apex,
762 "@//build/bazel/rules/apex:min_sdk_version": attr.apex_sdk_version,
763 "@//build/bazel/rules/apex:apex_name": apex_name,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500764 }
765
Yu Liue4312402023-01-18 09:15:31 -0800766 return outputs
767
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400768_config_node_transition = transition(
769 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500770 inputs = [],
771 outputs = [
772 "//command_line_option:platforms",
Yu Liue4312402023-01-18 09:15:31 -0800773 "@//build/bazel/rules/apex:within_apex",
774 "@//build/bazel/rules/apex:min_sdk_version",
775 "@//build/bazel/rules/apex:apex_name",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500776 ],
777)
778
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400779def _passthrough_rule_impl(ctx):
780 return [DefaultInfo(files = depset(ctx.files.deps))]
781
782config_node = rule(
783 implementation = _passthrough_rule_impl,
784 attrs = {
Yu Liue4312402023-01-18 09:15:31 -0800785 "arch" : attr.string(mandatory = True),
786 "os" : attr.string(mandatory = True),
787 "within_apex" : attr.bool(default = False),
788 "apex_sdk_version" : attr.string(mandatory = True),
789 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400790 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
791 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500792)
793
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400794
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500795# Rule representing the root of the build, to depend on all Bazel targets that
796# are required for the build. Building this target will build the entire Bazel
797# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400798mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400799 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500800 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400801 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500802 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400803)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500804
805def _phony_root_impl(ctx):
806 return []
807
808# Rule to depend on other targets but build nothing.
809# This is useful as follows: building a target of this rule will generate
810# symlink forests for all dependencies of the target, without executing any
811# actions of the build.
812phony_root = rule(
813 implementation = _phony_root_impl,
814 attrs = {"deps" : attr.label_list()},
815)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400816`
Cole Faustb85d1a12022-11-08 18:14:01 -0800817
818 productReplacer := strings.NewReplacer(
819 "{PRODUCT}", context.targetProduct,
820 "{VARIANT}", context.targetBuildVariant)
821
822 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400823}
824
Sasha Smundak39a301c2022-12-29 17:11:49 -0800825func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500826 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
827 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400828 formatString := `
829# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400830load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
831
832%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400833
834mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400835 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000836 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400837)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500838
839phony_root(name = "phonyroot",
840 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000841 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500842)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400843`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400844 configNodeFormatString := `
845config_node(name = "%s",
846 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400847 os = "%s",
Yu Liue4312402023-01-18 09:15:31 -0800848 within_apex = %s,
849 apex_sdk_version = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400850 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000851 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400852)
853`
854
855 configNodesSection := ""
856
Chris Parsons787fb362021-10-14 18:43:51 -0400857 labelsByConfig := map[string][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500858
859 for _, val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200860 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400861 configString := getConfigString(val)
862 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400863 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400864
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500865 // Configs need to be sorted to maintain determinism of the BUILD file.
866 sortedConfigs := make([]string, 0, len(labelsByConfig))
867 for val := range labelsByConfig {
868 sortedConfigs = append(sortedConfigs, val)
869 }
870 sort.Slice(sortedConfigs, func(i, j int) bool { return sortedConfigs[i] < sortedConfigs[j] })
871
Jingwen Chen1e347862021-09-02 12:11:49 +0000872 allLabels := []string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500873 for _, configString := range sortedConfigs {
874 labels := labelsByConfig[configString]
Chris Parsons787fb362021-10-14 18:43:51 -0400875 configTokens := strings.Split(configString, "|")
Yu Liue4312402023-01-18 09:15:31 -0800876 if len(configTokens) < 2 {
Chris Parsons787fb362021-10-14 18:43:51 -0400877 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000878 }
Chris Parsons787fb362021-10-14 18:43:51 -0400879 archString := configTokens[0]
880 osString := configTokens[1]
Yu Liue4312402023-01-18 09:15:31 -0800881 withinApex := "False"
882 apexSdkVerString := ""
Chris Parsons787fb362021-10-14 18:43:51 -0400883 targetString := fmt.Sprintf("%s_%s", osString, archString)
Yu Liue4312402023-01-18 09:15:31 -0800884 if len(configTokens) > 2 {
885 targetString += "_" + configTokens[2]
886 if configTokens[2] == withinApexToString(true) {
887 withinApex = "True"
888 }
889 }
890 if len(configTokens) > 3 {
891 targetString += "_" + configTokens[3]
892 apexSdkVerString = configTokens[3]
893 }
Chris Parsons787fb362021-10-14 18:43:51 -0400894 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
895 labelsString := strings.Join(labels, ",\n ")
Yu Liue4312402023-01-18 09:15:31 -0800896 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, withinApex, apexSdkVerString,
897 labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400898 }
899
Jingwen Chen1e347862021-09-02 12:11:49 +0000900 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400901}
902
Chris Parsons944e7d02021-03-11 11:08:46 -0500903func indent(original string) string {
904 result := ""
905 for _, line := range strings.Split(original, "\n") {
906 result += " " + line + "\n"
907 }
908 return result
909}
910
Chris Parsons808d84c2021-03-09 20:43:32 -0500911// Returns the file contents of the buildroot.cquery file that should be used for the cquery
912// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800913// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500914// and grouped by their request type. The data retrieved for each label depends on its
915// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800916func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400917 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons38851d82023-03-15 00:19:32 -0400918 requestTypes := []cqueryRequest{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500919 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500920 cqueryId := getCqueryId(val)
921 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
Chris Parsons38851d82023-03-15 00:19:32 -0400922 if _, seenKey := requestTypeToCqueryIdEntries[val.requestType]; !seenKey {
923 requestTypes = append(requestTypes, val.requestType)
924 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500925 requestTypeToCqueryIdEntries[val.requestType] =
926 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
927 }
928 labelRegistrationMapSection := ""
929 functionDefSection := ""
930 mainSwitchSection := ""
931
932 mapDeclarationFormatString := `
933%s = {
934 %s
935}
936`
937 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800938def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500939%s
940`
941 mainSwitchSectionFormatString := `
942 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800943 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500944`
945
Chris Parsons38851d82023-03-15 00:19:32 -0400946 for _, requestType := range requestTypes {
Chris Parsons944e7d02021-03-11 11:08:46 -0500947 labelMapName := requestType.Name() + "_Labels"
948 functionName := requestType.Name() + "_Fn"
949 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
950 labelMapName,
951 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
952 functionDefSection += fmt.Sprintf(functionDefFormatString,
953 functionName,
954 indent(requestType.StarlarkFunctionBody()))
955 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
956 labelMapName, functionName)
957 }
958
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400959 formatString := `
960# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400961
Cole Faustb85d1a12022-11-08 18:14:01 -0800962{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500963
Cole Faustb85d1a12022-11-08 18:14:01 -0800964{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500965
966def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400967 # TODO(b/199363072): filegroups and file targets aren't associated with any
968 # specific platform architecture in mixed builds. This is consistent with how
969 # Soong treats filegroups, but it may not be the case with manually-written
970 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500971 buildoptions = build_options(target)
Yu Liue4312402023-01-18 09:15:31 -0800972
Jingwen Chen8f222742021-10-07 12:02:23 +0000973 if buildoptions == None:
974 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400975 # any specific platform architecture in mixed builds, so use the host.
976 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -0800977 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500978 if len(platforms) != 1:
979 # An individual configured target should have only one platform architecture.
980 # Note that it's fine for there to be multiple architectures for the same label,
981 # but each is its own configured target.
982 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -0800983 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -0500984 if platform_name == "host":
985 return "HOST"
Cole Faust319abae2023-06-06 15:12:49 -0700986 if not platform_name.startswith("mixed_builds_product-{TARGET_BUILD_VARIANT}"):
987 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))
988 platform_name = platform_name.removeprefix("mixed_builds_product-{TARGET_BUILD_VARIANT}").removeprefix("_")
Yu Liue4312402023-01-18 09:15:31 -0800989 config_key = ""
Cole Faustb85d1a12022-11-08 18:14:01 -0800990 if not platform_name:
Yu Liue4312402023-01-18 09:15:31 -0800991 config_key = "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400992 elif platform_name.startswith("android_"):
Yu Liue4312402023-01-18 09:15:31 -0800993 config_key = platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400994 elif platform_name.startswith("linux_"):
Yu Liue4312402023-01-18 09:15:31 -0800995 config_key = platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400996 else:
Cole Faust319abae2023-06-06 15:12:49 -0700997 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 -0500998
Yu Liue4312402023-01-18 09:15:31 -0800999 within_apex = buildoptions.get("//build/bazel/rules/apex:within_apex")
1000 apex_sdk_version = buildoptions.get("//build/bazel/rules/apex:min_sdk_version")
1001
1002 if within_apex:
1003 config_key += "|within_apex"
1004 if apex_sdk_version != None and len(apex_sdk_version) > 0:
1005 config_key += "|" + apex_sdk_version
1006
1007 return config_key
1008
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001009def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -05001010 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -05001011
Chris Parsons86dc2c22022-09-28 14:58:41 -04001012 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
1013 if id_string.startswith("//"):
1014 id_string = "@" + id_string
1015
Cole Faustb85d1a12022-11-08 18:14:01 -08001016 {MAIN_SWITCH_SECTION}
1017
Chris Parsons944e7d02021-03-11 11:08:46 -05001018 # This target was not requested via cquery, and thus must be a dependency
1019 # of a requested target.
1020 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001021`
Cole Faustb85d1a12022-11-08 18:14:01 -08001022 replacer := strings.NewReplacer(
1023 "{TARGET_PRODUCT}", context.targetProduct,
1024 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
1025 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
1026 "{FUNCTION_DEF_SECTION}", functionDefSection,
1027 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001028
Cole Faustb85d1a12022-11-08 18:14:01 -08001029 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001030}
1031
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001032// Returns a path containing build-related metadata required for interfacing
1033// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001034func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001035 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -05001036}
1037
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001038// Returns the path where the contents of the @soong_injection repository live.
1039// It is used by Soong to tell Bazel things it cannot over the command line.
1040func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001041 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001042}
1043
1044// Returns the path of the synthetic Bazel workspace that contains a symlink
1045// forest composed the whole source tree and BUILD files generated by bp2build.
1046func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001047 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001048}
1049
Jingwen Chen8c523582021-06-01 11:19:53 +00001050// Returns the path to the top level out dir ($OUT_DIR).
1051func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001052 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +00001053}
1054
Sasha Smundak4975c822022-11-16 15:28:18 -08001055const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
1056
1057var (
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001058 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
1059 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
1060 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
1061 allBazelCommands = []bazelCommand{aqueryCmd, cqueryCmd, buildCmd}
Sasha Smundak4975c822022-11-16 15:28:18 -08001062)
1063
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001064// Issues commands to Bazel to receive results for all cquery requests
1065// queued in the BazelContext.
Liz Kammer690fbac2023-02-10 11:11:17 -05001066func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx invokeBazelContext) error {
1067 eventHandler := ctx.GetEventHandler()
1068 eventHandler.Begin("bazel")
1069 defer eventHandler.End("bazel")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001070
Sasha Smundak4975c822022-11-16 15:28:18 -08001071 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
1072 if err := os.MkdirAll(metricsDir, 0777); err != nil {
1073 return err
1074 }
1075 }
1076 context.results = make(map[cqueryKey]string)
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001077 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001078 return err
1079 }
1080 if err := context.runAquery(config, ctx); err != nil {
1081 return err
1082 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001083 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001084 return err
1085 }
1086
1087 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001088 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -08001089 return nil
1090}
1091
Liz Kammer690fbac2023-02-10 11:11:17 -05001092func (context *mixedBuildBazelContext) runCquery(config Config, ctx invokeBazelContext) error {
1093 eventHandler := ctx.GetEventHandler()
1094 eventHandler.Begin("cquery")
1095 defer eventHandler.End("cquery")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001096 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +02001097 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
1098 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
1099 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -05001100 if err != nil {
1101 return err
1102 }
1103 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001104 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001105 return err
1106 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001107 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001108 return err
1109 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001110 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001111 return err
1112 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001113 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001114 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001115 return err
1116 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001117
Yu Liue4312402023-01-18 09:15:31 -08001118 extraFlags := []string{"--output=starlark", "--starlark:file=" + absolutePath(cqueryFileRelpath)}
1119 if Bool(config.productVariables.ClangCoverage) {
1120 extraFlags = append(extraFlags, "--collect_code_coverage")
1121 }
1122
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001123 cqueryCmdRequest := context.createBazelCommand(config, bazel.CqueryBuildRootRunName, cqueryCmd, extraFlags...)
1124 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCmdRequest, context.paths, eventHandler)
Wei Licbd181c2022-11-16 08:59:23 -08001125 if cqueryErr != nil {
1126 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001127 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001128 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", context.printableCqueryCommand(cqueryCmdRequest))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001129 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001130 return err
1131 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001132 cqueryResults := map[string]string{}
1133 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1134 if strings.Contains(outputLine, ">>") {
1135 splitLine := strings.SplitN(outputLine, ">>", 2)
1136 cqueryResults[splitLine[0]] = splitLine[1]
1137 }
1138 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001139 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001140 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001141 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001142 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001143 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001144 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001145 }
1146 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001147 return nil
1148}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001149
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001150func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1151 oldContents, err := os.ReadFile(path)
1152 if err != nil || !bytes.Equal(contents, oldContents) {
1153 err = os.WriteFile(path, contents, perm)
1154 }
1155 return nil
1156}
1157
Liz Kammer690fbac2023-02-10 11:11:17 -05001158func (context *mixedBuildBazelContext) runAquery(config Config, ctx invokeBazelContext) error {
1159 eventHandler := ctx.GetEventHandler()
1160 eventHandler.Begin("aquery")
1161 defer eventHandler.End("aquery")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001162 // Issue an aquery command to retrieve action information about the bazel build tree.
1163 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001164 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1165 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001166 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001167 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001168 extraFlags = append(extraFlags, "--collect_code_coverage")
1169 paths := make([]string, 0, 2)
1170 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001171 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001172 // TODO(b/259404593) convert path wildcard to regex values
1173 if p[i] == "*" {
1174 p[i] = ".*"
1175 }
1176 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001177 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1178 }
1179 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1180 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1181 }
1182 if len(paths) > 0 {
1183 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001184 }
1185 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001186 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.AqueryBuildRootRunName, aqueryCmd,
1187 extraFlags...), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001188 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001189 return err
1190 }
Liz Kammer690fbac2023-02-10 11:11:17 -05001191 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001192 return err
1193}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001194
Liz Kammer690fbac2023-02-10 11:11:17 -05001195func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx invokeBazelContext) error {
1196 eventHandler := ctx.GetEventHandler()
1197 eventHandler.Begin("symlinks")
1198 defer eventHandler.End("symlinks")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001199 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1200 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1201 // but some of symlinks may be required to resolve source dependencies of the build.
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001202 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.BazelBuildPhonyRootRunName, buildCmd), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001203 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001204}
Chris Parsonsa798d962020-10-12 23:44:08 -04001205
Liz Kammera4655a92023-02-10 17:17:28 -05001206func (context *mixedBuildBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001207 return context.buildStatements
1208}
1209
Sasha Smundak39a301c2022-12-29 17:11:49 -08001210func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001211 return context.depsets
1212}
1213
Sasha Smundak39a301c2022-12-29 17:11:49 -08001214func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001215 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001216}
1217
Chris Parsonsa798d962020-10-12 23:44:08 -04001218// Singleton used for registering BUILD file ninja dependencies (needed
1219// for correctness of builds which use Bazel.
1220func BazelSingleton() Singleton {
1221 return &bazelSingleton{}
1222}
1223
1224type bazelSingleton struct{}
1225
1226func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001227 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001228 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001229 return
1230 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001231
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001232 // Add ninja file dependencies for files which all bazel invocations require.
1233 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001234 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001235 ctx.AddNinjaFileDeps(bazelBuildList)
1236
Sasha Smundak0e87b182022-12-01 11:46:11 -08001237 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001238 if err != nil {
1239 ctx.Errorf(err.Error())
1240 }
1241 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1242 for _, file := range files {
1243 ctx.AddNinjaFileDeps(file)
1244 }
1245
Chris Parsons1a7aca02022-04-25 22:35:15 -04001246 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1247 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001248 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001249 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1250 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001251 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1252 }
1253 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001254 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1255 if artifactPath == "bazel-out/volatile-status.txt" {
1256 // See https://bazel.build/docs/user-manual#workspace-status
1257 orderOnlies = append(orderOnlies, pathInBazelOut)
1258 } else {
1259 outputs = append(outputs, pathInBazelOut)
1260 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001261 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001262 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001263 ctx.Build(pctx, BuildParams{
1264 Rule: blueprint.Phony,
1265 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1266 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001267 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001268 })
1269 }
1270
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001271 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1272 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001273 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Liz Kammera4655a92023-02-10 17:17:28 -05001274 // nil build statements are a valid case where we do not create an action because it is
1275 // unnecessary or handled by other processing
1276 if buildStatement == nil {
1277 continue
1278 }
Sasha Smundak1da064c2022-06-08 16:36:16 -07001279 if len(buildStatement.Command) > 0 {
1280 rule := NewRuleBuilder(pctx, ctx)
1281 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1282 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1283 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1284 continue
1285 }
1286 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1287 // and thus require special treatment. If BuildStatement were an interface implementing
1288 // buildRule(ctx) function, the code here would just call it.
1289 // Unfortunately, the BuildStatement is defined in
1290 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1291 // because this would cause circular dependency. So, until we move aquery processing
1292 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001293 switch buildStatement.Mnemonic {
1294 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001295 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1296 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001297 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001298 // build-runfiles arguments are the manifest file and the target directory
1299 // where it creates the symlink tree according to this manifest (and then
1300 // writes the MANIFEST file to it).
1301 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1302 outManifestPath := outManifest.String()
1303 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1304 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1305 }
1306 outDir := filepath.Dir(outManifestPath)
1307 ctx.Build(pctx, BuildParams{
1308 Rule: buildRunfilesRule,
1309 Output: outManifest,
1310 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1311 Description: "symlink tree for " + outDir,
1312 Args: map[string]string{
1313 "outDir": outDir,
1314 },
1315 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001316 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001317 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001318 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001319 }
1320}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001321
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001322// Register bazel-owned build statements (obtained from the aquery invocation).
Liz Kammera4655a92023-02-10 17:17:28 -05001323func createCommand(cmd *RuleBuilderCommand, buildStatement *bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001324 // executionRoot is the action cwd.
1325 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1326
1327 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1328 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001329 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001330 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001331 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001332 }
1333 cmd.Text("&&")
1334 }
1335
1336 for _, pair := range buildStatement.Env {
1337 // Set per-action env variables, if any.
1338 cmd.Flag(pair.Key + "=" + pair.Value)
1339 }
1340
1341 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001342 if len(buildStatement.Command) > 16*1024 {
1343 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1344 WriteFileRule(ctx, commandFile, buildStatement.Command)
1345
1346 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1347 } else {
1348 cmd.Text(buildStatement.Command)
1349 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001350
1351 for _, outputPath := range buildStatement.OutputPaths {
1352 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1353 }
1354 for _, inputPath := range buildStatement.InputPaths {
1355 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1356 }
1357 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1358 otherDepsetName := bazelDepsetName(inputDepsetHash)
1359 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1360 }
1361
1362 if depfile := buildStatement.Depfile; depfile != nil {
1363 // The paths in depfile are relative to `executionRoot`.
1364 // Hence, they need to be corrected by replacing "bazel-out"
1365 // with the full `bazelOutDir`.
1366 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1367 // would be deemed missing.
1368 // (Note: The regexp uses a capture group because the version of sed
1369 // does not support a look-behind pattern.)
1370 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1371 bazelOutDir, *depfile)
1372 cmd.Text(replacement)
1373 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1374 }
1375
1376 for _, symlinkPath := range buildStatement.SymlinkPaths {
1377 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1378 }
1379}
1380
Chris Parsons8d6e4332021-02-22 16:13:50 -05001381func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001382 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001383}
1384
Chris Parsons787fb362021-10-14 18:43:51 -04001385func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001386 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001387 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001388 if key.configKey.osType.Class == Device {
1389 // For the generic Android, the expected result is "target|android", which
1390 // corresponds to the product_variable_config named "android_target" in
1391 // build/bazel/platforms/BUILD.bazel.
1392 arch = "target"
1393 } else {
1394 // Use host platform, which is currently hardcoded to be x86_64.
1395 arch = "x86_64"
1396 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001397 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001398 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001399 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001400 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001401 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001402 }
Yu Liue4312402023-01-18 09:15:31 -08001403 keyString := arch + "|" + osName
1404 if key.configKey.apexKey.WithinApex {
1405 keyString += "|" + withinApexToString(key.configKey.apexKey.WithinApex)
1406 }
1407
1408 if len(key.configKey.apexKey.ApexSdkVersion) > 0 {
1409 keyString += "|" + key.configKey.apexKey.ApexSdkVersion
1410 }
1411
1412 return keyString
Chris Parsons787fb362021-10-14 18:43:51 -04001413}
1414
Chris Parsonsf874e462022-05-10 13:50:12 -04001415func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001416 return configKey{
1417 // use string because Arch is not a valid key in go
1418 arch: ctx.Arch().String(),
1419 osType: ctx.Os(),
1420 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001421}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001422
Yu Liue4312402023-01-18 09:15:31 -08001423func GetConfigKeyApexVariant(ctx BaseModuleContext, apexKey *ApexConfigKey) configKey {
1424 configKey := GetConfigKey(ctx)
1425
1426 if apexKey != nil {
1427 configKey.apexKey = ApexConfigKey{
1428 WithinApex: apexKey.WithinApex,
1429 ApexSdkVersion: apexKey.ApexSdkVersion,
1430 }
1431 }
1432
1433 return configKey
1434}
1435
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001436func bazelDepsetName(contentHash string) string {
1437 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001438}
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001439
1440func EnvironmentVarsFile(config Config) string {
1441 return fmt.Sprintf(bazel.GeneratedBazelFileWarning+`
1442_env = %s
1443
1444env = _env
1445`,
1446 starlark_fmt.PrintStringList(allowedBazelEnvironmentVars, 0),
1447 )
1448}