blob: 4645e6be5abfdcbe030ee331ff8b231fc5f8345d [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
Chris Parsonsad876012022-08-20 14:48:32 -0400260 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
261 modulesDefaultToBazel bool
Cole Faustb85d1a12022-11-08 18:14:01 -0800262
263 targetProduct string
264 targetBuildVariant string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400265}
266
Sasha Smundak39a301c2022-12-29 17:11:49 -0800267var _ BazelContext = &mixedBuildBazelContext{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400268
269// A bazel context to use when Bazel is disabled.
270type noopBazelContext struct{}
271
272var _ BazelContext = noopBazelContext{}
273
274// A bazel context to use for tests.
275type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400276 OutputBaseDir string
277
Spandan Dasbd156812023-06-05 22:43:13 +0000278 LabelToOutputFiles map[string][]string
279 LabelToCcInfo map[string]cquery.CcInfo
280 LabelToPythonBinary map[string]string
281 LabelToApexInfo map[string]cquery.ApexInfo
282 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
283 LabelToPrebuiltFileInfo map[string]cquery.PrebuiltFileInfo
Yu Liue4312402023-01-18 09:15:31 -0800284
285 BazelRequests map[string]bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400286}
287
Yu Liue4312402023-01-18 09:15:31 -0800288func (m MockBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
289 key := BuildMockBazelContextRequestKey(label, requestType, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
290 if m.BazelRequests == nil {
291 m.BazelRequests = make(map[string]bool)
292 }
293 m.BazelRequests[key] = true
Chris Parsons8d6e4332021-02-22 16:13:50 -0500294}
295
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700296func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500297 result, ok := m.LabelToOutputFiles[label]
298 if !ok {
299 return []string{}, fmt.Errorf("no target with label %q in LabelToOutputFiles", label)
300 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400301 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400302}
303
Yu Liue4312402023-01-18 09:15:31 -0800304func (m MockBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500305 result, ok := m.LabelToCcInfo[label]
306 if !ok {
Yu Liue4312402023-01-18 09:15:31 -0800307 key := BuildMockBazelContextResultKey(label, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
308 result, ok = m.LabelToCcInfo[key]
309 if !ok {
310 return cquery.CcInfo{}, fmt.Errorf("no target with label %q in LabelToCcInfo", label)
311 }
Sam Delmericoce39f832023-01-23 14:04:24 -0500312 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400313 return result, nil
314}
315
Liz Kammerbe6a7122022-11-04 16:05:11 -0400316func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500317 result, ok := m.LabelToApexInfo[label]
318 if !ok {
319 return cquery.ApexInfo{}, fmt.Errorf("no target with label %q in LabelToApexInfo", label)
320 }
Liz Kammer0e255ef2022-11-04 16:07:04 -0400321 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700322}
323
Sasha Smundakedd16662022-10-07 14:44:50 -0700324func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500325 result, ok := m.LabelToCcBinary[label]
326 if !ok {
327 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no target with label %q in LabelToCcBinary", label)
328 }
Sasha Smundakedd16662022-10-07 14:44:50 -0700329 return result, nil
330}
331
Spandan Dasbd156812023-06-05 22:43:13 +0000332func (m MockBazelContext) GetPrebuiltFileInfo(label string, _ configKey) (cquery.PrebuiltFileInfo, error) {
333 result, ok := m.LabelToPrebuiltFileInfo[label]
334 if !ok {
335 return cquery.PrebuiltFileInfo{}, fmt.Errorf("no target with label %q in LabelToPrebuiltFileInfo", label)
336 }
337 return result, nil
338}
339
Liz Kammer690fbac2023-02-10 11:11:17 -0500340func (m MockBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400341 panic("unimplemented")
342}
343
Yu Liue4312402023-01-18 09:15:31 -0800344func (m MockBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400345 return true
346}
347
Yu Liubfb23622023-02-22 10:42:15 -0800348func (m MockBazelContext) IsModuleDclaAllowed(_ string) bool {
349 return true
350}
351
Liz Kammera92e8442021-04-07 20:25:21 -0400352func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500353
Liz Kammera4655a92023-02-10 17:17:28 -0500354func (m MockBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
355 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500356}
357
Chris Parsons1a7aca02022-04-25 22:35:15 -0400358func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
359 return []bazel.AqueryDepset{}
360}
361
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400362var _ BazelContext = MockBazelContext{}
363
Yu Liue4312402023-01-18 09:15:31 -0800364func BuildMockBazelContextRequestKey(label string, request cqueryRequest, arch string, osType OsType, apexKey ApexConfigKey) string {
365 cfgKey := configKey{
366 arch: arch,
367 osType: osType,
368 apexKey: apexKey,
369 }
370
371 return strings.Join([]string{label, request.Name(), cfgKey.String()}, "_")
372}
373
374func BuildMockBazelContextResultKey(label string, arch string, osType OsType, apexKey ApexConfigKey) string {
375 cfgKey := configKey{
376 arch: arch,
377 osType: osType,
378 apexKey: apexKey,
379 }
380
381 return strings.Join([]string{label, cfgKey.String()}, "_")
382}
383
Sasha Smundak39a301c2022-12-29 17:11:49 -0800384func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400385 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400386 bazelCtx.requestMutex.Lock()
387 defer bazelCtx.requestMutex.Unlock()
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500388
389 // Insert key into requests, maintaining the sort, and only if it's not duplicate.
390 keyString := key.String()
391 foundEqual := false
392 notLessThanKeyString := func(i int) bool {
393 s := bazelCtx.requests[i].String()
394 v := strings.Compare(s, keyString)
395 if v == 0 {
396 foundEqual = true
397 }
398 return v >= 0
399 }
400 targetIndex := sort.Search(len(bazelCtx.requests), notLessThanKeyString)
401 if foundEqual {
402 return
403 }
404
405 if targetIndex == len(bazelCtx.requests) {
406 bazelCtx.requests = append(bazelCtx.requests, key)
407 } else {
408 bazelCtx.requests = append(bazelCtx.requests[:targetIndex+1], bazelCtx.requests[targetIndex:]...)
409 bazelCtx.requests[targetIndex] = key
410 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400411}
412
Sasha Smundak39a301c2022-12-29 17:11:49 -0800413func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400414 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400415 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500416 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400417
Chris Parsonsf874e462022-05-10 13:50:12 -0400418 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400419 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400420 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400421}
422
Sasha Smundak39a301c2022-12-29 17:11:49 -0800423func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400424 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400425 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000426 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400427 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000428 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400429 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 +0000430}
431
Sasha Smundak39a301c2022-12-29 17:11:49 -0800432func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400433 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700434 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500435 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700436 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400437 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700438}
439
Sasha Smundak39a301c2022-12-29 17:11:49 -0800440func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700441 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
442 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500443 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700444 }
445 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
446}
447
Spandan Dasbd156812023-06-05 22:43:13 +0000448func (bazelCtx *mixedBuildBazelContext) GetPrebuiltFileInfo(label string, cfgKey configKey) (cquery.PrebuiltFileInfo, error) {
449 key := makeCqueryKey(label, cquery.GetPrebuiltFileInfo, cfgKey)
450 if rawString, ok := bazelCtx.results[key]; ok {
451 return cquery.GetPrebuiltFileInfo.ParseResult(strings.TrimSpace(rawString))
452 }
453 return cquery.PrebuiltFileInfo{}, fmt.Errorf("no bazel response for %s", key)
454}
455
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700456func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500457 panic("unimplemented")
458}
459
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700460func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500461 panic("unimplemented")
462}
463
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700464func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400465 panic("unimplemented")
466}
467
Liz Kammerbe6a7122022-11-04 16:05:11 -0400468func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700469 panic("unimplemented")
470}
471
Sasha Smundakedd16662022-10-07 14:44:50 -0700472func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
473 //TODO implement me
474 panic("implement me")
475}
476
Spandan Dasbd156812023-06-05 22:43:13 +0000477func (n noopBazelContext) GetPrebuiltFileInfo(_ string, _ configKey) (cquery.PrebuiltFileInfo, error) {
478 panic("implement me")
479}
480
Liz Kammer690fbac2023-02-10 11:11:17 -0500481func (n noopBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400482 panic("unimplemented")
483}
484
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500485func (m noopBazelContext) OutputBase() string {
486 return ""
487}
488
Yu Liue4312402023-01-18 09:15:31 -0800489func (n noopBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400490 return false
491}
492
Yu Liubfb23622023-02-22 10:42:15 -0800493func (n noopBazelContext) IsModuleDclaAllowed(_ string) bool {
494 return false
495}
496
Liz Kammera4655a92023-02-10 17:17:28 -0500497func (m noopBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
498 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500499}
500
Chris Parsons1a7aca02022-04-25 22:35:15 -0400501func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
502 return []bazel.AqueryDepset{}
503}
504
Yu Liu6a7940c2023-05-09 17:12:22 -0700505func AddToStringSet(set map[string]bool, items []string) {
Yu Liue4312402023-01-18 09:15:31 -0800506 for _, item := range items {
507 set[item] = true
508 }
509}
510
Cole Faust705968d2022-12-14 11:32:05 -0800511func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400512 disabledModules := map[string]bool{}
513 enabledModules := map[string]bool{}
514
Cole Faust705968d2022-12-14 11:32:05 -0800515 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400516 case BazelProdMode:
Yu Liu6a7940c2023-05-09 17:12:22 -0700517 AddToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800518 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000519 enabledModules[enabledAdHocModule] = true
520 }
MarkDacekb78465d2022-10-18 20:10:16 +0000521 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400522 // Staging mode includes all prod modules plus all staging modules.
Yu Liu6a7940c2023-05-09 17:12:22 -0700523 AddToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
524 AddToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800525 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000526 enabledModules[enabledAdHocModule] = true
527 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400528 case BazelDevMode:
Yu Liu6a7940c2023-05-09 17:12:22 -0700529 AddToStringSet(disabledModules, allowlists.MixedBuildsDisabledList)
Chris Parsonsef615e52022-08-18 22:04:11 -0400530 default:
Cole Faust705968d2022-12-14 11:32:05 -0800531 panic("Expected BazelProdMode, BazelStagingMode, or BazelDevMode")
532 }
533 return enabledModules, disabledModules
534}
535
536func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
537 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
538 enabledList := make([]string, 0, len(enabledModules))
539 for module := range enabledModules {
540 if !disabledModules[module] {
541 enabledList = append(enabledList, module)
542 }
543 }
544 sort.Strings(enabledList)
545 return enabledList
546}
547
548func NewBazelContext(c *config) (BazelContext, error) {
549 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode && c.BuildMode != BazelDevMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400550 return noopBazelContext{}, nil
551 }
552
Cole Faust705968d2022-12-14 11:32:05 -0800553 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
554
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800555 paths := bazelPaths{
556 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400557 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800558 var missing []string
559 vars := []struct {
560 name string
561 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000562
563 // True if the environment variable needs to be tracked so that changes to the variable
564 // cause the ninja file to be regenerated, false otherwise. False should only be set for
565 // environment variables that have no effect on the generated ninja file.
566 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800567 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000568 {"BAZEL_HOME", &paths.homeDir, true},
569 {"BAZEL_PATH", &paths.bazelPath, true},
570 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
571 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
572 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
573 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800574 }
575 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000576 if v.track {
577 if s := c.Getenv(v.name); len(s) > 1 {
578 *v.ptr = s
579 continue
580 }
581 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800582 *v.ptr = s
583 } else {
584 missing = append(missing, v.name)
585 }
586 }
587 if len(missing) > 0 {
588 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
589 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800590
591 targetBuildVariant := "user"
592 if c.Eng() {
593 targetBuildVariant = "eng"
594 } else if c.Debuggable() {
595 targetBuildVariant = "userdebug"
596 }
597 targetProduct := "unknown"
598 if c.HasDeviceProduct() {
599 targetProduct = c.DeviceProduct()
600 }
Yu Liue4312402023-01-18 09:15:31 -0800601 dclaMixedBuildsEnabledList := []string{}
602 if c.BuildMode == BazelProdMode {
603 dclaMixedBuildsEnabledList = allowlists.ProdDclaMixedBuildsEnabledList
604 } else if c.BuildMode == BazelStagingMode {
605 dclaMixedBuildsEnabledList = append(allowlists.ProdDclaMixedBuildsEnabledList,
606 allowlists.StagingDclaMixedBuildsEnabledList...)
607 }
608 dclaEnabledModules := map[string]bool{}
Yu Liu6a7940c2023-05-09 17:12:22 -0700609 AddToStringSet(dclaEnabledModules, dclaMixedBuildsEnabledList)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800610 return &mixedBuildBazelContext{
Chris Parsons9402ca82023-02-23 17:28:06 -0500611 bazelRunner: &builtinBazelRunner{c.UseBazelProxy, absolutePath(c.outDir)},
Yu Liue4312402023-01-18 09:15:31 -0800612 paths: &paths,
613 modulesDefaultToBazel: c.BuildMode == BazelDevMode,
614 bazelEnabledModules: enabledModules,
615 bazelDisabledModules: disabledModules,
616 bazelDclaEnabledModules: dclaEnabledModules,
617 targetProduct: targetProduct,
618 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400619 }, nil
620}
621
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400622func (p *bazelPaths) BazelMetricsDir() string {
623 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000624}
625
Yu Liue4312402023-01-18 09:15:31 -0800626func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string, withinApex bool) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400627 if context.bazelDisabledModules[moduleName] {
628 return false
629 }
630 if context.bazelEnabledModules[moduleName] {
631 return true
632 }
Yu Liubfb23622023-02-22 10:42:15 -0800633 if withinApex && context.IsModuleDclaAllowed(moduleName) {
Yu Liue4312402023-01-18 09:15:31 -0800634 return true
635 }
636
Chris Parsonsad876012022-08-20 14:48:32 -0400637 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400638}
639
Yu Liubfb23622023-02-22 10:42:15 -0800640func (context *mixedBuildBazelContext) IsModuleDclaAllowed(moduleName string) bool {
641 return context.bazelDclaEnabledModules[moduleName]
642}
643
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400644func pwdPrefix() string {
645 // Darwin doesn't have /proc
646 if runtime.GOOS != "darwin" {
647 return "PWD=/proc/self/cwd"
648 }
649 return ""
650}
651
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400652type bazelCommand struct {
653 command string
654 // query or label
655 expression string
656}
657
Chris Parsons9402ca82023-02-23 17:28:06 -0500658type builtinBazelRunner struct {
659 useBazelProxy bool
660 outDir string
661}
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400662
Chris Parsons808d84c2021-03-09 20:43:32 -0500663// Issues the given bazel command with given build label and additional flags.
664// Returns (stdout, stderr, error). The first and second return values are strings
665// containing the stdout and stderr of the run command, and an error is returned if
666// the invocation returned an error code.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000667func (r *builtinBazelRunner) issueBazelCommand(cmdRequest bazel.CmdRequest, paths *bazelPaths, eventHandler *metrics.EventHandler) (string, string, error) {
Chris Parsons9402ca82023-02-23 17:28:06 -0500668 if r.useBazelProxy {
669 eventHandler.Begin("client_proxy")
670 defer eventHandler.End("client_proxy")
671 proxyClient := bazel.NewProxyClient(r.outDir)
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000672 resp, err := proxyClient.IssueCommand(cmdRequest)
Chris Parsons9402ca82023-02-23 17:28:06 -0500673
674 if err != nil {
675 return "", "", err
676 }
677 if len(resp.ErrorString) > 0 {
678 return "", "", fmt.Errorf(resp.ErrorString)
679 }
680 return resp.Stdout, resp.Stderr, nil
Jason Wu52cd1942022-09-08 15:37:57 +0000681 } else {
Chris Parsons9402ca82023-02-23 17:28:06 -0500682 eventHandler.Begin("bazel command")
683 defer eventHandler.End("bazel command")
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000684
685 stdout, stderr, err := bazel.ExecBazel(paths.bazelPath, absolutePath(paths.syntheticWorkspaceDir()), cmdRequest)
686 return string(stdout), string(stderr), err
Jason Wu52cd1942022-09-08 15:37:57 +0000687 }
688}
689
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000690func (context *mixedBuildBazelContext) createBazelCommand(config Config, runName bazel.RunName, command bazelCommand,
691 extraFlags ...string) bazel.CmdRequest {
Cole Faust319abae2023-06-06 15:12:49 -0700692 if runtime.GOOS != "linux" && runtime.GOOS != "darwin" {
693 panic("Unknown GOOS: " + runtime.GOOS)
694 }
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000695 cmdFlags := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000696 "--output_base=" + absolutePath(context.paths.outputBase),
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000697 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700698 command.expression,
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000699 "--profile=" + shared.BazelMetricsFilename(context.paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400700
Cole Faust319abae2023-06-06 15:12:49 -0700701 "--host_platform=@soong_injection//product_config_platforms:mixed_builds_product-" + context.targetBuildVariant + "_" + runtime.GOOS + "_x86_64",
702 // Don't specify --platforms, because on some products/branches (like kernel-build-tools)
703 // the main platform for mixed_builds_product-variant doesn't exist because an arch isn't
704 // specified in product config. The derivative platforms that config_node transitions into
705 // will still work.
Jingwen Chen583ab212023-05-30 09:45:23 +0000706
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700707 // Suppress noise
708 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500709 "--noshow_progress",
710 "--norun_validations",
711 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400712 cmdFlags = append(cmdFlags, extraFlags...)
713
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700714 extraEnv := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000715 "HOME=" + context.paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200716 pwdPrefix(),
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000717 "BUILD_DIR=" + absolutePath(context.paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700718 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000719 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000720 "OUT_DIR=" + absolutePath(context.paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500721 // Disables local host detection of gcc; toolchain information is defined
722 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700723 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
724 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500725 for _, envvar := range allowedBazelEnvironmentVars {
726 val := config.Getenv(envvar)
727 if val == "" {
728 continue
729 }
730 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
731 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000732 envVars := append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400733
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000734 return bazel.CmdRequest{cmdFlags, envVars}
Jason Wu52cd1942022-09-08 15:37:57 +0000735}
736
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000737func (context *mixedBuildBazelContext) printableCqueryCommand(bazelCmd bazel.CmdRequest) string {
738 args := append([]string{context.paths.bazelPath}, bazelCmd.Argv...)
739 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(args, "\" \"") + "\""
Jason Wu52cd1942022-09-08 15:37:57 +0000740 return outputString
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400741}
742
Sasha Smundak39a301c2022-12-29 17:11:49 -0800743func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500744 // TODO(cparsons): Define configuration transitions programmatically based
745 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400746 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500747#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400748# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500749#####################################################
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400750def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800751 if attr.os == "android" and attr.arch == "target":
Cole Faust319abae2023-06-06 15:12:49 -0700752 target = "mixed_builds_product-{VARIANT}"
Cole Faustb85d1a12022-11-08 18:14:01 -0800753 else:
Cole Faust319abae2023-06-06 15:12:49 -0700754 target = "mixed_builds_product-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Yu Liue4312402023-01-18 09:15:31 -0800755 apex_name = ""
756 if attr.within_apex:
757 # //build/bazel/rules/apex:apex_name has to be set to a non_empty value,
758 # otherwise //build/bazel/rules/apex:non_apex will be true and the
759 # "-D__ANDROID_APEX__" compiler flag will be missing. Apex_name is used
760 # in some validation on bazel side which don't really apply in mixed
761 # build because soong will do the work, so we just set it to a fixed
762 # value here.
763 apex_name = "dcla_apex"
764 outputs = {
Jingwen Chen583ab212023-05-30 09:45:23 +0000765 "//command_line_option:platforms": "@soong_injection//product_config_platforms:%s" % target,
Yu Liue4312402023-01-18 09:15:31 -0800766 "@//build/bazel/rules/apex:within_apex": attr.within_apex,
767 "@//build/bazel/rules/apex:min_sdk_version": attr.apex_sdk_version,
768 "@//build/bazel/rules/apex:apex_name": apex_name,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500769 }
770
Yu Liue4312402023-01-18 09:15:31 -0800771 return outputs
772
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400773_config_node_transition = transition(
774 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500775 inputs = [],
776 outputs = [
777 "//command_line_option:platforms",
Yu Liue4312402023-01-18 09:15:31 -0800778 "@//build/bazel/rules/apex:within_apex",
779 "@//build/bazel/rules/apex:min_sdk_version",
780 "@//build/bazel/rules/apex:apex_name",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500781 ],
782)
783
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400784def _passthrough_rule_impl(ctx):
785 return [DefaultInfo(files = depset(ctx.files.deps))]
786
787config_node = rule(
788 implementation = _passthrough_rule_impl,
789 attrs = {
Yu Liue4312402023-01-18 09:15:31 -0800790 "arch" : attr.string(mandatory = True),
791 "os" : attr.string(mandatory = True),
792 "within_apex" : attr.bool(default = False),
793 "apex_sdk_version" : attr.string(mandatory = True),
794 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400795 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
796 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500797)
798
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400799
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500800# Rule representing the root of the build, to depend on all Bazel targets that
801# are required for the build. Building this target will build the entire Bazel
802# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400803mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400804 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500805 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400806 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500807 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400808)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500809
810def _phony_root_impl(ctx):
811 return []
812
813# Rule to depend on other targets but build nothing.
814# This is useful as follows: building a target of this rule will generate
815# symlink forests for all dependencies of the target, without executing any
816# actions of the build.
817phony_root = rule(
818 implementation = _phony_root_impl,
819 attrs = {"deps" : attr.label_list()},
820)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400821`
Cole Faustb85d1a12022-11-08 18:14:01 -0800822
823 productReplacer := strings.NewReplacer(
824 "{PRODUCT}", context.targetProduct,
825 "{VARIANT}", context.targetBuildVariant)
826
827 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400828}
829
Sasha Smundak39a301c2022-12-29 17:11:49 -0800830func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500831 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
832 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400833 formatString := `
834# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400835load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
836
837%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400838
839mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400840 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000841 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400842)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500843
844phony_root(name = "phonyroot",
845 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000846 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500847)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400848`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400849 configNodeFormatString := `
850config_node(name = "%s",
851 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400852 os = "%s",
Yu Liue4312402023-01-18 09:15:31 -0800853 within_apex = %s,
854 apex_sdk_version = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400855 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000856 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400857)
858`
859
860 configNodesSection := ""
861
Chris Parsons787fb362021-10-14 18:43:51 -0400862 labelsByConfig := map[string][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500863
864 for _, val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200865 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400866 configString := getConfigString(val)
867 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400868 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400869
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500870 // Configs need to be sorted to maintain determinism of the BUILD file.
871 sortedConfigs := make([]string, 0, len(labelsByConfig))
872 for val := range labelsByConfig {
873 sortedConfigs = append(sortedConfigs, val)
874 }
875 sort.Slice(sortedConfigs, func(i, j int) bool { return sortedConfigs[i] < sortedConfigs[j] })
876
Jingwen Chen1e347862021-09-02 12:11:49 +0000877 allLabels := []string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500878 for _, configString := range sortedConfigs {
879 labels := labelsByConfig[configString]
Chris Parsons787fb362021-10-14 18:43:51 -0400880 configTokens := strings.Split(configString, "|")
Yu Liue4312402023-01-18 09:15:31 -0800881 if len(configTokens) < 2 {
Chris Parsons787fb362021-10-14 18:43:51 -0400882 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000883 }
Chris Parsons787fb362021-10-14 18:43:51 -0400884 archString := configTokens[0]
885 osString := configTokens[1]
Yu Liue4312402023-01-18 09:15:31 -0800886 withinApex := "False"
887 apexSdkVerString := ""
Chris Parsons787fb362021-10-14 18:43:51 -0400888 targetString := fmt.Sprintf("%s_%s", osString, archString)
Yu Liue4312402023-01-18 09:15:31 -0800889 if len(configTokens) > 2 {
890 targetString += "_" + configTokens[2]
891 if configTokens[2] == withinApexToString(true) {
892 withinApex = "True"
893 }
894 }
895 if len(configTokens) > 3 {
896 targetString += "_" + configTokens[3]
897 apexSdkVerString = configTokens[3]
898 }
Chris Parsons787fb362021-10-14 18:43:51 -0400899 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
900 labelsString := strings.Join(labels, ",\n ")
Yu Liue4312402023-01-18 09:15:31 -0800901 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, withinApex, apexSdkVerString,
902 labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400903 }
904
Jingwen Chen1e347862021-09-02 12:11:49 +0000905 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400906}
907
Chris Parsons944e7d02021-03-11 11:08:46 -0500908func indent(original string) string {
909 result := ""
910 for _, line := range strings.Split(original, "\n") {
911 result += " " + line + "\n"
912 }
913 return result
914}
915
Chris Parsons808d84c2021-03-09 20:43:32 -0500916// Returns the file contents of the buildroot.cquery file that should be used for the cquery
917// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800918// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500919// and grouped by their request type. The data retrieved for each label depends on its
920// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800921func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400922 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons38851d82023-03-15 00:19:32 -0400923 requestTypes := []cqueryRequest{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500924 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500925 cqueryId := getCqueryId(val)
926 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
Chris Parsons38851d82023-03-15 00:19:32 -0400927 if _, seenKey := requestTypeToCqueryIdEntries[val.requestType]; !seenKey {
928 requestTypes = append(requestTypes, val.requestType)
929 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500930 requestTypeToCqueryIdEntries[val.requestType] =
931 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
932 }
933 labelRegistrationMapSection := ""
934 functionDefSection := ""
935 mainSwitchSection := ""
936
937 mapDeclarationFormatString := `
938%s = {
939 %s
940}
941`
942 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800943def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500944%s
945`
946 mainSwitchSectionFormatString := `
947 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800948 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500949`
950
Chris Parsons38851d82023-03-15 00:19:32 -0400951 for _, requestType := range requestTypes {
Chris Parsons944e7d02021-03-11 11:08:46 -0500952 labelMapName := requestType.Name() + "_Labels"
953 functionName := requestType.Name() + "_Fn"
954 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
955 labelMapName,
956 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
957 functionDefSection += fmt.Sprintf(functionDefFormatString,
958 functionName,
959 indent(requestType.StarlarkFunctionBody()))
960 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
961 labelMapName, functionName)
962 }
963
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400964 formatString := `
965# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400966
Cole Faustb85d1a12022-11-08 18:14:01 -0800967{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500968
Cole Faustb85d1a12022-11-08 18:14:01 -0800969{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500970
971def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400972 # TODO(b/199363072): filegroups and file targets aren't associated with any
973 # specific platform architecture in mixed builds. This is consistent with how
974 # Soong treats filegroups, but it may not be the case with manually-written
975 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500976 buildoptions = build_options(target)
Yu Liue4312402023-01-18 09:15:31 -0800977
Jingwen Chen8f222742021-10-07 12:02:23 +0000978 if buildoptions == None:
979 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400980 # any specific platform architecture in mixed builds, so use the host.
981 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -0800982 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500983 if len(platforms) != 1:
984 # An individual configured target should have only one platform architecture.
985 # Note that it's fine for there to be multiple architectures for the same label,
986 # but each is its own configured target.
987 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -0800988 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -0500989 if platform_name == "host":
990 return "HOST"
Cole Faust319abae2023-06-06 15:12:49 -0700991 if not platform_name.startswith("mixed_builds_product-{TARGET_BUILD_VARIANT}"):
992 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))
993 platform_name = platform_name.removeprefix("mixed_builds_product-{TARGET_BUILD_VARIANT}").removeprefix("_")
Yu Liue4312402023-01-18 09:15:31 -0800994 config_key = ""
Cole Faustb85d1a12022-11-08 18:14:01 -0800995 if not platform_name:
Yu Liue4312402023-01-18 09:15:31 -0800996 config_key = "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400997 elif platform_name.startswith("android_"):
Yu Liue4312402023-01-18 09:15:31 -0800998 config_key = platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400999 elif platform_name.startswith("linux_"):
Yu Liue4312402023-01-18 09:15:31 -08001000 config_key = platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -04001001 else:
Cole Faust319abae2023-06-06 15:12:49 -07001002 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 -05001003
Yu Liue4312402023-01-18 09:15:31 -08001004 within_apex = buildoptions.get("//build/bazel/rules/apex:within_apex")
1005 apex_sdk_version = buildoptions.get("//build/bazel/rules/apex:min_sdk_version")
1006
1007 if within_apex:
1008 config_key += "|within_apex"
1009 if apex_sdk_version != None and len(apex_sdk_version) > 0:
1010 config_key += "|" + apex_sdk_version
1011
1012 return config_key
1013
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001014def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -05001015 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -05001016
Chris Parsons86dc2c22022-09-28 14:58:41 -04001017 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
1018 if id_string.startswith("//"):
1019 id_string = "@" + id_string
1020
Cole Faustb85d1a12022-11-08 18:14:01 -08001021 {MAIN_SWITCH_SECTION}
1022
Chris Parsons944e7d02021-03-11 11:08:46 -05001023 # This target was not requested via cquery, and thus must be a dependency
1024 # of a requested target.
1025 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001026`
Cole Faustb85d1a12022-11-08 18:14:01 -08001027 replacer := strings.NewReplacer(
1028 "{TARGET_PRODUCT}", context.targetProduct,
1029 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
1030 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
1031 "{FUNCTION_DEF_SECTION}", functionDefSection,
1032 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001033
Cole Faustb85d1a12022-11-08 18:14:01 -08001034 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001035}
1036
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001037// Returns a path containing build-related metadata required for interfacing
1038// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001039func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001040 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -05001041}
1042
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001043// Returns the path where the contents of the @soong_injection repository live.
1044// It is used by Soong to tell Bazel things it cannot over the command line.
1045func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001046 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001047}
1048
1049// Returns the path of the synthetic Bazel workspace that contains a symlink
1050// forest composed the whole source tree and BUILD files generated by bp2build.
1051func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001052 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001053}
1054
Jingwen Chen8c523582021-06-01 11:19:53 +00001055// Returns the path to the top level out dir ($OUT_DIR).
1056func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001057 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +00001058}
1059
Sasha Smundak4975c822022-11-16 15:28:18 -08001060const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
1061
1062var (
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001063 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
1064 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
1065 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
1066 allBazelCommands = []bazelCommand{aqueryCmd, cqueryCmd, buildCmd}
Sasha Smundak4975c822022-11-16 15:28:18 -08001067)
1068
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001069// Issues commands to Bazel to receive results for all cquery requests
1070// queued in the BazelContext.
Liz Kammer690fbac2023-02-10 11:11:17 -05001071func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx invokeBazelContext) error {
1072 eventHandler := ctx.GetEventHandler()
1073 eventHandler.Begin("bazel")
1074 defer eventHandler.End("bazel")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001075
Sasha Smundak4975c822022-11-16 15:28:18 -08001076 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
1077 if err := os.MkdirAll(metricsDir, 0777); err != nil {
1078 return err
1079 }
1080 }
1081 context.results = make(map[cqueryKey]string)
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001082 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001083 return err
1084 }
1085 if err := context.runAquery(config, ctx); err != nil {
1086 return err
1087 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001088 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001089 return err
1090 }
1091
1092 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001093 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -08001094 return nil
1095}
1096
Liz Kammer690fbac2023-02-10 11:11:17 -05001097func (context *mixedBuildBazelContext) runCquery(config Config, ctx invokeBazelContext) error {
1098 eventHandler := ctx.GetEventHandler()
1099 eventHandler.Begin("cquery")
1100 defer eventHandler.End("cquery")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001101 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +02001102 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
1103 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
1104 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -05001105 if err != nil {
1106 return err
1107 }
1108 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001109 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001110 return err
1111 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001112 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001113 return err
1114 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001115 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001116 return err
1117 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001118 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001119 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001120 return err
1121 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001122
Yu Liue4312402023-01-18 09:15:31 -08001123 extraFlags := []string{"--output=starlark", "--starlark:file=" + absolutePath(cqueryFileRelpath)}
1124 if Bool(config.productVariables.ClangCoverage) {
1125 extraFlags = append(extraFlags, "--collect_code_coverage")
1126 }
1127
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001128 cqueryCmdRequest := context.createBazelCommand(config, bazel.CqueryBuildRootRunName, cqueryCmd, extraFlags...)
1129 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCmdRequest, context.paths, eventHandler)
Wei Licbd181c2022-11-16 08:59:23 -08001130 if cqueryErr != nil {
1131 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001132 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001133 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", context.printableCqueryCommand(cqueryCmdRequest))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001134 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001135 return err
1136 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001137 cqueryResults := map[string]string{}
1138 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1139 if strings.Contains(outputLine, ">>") {
1140 splitLine := strings.SplitN(outputLine, ">>", 2)
1141 cqueryResults[splitLine[0]] = splitLine[1]
1142 }
1143 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001144 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001145 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001146 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001147 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001148 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001149 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001150 }
1151 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001152 return nil
1153}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001154
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001155func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1156 oldContents, err := os.ReadFile(path)
1157 if err != nil || !bytes.Equal(contents, oldContents) {
1158 err = os.WriteFile(path, contents, perm)
1159 }
1160 return nil
1161}
1162
Liz Kammer690fbac2023-02-10 11:11:17 -05001163func (context *mixedBuildBazelContext) runAquery(config Config, ctx invokeBazelContext) error {
1164 eventHandler := ctx.GetEventHandler()
1165 eventHandler.Begin("aquery")
1166 defer eventHandler.End("aquery")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001167 // Issue an aquery command to retrieve action information about the bazel build tree.
1168 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001169 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1170 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001171 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001172 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001173 extraFlags = append(extraFlags, "--collect_code_coverage")
1174 paths := make([]string, 0, 2)
1175 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001176 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001177 // TODO(b/259404593) convert path wildcard to regex values
1178 if p[i] == "*" {
1179 p[i] = ".*"
1180 }
1181 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001182 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1183 }
1184 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1185 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1186 }
1187 if len(paths) > 0 {
1188 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001189 }
1190 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001191 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.AqueryBuildRootRunName, aqueryCmd,
1192 extraFlags...), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001193 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001194 return err
1195 }
Liz Kammer690fbac2023-02-10 11:11:17 -05001196 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001197 return err
1198}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001199
Liz Kammer690fbac2023-02-10 11:11:17 -05001200func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx invokeBazelContext) error {
1201 eventHandler := ctx.GetEventHandler()
1202 eventHandler.Begin("symlinks")
1203 defer eventHandler.End("symlinks")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001204 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1205 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1206 // but some of symlinks may be required to resolve source dependencies of the build.
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001207 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.BazelBuildPhonyRootRunName, buildCmd), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001208 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001209}
Chris Parsonsa798d962020-10-12 23:44:08 -04001210
Liz Kammera4655a92023-02-10 17:17:28 -05001211func (context *mixedBuildBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001212 return context.buildStatements
1213}
1214
Sasha Smundak39a301c2022-12-29 17:11:49 -08001215func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001216 return context.depsets
1217}
1218
Sasha Smundak39a301c2022-12-29 17:11:49 -08001219func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001220 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001221}
1222
Chris Parsonsa798d962020-10-12 23:44:08 -04001223// Singleton used for registering BUILD file ninja dependencies (needed
1224// for correctness of builds which use Bazel.
1225func BazelSingleton() Singleton {
1226 return &bazelSingleton{}
1227}
1228
1229type bazelSingleton struct{}
1230
1231func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001232 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001233 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001234 return
1235 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001236
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001237 // Add ninja file dependencies for files which all bazel invocations require.
1238 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001239 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001240 ctx.AddNinjaFileDeps(bazelBuildList)
1241
Sasha Smundak0e87b182022-12-01 11:46:11 -08001242 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001243 if err != nil {
1244 ctx.Errorf(err.Error())
1245 }
1246 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1247 for _, file := range files {
1248 ctx.AddNinjaFileDeps(file)
1249 }
1250
Chris Parsons1a7aca02022-04-25 22:35:15 -04001251 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1252 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001253 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001254 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1255 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001256 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1257 }
1258 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001259 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1260 if artifactPath == "bazel-out/volatile-status.txt" {
1261 // See https://bazel.build/docs/user-manual#workspace-status
1262 orderOnlies = append(orderOnlies, pathInBazelOut)
1263 } else {
1264 outputs = append(outputs, pathInBazelOut)
1265 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001266 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001267 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001268 ctx.Build(pctx, BuildParams{
1269 Rule: blueprint.Phony,
1270 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1271 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001272 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001273 })
1274 }
1275
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001276 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1277 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001278 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Liz Kammera4655a92023-02-10 17:17:28 -05001279 // nil build statements are a valid case where we do not create an action because it is
1280 // unnecessary or handled by other processing
1281 if buildStatement == nil {
1282 continue
1283 }
Sasha Smundak1da064c2022-06-08 16:36:16 -07001284 if len(buildStatement.Command) > 0 {
1285 rule := NewRuleBuilder(pctx, ctx)
1286 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1287 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1288 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1289 continue
1290 }
1291 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1292 // and thus require special treatment. If BuildStatement were an interface implementing
1293 // buildRule(ctx) function, the code here would just call it.
1294 // Unfortunately, the BuildStatement is defined in
1295 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1296 // because this would cause circular dependency. So, until we move aquery processing
1297 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001298 switch buildStatement.Mnemonic {
1299 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001300 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1301 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001302 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001303 // build-runfiles arguments are the manifest file and the target directory
1304 // where it creates the symlink tree according to this manifest (and then
1305 // writes the MANIFEST file to it).
1306 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1307 outManifestPath := outManifest.String()
1308 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1309 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1310 }
1311 outDir := filepath.Dir(outManifestPath)
1312 ctx.Build(pctx, BuildParams{
1313 Rule: buildRunfilesRule,
1314 Output: outManifest,
1315 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1316 Description: "symlink tree for " + outDir,
1317 Args: map[string]string{
1318 "outDir": outDir,
1319 },
1320 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001321 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001322 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001323 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001324 }
1325}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001326
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001327// Register bazel-owned build statements (obtained from the aquery invocation).
Liz Kammera4655a92023-02-10 17:17:28 -05001328func createCommand(cmd *RuleBuilderCommand, buildStatement *bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001329 // executionRoot is the action cwd.
1330 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1331
1332 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1333 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001334 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001335 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001336 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001337 }
1338 cmd.Text("&&")
1339 }
1340
1341 for _, pair := range buildStatement.Env {
1342 // Set per-action env variables, if any.
1343 cmd.Flag(pair.Key + "=" + pair.Value)
1344 }
1345
1346 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001347 if len(buildStatement.Command) > 16*1024 {
1348 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1349 WriteFileRule(ctx, commandFile, buildStatement.Command)
1350
1351 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1352 } else {
1353 cmd.Text(buildStatement.Command)
1354 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001355
1356 for _, outputPath := range buildStatement.OutputPaths {
1357 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1358 }
1359 for _, inputPath := range buildStatement.InputPaths {
1360 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1361 }
1362 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1363 otherDepsetName := bazelDepsetName(inputDepsetHash)
1364 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1365 }
1366
1367 if depfile := buildStatement.Depfile; depfile != nil {
1368 // The paths in depfile are relative to `executionRoot`.
1369 // Hence, they need to be corrected by replacing "bazel-out"
1370 // with the full `bazelOutDir`.
1371 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1372 // would be deemed missing.
1373 // (Note: The regexp uses a capture group because the version of sed
1374 // does not support a look-behind pattern.)
1375 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1376 bazelOutDir, *depfile)
1377 cmd.Text(replacement)
1378 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1379 }
1380
1381 for _, symlinkPath := range buildStatement.SymlinkPaths {
1382 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1383 }
1384}
1385
Chris Parsons8d6e4332021-02-22 16:13:50 -05001386func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001387 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001388}
1389
Chris Parsons787fb362021-10-14 18:43:51 -04001390func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001391 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001392 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001393 if key.configKey.osType.Class == Device {
1394 // For the generic Android, the expected result is "target|android", which
1395 // corresponds to the product_variable_config named "android_target" in
1396 // build/bazel/platforms/BUILD.bazel.
1397 arch = "target"
1398 } else {
1399 // Use host platform, which is currently hardcoded to be x86_64.
1400 arch = "x86_64"
1401 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001402 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001403 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001404 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001405 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001406 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001407 }
Yu Liue4312402023-01-18 09:15:31 -08001408 keyString := arch + "|" + osName
1409 if key.configKey.apexKey.WithinApex {
1410 keyString += "|" + withinApexToString(key.configKey.apexKey.WithinApex)
1411 }
1412
1413 if len(key.configKey.apexKey.ApexSdkVersion) > 0 {
1414 keyString += "|" + key.configKey.apexKey.ApexSdkVersion
1415 }
1416
1417 return keyString
Chris Parsons787fb362021-10-14 18:43:51 -04001418}
1419
Chris Parsonsf874e462022-05-10 13:50:12 -04001420func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001421 return configKey{
1422 // use string because Arch is not a valid key in go
1423 arch: ctx.Arch().String(),
1424 osType: ctx.Os(),
1425 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001426}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001427
Yu Liue4312402023-01-18 09:15:31 -08001428func GetConfigKeyApexVariant(ctx BaseModuleContext, apexKey *ApexConfigKey) configKey {
1429 configKey := GetConfigKey(ctx)
1430
1431 if apexKey != nil {
1432 configKey.apexKey = ApexConfigKey{
1433 WithinApex: apexKey.WithinApex,
1434 ApexSdkVersion: apexKey.ApexSdkVersion,
1435 }
1436 }
1437
1438 return configKey
1439}
1440
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001441func bazelDepsetName(contentHash string) string {
1442 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001443}
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001444
1445func EnvironmentVarsFile(config Config) string {
1446 return fmt.Sprintf(bazel.GeneratedBazelFileWarning+`
1447_env = %s
1448
1449env = _env
1450`,
1451 starlark_fmt.PrintStringList(allowedBazelEnvironmentVars, 0),
1452 )
1453}