blob: d71eca2fa632300d21a1840a4ada96d4ab2e5d89 [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
Chris Parsonsf874e462022-05-10 13:50:12 -0400190 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400191
192 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800193 // queued in the BazelContext. The ctx argument is optional and is only
194 // used for performance data collection
Liz Kammer690fbac2023-02-10 11:11:17 -0500195 InvokeBazel(config Config, ctx invokeBazelContext) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400196
Chris Parsonsad876012022-08-20 14:48:32 -0400197 // Returns true if Bazel handling is enabled for the module with the given name.
198 // Note that this only implies "bazel mixed build" allowlisting. The caller
199 // should independently verify the module is eligible for Bazel handling
200 // (for example, that it is MixedBuildBuildable).
Yu Liue4312402023-01-18 09:15:31 -0800201 IsModuleNameAllowed(moduleName string, withinApex bool) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500202
Yu Liubfb23622023-02-22 10:42:15 -0800203 IsModuleDclaAllowed(moduleName string) bool
204
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500205 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
206 OutputBase() string
207
208 // Returns build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500209 BuildStatementsToRegister() []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400210
211 // Returns the depsets defined in Bazel's aquery response.
212 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400213}
214
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400215type bazelRunner interface {
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000216 issueBazelCommand(cmdRequest bazel.CmdRequest, paths *bazelPaths, eventHandler *metrics.EventHandler) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400217}
218
219type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000220 homeDir string
221 bazelPath string
222 outputBase string
223 workspaceDir string
224 soongOutDir string
225 metricsDir string
226 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400227}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400228
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400229// A context object which tracks queued requests that need to be made to Bazel,
230// and their results after the requests have been made.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800231type mixedBuildBazelContext struct {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400232 bazelRunner
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500233 paths *bazelPaths
234 // cquery requests that have not yet been issued to Bazel. This list is maintained
235 // in a sorted state, and is guaranteed to have no duplicates.
236 requests []cqueryKey
237 requestMutex sync.Mutex // requests can be written in parallel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400238
239 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500240
241 // Build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500242 buildStatements []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400243
244 // Depsets which should be used for Bazel's build statements.
245 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400246
247 // Per-module allowlist/denylist functionality to control whether analysis of
248 // modules are handled by Bazel. For modules which do not have a Bazel definition
249 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
250 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
251 // Per-module denylist to opt modules out of bazel handling.
252 bazelDisabledModules map[string]bool
253 // Per-module allowlist to opt modules in to bazel handling.
254 bazelEnabledModules map[string]bool
Yu Liue4312402023-01-18 09:15:31 -0800255 // DCLA modules are enabled when used in apex.
256 bazelDclaEnabledModules map[string]bool
Chris Parsonsad876012022-08-20 14:48:32 -0400257 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
258 modulesDefaultToBazel bool
Cole Faustb85d1a12022-11-08 18:14:01 -0800259
260 targetProduct string
261 targetBuildVariant string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400262}
263
Sasha Smundak39a301c2022-12-29 17:11:49 -0800264var _ BazelContext = &mixedBuildBazelContext{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400265
266// A bazel context to use when Bazel is disabled.
267type noopBazelContext struct{}
268
269var _ BazelContext = noopBazelContext{}
270
271// A bazel context to use for tests.
272type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400273 OutputBaseDir string
274
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000275 LabelToOutputFiles map[string][]string
276 LabelToCcInfo map[string]cquery.CcInfo
277 LabelToPythonBinary map[string]string
Liz Kammerbe6a7122022-11-04 16:05:11 -0400278 LabelToApexInfo map[string]cquery.ApexInfo
Sasha Smundakedd16662022-10-07 14:44:50 -0700279 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
Yu Liue4312402023-01-18 09:15:31 -0800280
281 BazelRequests map[string]bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400282}
283
Yu Liue4312402023-01-18 09:15:31 -0800284func (m MockBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
285 key := BuildMockBazelContextRequestKey(label, requestType, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
286 if m.BazelRequests == nil {
287 m.BazelRequests = make(map[string]bool)
288 }
289 m.BazelRequests[key] = true
Chris Parsons8d6e4332021-02-22 16:13:50 -0500290}
291
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700292func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500293 result, ok := m.LabelToOutputFiles[label]
294 if !ok {
295 return []string{}, fmt.Errorf("no target with label %q in LabelToOutputFiles", label)
296 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400297 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400298}
299
Yu Liue4312402023-01-18 09:15:31 -0800300func (m MockBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500301 result, ok := m.LabelToCcInfo[label]
302 if !ok {
Yu Liue4312402023-01-18 09:15:31 -0800303 key := BuildMockBazelContextResultKey(label, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
304 result, ok = m.LabelToCcInfo[key]
305 if !ok {
306 return cquery.CcInfo{}, fmt.Errorf("no target with label %q in LabelToCcInfo", label)
307 }
Sam Delmericoce39f832023-01-23 14:04:24 -0500308 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400309 return result, nil
310}
311
Liz Kammerbe6a7122022-11-04 16:05:11 -0400312func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500313 result, ok := m.LabelToApexInfo[label]
314 if !ok {
315 return cquery.ApexInfo{}, fmt.Errorf("no target with label %q in LabelToApexInfo", label)
316 }
Liz Kammer0e255ef2022-11-04 16:07:04 -0400317 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700318}
319
Sasha Smundakedd16662022-10-07 14:44:50 -0700320func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500321 result, ok := m.LabelToCcBinary[label]
322 if !ok {
323 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no target with label %q in LabelToCcBinary", label)
324 }
Sasha Smundakedd16662022-10-07 14:44:50 -0700325 return result, nil
326}
327
Liz Kammer690fbac2023-02-10 11:11:17 -0500328func (m MockBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400329 panic("unimplemented")
330}
331
Yu Liue4312402023-01-18 09:15:31 -0800332func (m MockBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400333 return true
334}
335
Yu Liubfb23622023-02-22 10:42:15 -0800336func (m MockBazelContext) IsModuleDclaAllowed(_ string) bool {
337 return true
338}
339
Liz Kammera92e8442021-04-07 20:25:21 -0400340func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500341
Liz Kammera4655a92023-02-10 17:17:28 -0500342func (m MockBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
343 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500344}
345
Chris Parsons1a7aca02022-04-25 22:35:15 -0400346func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
347 return []bazel.AqueryDepset{}
348}
349
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400350var _ BazelContext = MockBazelContext{}
351
Yu Liue4312402023-01-18 09:15:31 -0800352func BuildMockBazelContextRequestKey(label string, request cqueryRequest, arch string, osType OsType, apexKey ApexConfigKey) string {
353 cfgKey := configKey{
354 arch: arch,
355 osType: osType,
356 apexKey: apexKey,
357 }
358
359 return strings.Join([]string{label, request.Name(), cfgKey.String()}, "_")
360}
361
362func BuildMockBazelContextResultKey(label string, 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, cfgKey.String()}, "_")
370}
371
Sasha Smundak39a301c2022-12-29 17:11:49 -0800372func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400373 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400374 bazelCtx.requestMutex.Lock()
375 defer bazelCtx.requestMutex.Unlock()
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500376
377 // Insert key into requests, maintaining the sort, and only if it's not duplicate.
378 keyString := key.String()
379 foundEqual := false
380 notLessThanKeyString := func(i int) bool {
381 s := bazelCtx.requests[i].String()
382 v := strings.Compare(s, keyString)
383 if v == 0 {
384 foundEqual = true
385 }
386 return v >= 0
387 }
388 targetIndex := sort.Search(len(bazelCtx.requests), notLessThanKeyString)
389 if foundEqual {
390 return
391 }
392
393 if targetIndex == len(bazelCtx.requests) {
394 bazelCtx.requests = append(bazelCtx.requests, key)
395 } else {
396 bazelCtx.requests = append(bazelCtx.requests[:targetIndex+1], bazelCtx.requests[targetIndex:]...)
397 bazelCtx.requests[targetIndex] = key
398 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400399}
400
Sasha Smundak39a301c2022-12-29 17:11:49 -0800401func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400402 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400403 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500404 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400405
Chris Parsonsf874e462022-05-10 13:50:12 -0400406 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400407 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400408 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400409}
410
Sasha Smundak39a301c2022-12-29 17:11:49 -0800411func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400412 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400413 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000414 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400415 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000416 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400417 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 +0000418}
419
Sasha Smundak39a301c2022-12-29 17:11:49 -0800420func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400421 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700422 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500423 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700424 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400425 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700426}
427
Sasha Smundak39a301c2022-12-29 17:11:49 -0800428func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700429 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
430 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500431 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700432 }
433 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
434}
435
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700436func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500437 panic("unimplemented")
438}
439
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700440func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500441 panic("unimplemented")
442}
443
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700444func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400445 panic("unimplemented")
446}
447
Liz Kammerbe6a7122022-11-04 16:05:11 -0400448func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700449 panic("unimplemented")
450}
451
Sasha Smundakedd16662022-10-07 14:44:50 -0700452func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
453 //TODO implement me
454 panic("implement me")
455}
456
Liz Kammer690fbac2023-02-10 11:11:17 -0500457func (n noopBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400458 panic("unimplemented")
459}
460
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500461func (m noopBazelContext) OutputBase() string {
462 return ""
463}
464
Yu Liue4312402023-01-18 09:15:31 -0800465func (n noopBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400466 return false
467}
468
Yu Liubfb23622023-02-22 10:42:15 -0800469func (n noopBazelContext) IsModuleDclaAllowed(_ string) bool {
470 return false
471}
472
Liz Kammera4655a92023-02-10 17:17:28 -0500473func (m noopBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
474 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500475}
476
Chris Parsons1a7aca02022-04-25 22:35:15 -0400477func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
478 return []bazel.AqueryDepset{}
479}
480
Yu Liu6a7940c2023-05-09 17:12:22 -0700481func AddToStringSet(set map[string]bool, items []string) {
Yu Liue4312402023-01-18 09:15:31 -0800482 for _, item := range items {
483 set[item] = true
484 }
485}
486
Cole Faust705968d2022-12-14 11:32:05 -0800487func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400488 disabledModules := map[string]bool{}
489 enabledModules := map[string]bool{}
490
Cole Faust705968d2022-12-14 11:32:05 -0800491 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400492 case BazelProdMode:
Yu Liu6a7940c2023-05-09 17:12:22 -0700493 AddToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800494 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000495 enabledModules[enabledAdHocModule] = true
496 }
MarkDacekb78465d2022-10-18 20:10:16 +0000497 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400498 // Staging mode includes all prod modules plus all staging modules.
Yu Liu6a7940c2023-05-09 17:12:22 -0700499 AddToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
500 AddToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800501 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000502 enabledModules[enabledAdHocModule] = true
503 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400504 case BazelDevMode:
Yu Liu6a7940c2023-05-09 17:12:22 -0700505 AddToStringSet(disabledModules, allowlists.MixedBuildsDisabledList)
Chris Parsonsef615e52022-08-18 22:04:11 -0400506 default:
Cole Faust705968d2022-12-14 11:32:05 -0800507 panic("Expected BazelProdMode, BazelStagingMode, or BazelDevMode")
508 }
509 return enabledModules, disabledModules
510}
511
512func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
513 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
514 enabledList := make([]string, 0, len(enabledModules))
515 for module := range enabledModules {
516 if !disabledModules[module] {
517 enabledList = append(enabledList, module)
518 }
519 }
520 sort.Strings(enabledList)
521 return enabledList
522}
523
524func NewBazelContext(c *config) (BazelContext, error) {
525 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode && c.BuildMode != BazelDevMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400526 return noopBazelContext{}, nil
527 }
528
Cole Faust705968d2022-12-14 11:32:05 -0800529 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
530
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800531 paths := bazelPaths{
532 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400533 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800534 var missing []string
535 vars := []struct {
536 name string
537 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000538
539 // True if the environment variable needs to be tracked so that changes to the variable
540 // cause the ninja file to be regenerated, false otherwise. False should only be set for
541 // environment variables that have no effect on the generated ninja file.
542 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800543 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000544 {"BAZEL_HOME", &paths.homeDir, true},
545 {"BAZEL_PATH", &paths.bazelPath, true},
546 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
547 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
548 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
549 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800550 }
551 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000552 if v.track {
553 if s := c.Getenv(v.name); len(s) > 1 {
554 *v.ptr = s
555 continue
556 }
557 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800558 *v.ptr = s
559 } else {
560 missing = append(missing, v.name)
561 }
562 }
563 if len(missing) > 0 {
564 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
565 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800566
567 targetBuildVariant := "user"
568 if c.Eng() {
569 targetBuildVariant = "eng"
570 } else if c.Debuggable() {
571 targetBuildVariant = "userdebug"
572 }
573 targetProduct := "unknown"
574 if c.HasDeviceProduct() {
575 targetProduct = c.DeviceProduct()
576 }
Yu Liue4312402023-01-18 09:15:31 -0800577 dclaMixedBuildsEnabledList := []string{}
578 if c.BuildMode == BazelProdMode {
579 dclaMixedBuildsEnabledList = allowlists.ProdDclaMixedBuildsEnabledList
580 } else if c.BuildMode == BazelStagingMode {
581 dclaMixedBuildsEnabledList = append(allowlists.ProdDclaMixedBuildsEnabledList,
582 allowlists.StagingDclaMixedBuildsEnabledList...)
583 }
584 dclaEnabledModules := map[string]bool{}
Yu Liu6a7940c2023-05-09 17:12:22 -0700585 AddToStringSet(dclaEnabledModules, dclaMixedBuildsEnabledList)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800586 return &mixedBuildBazelContext{
Chris Parsons9402ca82023-02-23 17:28:06 -0500587 bazelRunner: &builtinBazelRunner{c.UseBazelProxy, absolutePath(c.outDir)},
Yu Liue4312402023-01-18 09:15:31 -0800588 paths: &paths,
589 modulesDefaultToBazel: c.BuildMode == BazelDevMode,
590 bazelEnabledModules: enabledModules,
591 bazelDisabledModules: disabledModules,
592 bazelDclaEnabledModules: dclaEnabledModules,
593 targetProduct: targetProduct,
594 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400595 }, nil
596}
597
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400598func (p *bazelPaths) BazelMetricsDir() string {
599 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000600}
601
Yu Liue4312402023-01-18 09:15:31 -0800602func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string, withinApex bool) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400603 if context.bazelDisabledModules[moduleName] {
604 return false
605 }
606 if context.bazelEnabledModules[moduleName] {
607 return true
608 }
Yu Liubfb23622023-02-22 10:42:15 -0800609 if withinApex && context.IsModuleDclaAllowed(moduleName) {
Yu Liue4312402023-01-18 09:15:31 -0800610 return true
611 }
612
Chris Parsonsad876012022-08-20 14:48:32 -0400613 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400614}
615
Yu Liubfb23622023-02-22 10:42:15 -0800616func (context *mixedBuildBazelContext) IsModuleDclaAllowed(moduleName string) bool {
617 return context.bazelDclaEnabledModules[moduleName]
618}
619
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400620func pwdPrefix() string {
621 // Darwin doesn't have /proc
622 if runtime.GOOS != "darwin" {
623 return "PWD=/proc/self/cwd"
624 }
625 return ""
626}
627
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400628type bazelCommand struct {
629 command string
630 // query or label
631 expression string
632}
633
Chris Parsons9402ca82023-02-23 17:28:06 -0500634type builtinBazelRunner struct {
635 useBazelProxy bool
636 outDir string
637}
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400638
Chris Parsons808d84c2021-03-09 20:43:32 -0500639// Issues the given bazel command with given build label and additional flags.
640// Returns (stdout, stderr, error). The first and second return values are strings
641// containing the stdout and stderr of the run command, and an error is returned if
642// the invocation returned an error code.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000643func (r *builtinBazelRunner) issueBazelCommand(cmdRequest bazel.CmdRequest, paths *bazelPaths, eventHandler *metrics.EventHandler) (string, string, error) {
Chris Parsons9402ca82023-02-23 17:28:06 -0500644 if r.useBazelProxy {
645 eventHandler.Begin("client_proxy")
646 defer eventHandler.End("client_proxy")
647 proxyClient := bazel.NewProxyClient(r.outDir)
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000648 resp, err := proxyClient.IssueCommand(cmdRequest)
Chris Parsons9402ca82023-02-23 17:28:06 -0500649
650 if err != nil {
651 return "", "", err
652 }
653 if len(resp.ErrorString) > 0 {
654 return "", "", fmt.Errorf(resp.ErrorString)
655 }
656 return resp.Stdout, resp.Stderr, nil
Jason Wu52cd1942022-09-08 15:37:57 +0000657 } else {
Chris Parsons9402ca82023-02-23 17:28:06 -0500658 eventHandler.Begin("bazel command")
659 defer eventHandler.End("bazel command")
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000660
661 stdout, stderr, err := bazel.ExecBazel(paths.bazelPath, absolutePath(paths.syntheticWorkspaceDir()), cmdRequest)
662 return string(stdout), string(stderr), err
Jason Wu52cd1942022-09-08 15:37:57 +0000663 }
664}
665
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000666func (context *mixedBuildBazelContext) createBazelCommand(config Config, runName bazel.RunName, command bazelCommand,
667 extraFlags ...string) bazel.CmdRequest {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000668 cmdFlags := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000669 "--output_base=" + absolutePath(context.paths.outputBase),
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000670 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700671 command.expression,
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000672 "--profile=" + shared.BazelMetricsFilename(context.paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400673
Cole Faustb85d1a12022-11-08 18:14:01 -0800674 // We don't need to set --host_platforms because it's set in bazelrc files
675 // that the bazel shell script wrapper passes
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700676
Jingwen Chen583ab212023-05-30 09:45:23 +0000677 // Optimize Ninja rebuilds by ensuring Bazel write into product-agnostic
678 // output paths for the configured targets that shouldn't be affected by
679 // TARGET_PRODUCT. Otherwise product agnostic modules will be rebuilt by
680 // Ninja when the product changes, unconditionally.
681 //
682 // For example, Mainline APEXes should be identical regardless of the
683 // product (modulo arch/cpu).
684 //
685 // This flag forcibly disables the platform prefix in the intermediate
686 // outputs during a mixed build.
687 "--noexperimental_platform_in_output_dir",
688
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700689 // Suppress noise
690 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500691 "--noshow_progress",
692 "--norun_validations",
693 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400694 cmdFlags = append(cmdFlags, extraFlags...)
695
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700696 extraEnv := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000697 "HOME=" + context.paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200698 pwdPrefix(),
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000699 "BUILD_DIR=" + absolutePath(context.paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700700 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000701 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000702 "OUT_DIR=" + absolutePath(context.paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500703 // Disables local host detection of gcc; toolchain information is defined
704 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700705 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
706 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500707 for _, envvar := range allowedBazelEnvironmentVars {
708 val := config.Getenv(envvar)
709 if val == "" {
710 continue
711 }
712 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
713 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000714 envVars := append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400715
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000716 return bazel.CmdRequest{cmdFlags, envVars}
Jason Wu52cd1942022-09-08 15:37:57 +0000717}
718
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000719func (context *mixedBuildBazelContext) printableCqueryCommand(bazelCmd bazel.CmdRequest) string {
720 args := append([]string{context.paths.bazelPath}, bazelCmd.Argv...)
721 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(args, "\" \"") + "\""
Jason Wu52cd1942022-09-08 15:37:57 +0000722 return outputString
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400723}
724
Sasha Smundak39a301c2022-12-29 17:11:49 -0800725func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500726 // TODO(cparsons): Define configuration transitions programmatically based
727 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400728 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500729#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400730# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500731#####################################################
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400732def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800733 if attr.os == "android" and attr.arch == "target":
Jingwen Chen583ab212023-05-30 09:45:23 +0000734 target = "current_product-{VARIANT}"
Cole Faustb85d1a12022-11-08 18:14:01 -0800735 else:
Jingwen Chen583ab212023-05-30 09:45:23 +0000736 target = "current_product-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Yu Liue4312402023-01-18 09:15:31 -0800737 apex_name = ""
738 if attr.within_apex:
739 # //build/bazel/rules/apex:apex_name has to be set to a non_empty value,
740 # otherwise //build/bazel/rules/apex:non_apex will be true and the
741 # "-D__ANDROID_APEX__" compiler flag will be missing. Apex_name is used
742 # in some validation on bazel side which don't really apply in mixed
743 # build because soong will do the work, so we just set it to a fixed
744 # value here.
745 apex_name = "dcla_apex"
746 outputs = {
Jingwen Chen583ab212023-05-30 09:45:23 +0000747 "//command_line_option:platforms": "@soong_injection//product_config_platforms:%s" % target,
Yu Liue4312402023-01-18 09:15:31 -0800748 "@//build/bazel/rules/apex:within_apex": attr.within_apex,
749 "@//build/bazel/rules/apex:min_sdk_version": attr.apex_sdk_version,
750 "@//build/bazel/rules/apex:apex_name": apex_name,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500751 }
752
Yu Liue4312402023-01-18 09:15:31 -0800753 return outputs
754
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400755_config_node_transition = transition(
756 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500757 inputs = [],
758 outputs = [
759 "//command_line_option:platforms",
Yu Liue4312402023-01-18 09:15:31 -0800760 "@//build/bazel/rules/apex:within_apex",
761 "@//build/bazel/rules/apex:min_sdk_version",
762 "@//build/bazel/rules/apex:apex_name",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500763 ],
764)
765
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400766def _passthrough_rule_impl(ctx):
767 return [DefaultInfo(files = depset(ctx.files.deps))]
768
769config_node = rule(
770 implementation = _passthrough_rule_impl,
771 attrs = {
Yu Liue4312402023-01-18 09:15:31 -0800772 "arch" : attr.string(mandatory = True),
773 "os" : attr.string(mandatory = True),
774 "within_apex" : attr.bool(default = False),
775 "apex_sdk_version" : attr.string(mandatory = True),
776 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400777 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
778 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500779)
780
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400781
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500782# Rule representing the root of the build, to depend on all Bazel targets that
783# are required for the build. Building this target will build the entire Bazel
784# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400785mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400786 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500787 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400788 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500789 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400790)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500791
792def _phony_root_impl(ctx):
793 return []
794
795# Rule to depend on other targets but build nothing.
796# This is useful as follows: building a target of this rule will generate
797# symlink forests for all dependencies of the target, without executing any
798# actions of the build.
799phony_root = rule(
800 implementation = _phony_root_impl,
801 attrs = {"deps" : attr.label_list()},
802)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400803`
Cole Faustb85d1a12022-11-08 18:14:01 -0800804
805 productReplacer := strings.NewReplacer(
806 "{PRODUCT}", context.targetProduct,
807 "{VARIANT}", context.targetBuildVariant)
808
809 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400810}
811
Sasha Smundak39a301c2022-12-29 17:11:49 -0800812func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500813 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
814 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400815 formatString := `
816# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400817load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
818
819%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400820
821mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400822 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000823 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400824)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500825
826phony_root(name = "phonyroot",
827 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000828 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500829)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400830`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400831 configNodeFormatString := `
832config_node(name = "%s",
833 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400834 os = "%s",
Yu Liue4312402023-01-18 09:15:31 -0800835 within_apex = %s,
836 apex_sdk_version = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400837 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000838 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400839)
840`
841
842 configNodesSection := ""
843
Chris Parsons787fb362021-10-14 18:43:51 -0400844 labelsByConfig := map[string][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500845
846 for _, val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200847 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400848 configString := getConfigString(val)
849 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400850 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400851
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500852 // Configs need to be sorted to maintain determinism of the BUILD file.
853 sortedConfigs := make([]string, 0, len(labelsByConfig))
854 for val := range labelsByConfig {
855 sortedConfigs = append(sortedConfigs, val)
856 }
857 sort.Slice(sortedConfigs, func(i, j int) bool { return sortedConfigs[i] < sortedConfigs[j] })
858
Jingwen Chen1e347862021-09-02 12:11:49 +0000859 allLabels := []string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500860 for _, configString := range sortedConfigs {
861 labels := labelsByConfig[configString]
Chris Parsons787fb362021-10-14 18:43:51 -0400862 configTokens := strings.Split(configString, "|")
Yu Liue4312402023-01-18 09:15:31 -0800863 if len(configTokens) < 2 {
Chris Parsons787fb362021-10-14 18:43:51 -0400864 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000865 }
Chris Parsons787fb362021-10-14 18:43:51 -0400866 archString := configTokens[0]
867 osString := configTokens[1]
Yu Liue4312402023-01-18 09:15:31 -0800868 withinApex := "False"
869 apexSdkVerString := ""
Chris Parsons787fb362021-10-14 18:43:51 -0400870 targetString := fmt.Sprintf("%s_%s", osString, archString)
Yu Liue4312402023-01-18 09:15:31 -0800871 if len(configTokens) > 2 {
872 targetString += "_" + configTokens[2]
873 if configTokens[2] == withinApexToString(true) {
874 withinApex = "True"
875 }
876 }
877 if len(configTokens) > 3 {
878 targetString += "_" + configTokens[3]
879 apexSdkVerString = configTokens[3]
880 }
Chris Parsons787fb362021-10-14 18:43:51 -0400881 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
882 labelsString := strings.Join(labels, ",\n ")
Yu Liue4312402023-01-18 09:15:31 -0800883 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, withinApex, apexSdkVerString,
884 labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400885 }
886
Jingwen Chen1e347862021-09-02 12:11:49 +0000887 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400888}
889
Chris Parsons944e7d02021-03-11 11:08:46 -0500890func indent(original string) string {
891 result := ""
892 for _, line := range strings.Split(original, "\n") {
893 result += " " + line + "\n"
894 }
895 return result
896}
897
Chris Parsons808d84c2021-03-09 20:43:32 -0500898// Returns the file contents of the buildroot.cquery file that should be used for the cquery
899// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800900// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500901// and grouped by their request type. The data retrieved for each label depends on its
902// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800903func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400904 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons38851d82023-03-15 00:19:32 -0400905 requestTypes := []cqueryRequest{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500906 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500907 cqueryId := getCqueryId(val)
908 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
Chris Parsons38851d82023-03-15 00:19:32 -0400909 if _, seenKey := requestTypeToCqueryIdEntries[val.requestType]; !seenKey {
910 requestTypes = append(requestTypes, val.requestType)
911 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500912 requestTypeToCqueryIdEntries[val.requestType] =
913 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
914 }
915 labelRegistrationMapSection := ""
916 functionDefSection := ""
917 mainSwitchSection := ""
918
919 mapDeclarationFormatString := `
920%s = {
921 %s
922}
923`
924 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800925def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500926%s
927`
928 mainSwitchSectionFormatString := `
929 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800930 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500931`
932
Chris Parsons38851d82023-03-15 00:19:32 -0400933 for _, requestType := range requestTypes {
Chris Parsons944e7d02021-03-11 11:08:46 -0500934 labelMapName := requestType.Name() + "_Labels"
935 functionName := requestType.Name() + "_Fn"
936 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
937 labelMapName,
938 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
939 functionDefSection += fmt.Sprintf(functionDefFormatString,
940 functionName,
941 indent(requestType.StarlarkFunctionBody()))
942 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
943 labelMapName, functionName)
944 }
945
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400946 formatString := `
947# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400948
Cole Faustb85d1a12022-11-08 18:14:01 -0800949{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500950
Cole Faustb85d1a12022-11-08 18:14:01 -0800951{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500952
953def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400954 # TODO(b/199363072): filegroups and file targets aren't associated with any
955 # specific platform architecture in mixed builds. This is consistent with how
956 # Soong treats filegroups, but it may not be the case with manually-written
957 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500958 buildoptions = build_options(target)
Yu Liue4312402023-01-18 09:15:31 -0800959
Jingwen Chen8f222742021-10-07 12:02:23 +0000960 if buildoptions == None:
961 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400962 # any specific platform architecture in mixed builds, so use the host.
963 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -0800964 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500965 if len(platforms) != 1:
966 # An individual configured target should have only one platform architecture.
967 # Note that it's fine for there to be multiple architectures for the same label,
968 # but each is its own configured target.
969 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -0800970 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -0500971 if platform_name == "host":
972 return "HOST"
Jingwen Chen583ab212023-05-30 09:45:23 +0000973 if not platform_name.startswith("current_product-{TARGET_BUILD_VARIANT}"):
974 fail("expected platform name of the form 'current_product-{TARGET_BUILD_VARIANT}_android_<arch>' or 'current_product-{TARGET_BUILD_VARIANT}_linux_<arch>', but was " + str(platforms))
975 platform_name = platform_name.removeprefix("current_product-{TARGET_BUILD_VARIANT}").removeprefix("_")
Yu Liue4312402023-01-18 09:15:31 -0800976 config_key = ""
Cole Faustb85d1a12022-11-08 18:14:01 -0800977 if not platform_name:
Yu Liue4312402023-01-18 09:15:31 -0800978 config_key = "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400979 elif platform_name.startswith("android_"):
Yu Liue4312402023-01-18 09:15:31 -0800980 config_key = platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400981 elif platform_name.startswith("linux_"):
Yu Liue4312402023-01-18 09:15:31 -0800982 config_key = platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400983 else:
Jingwen Chen583ab212023-05-30 09:45:23 +0000984 fail("expected platform name of the form 'current_product-{TARGET_BUILD_VARIANT}_android_<arch>' or 'current_product-{TARGET_BUILD_VARIANT}_linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500985
Yu Liue4312402023-01-18 09:15:31 -0800986 within_apex = buildoptions.get("//build/bazel/rules/apex:within_apex")
987 apex_sdk_version = buildoptions.get("//build/bazel/rules/apex:min_sdk_version")
988
989 if within_apex:
990 config_key += "|within_apex"
991 if apex_sdk_version != None and len(apex_sdk_version) > 0:
992 config_key += "|" + apex_sdk_version
993
994 return config_key
995
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400996def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500997 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500998
Chris Parsons86dc2c22022-09-28 14:58:41 -0400999 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
1000 if id_string.startswith("//"):
1001 id_string = "@" + id_string
1002
Cole Faustb85d1a12022-11-08 18:14:01 -08001003 {MAIN_SWITCH_SECTION}
1004
Chris Parsons944e7d02021-03-11 11:08:46 -05001005 # This target was not requested via cquery, and thus must be a dependency
1006 # of a requested target.
1007 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001008`
Cole Faustb85d1a12022-11-08 18:14:01 -08001009 replacer := strings.NewReplacer(
1010 "{TARGET_PRODUCT}", context.targetProduct,
1011 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
1012 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
1013 "{FUNCTION_DEF_SECTION}", functionDefSection,
1014 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001015
Cole Faustb85d1a12022-11-08 18:14:01 -08001016 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001017}
1018
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001019// Returns a path containing build-related metadata required for interfacing
1020// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001021func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001022 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -05001023}
1024
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001025// Returns the path where the contents of the @soong_injection repository live.
1026// It is used by Soong to tell Bazel things it cannot over the command line.
1027func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001028 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001029}
1030
1031// Returns the path of the synthetic Bazel workspace that contains a symlink
1032// forest composed the whole source tree and BUILD files generated by bp2build.
1033func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001034 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001035}
1036
Jingwen Chen8c523582021-06-01 11:19:53 +00001037// Returns the path to the top level out dir ($OUT_DIR).
1038func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001039 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +00001040}
1041
Sasha Smundak4975c822022-11-16 15:28:18 -08001042const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
1043
1044var (
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001045 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
1046 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
1047 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
1048 allBazelCommands = []bazelCommand{aqueryCmd, cqueryCmd, buildCmd}
Sasha Smundak4975c822022-11-16 15:28:18 -08001049)
1050
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001051// Issues commands to Bazel to receive results for all cquery requests
1052// queued in the BazelContext.
Liz Kammer690fbac2023-02-10 11:11:17 -05001053func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx invokeBazelContext) error {
1054 eventHandler := ctx.GetEventHandler()
1055 eventHandler.Begin("bazel")
1056 defer eventHandler.End("bazel")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001057
Sasha Smundak4975c822022-11-16 15:28:18 -08001058 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
1059 if err := os.MkdirAll(metricsDir, 0777); err != nil {
1060 return err
1061 }
1062 }
1063 context.results = make(map[cqueryKey]string)
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001064 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001065 return err
1066 }
1067 if err := context.runAquery(config, ctx); err != nil {
1068 return err
1069 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001070 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001071 return err
1072 }
1073
1074 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001075 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -08001076 return nil
1077}
1078
Liz Kammer690fbac2023-02-10 11:11:17 -05001079func (context *mixedBuildBazelContext) runCquery(config Config, ctx invokeBazelContext) error {
1080 eventHandler := ctx.GetEventHandler()
1081 eventHandler.Begin("cquery")
1082 defer eventHandler.End("cquery")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001083 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +02001084 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
1085 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
1086 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -05001087 if err != nil {
1088 return err
1089 }
1090 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001091 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001092 return err
1093 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001094 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001095 return err
1096 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001097 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001098 return err
1099 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001100 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001101 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001102 return err
1103 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001104
Yu Liue4312402023-01-18 09:15:31 -08001105 extraFlags := []string{"--output=starlark", "--starlark:file=" + absolutePath(cqueryFileRelpath)}
1106 if Bool(config.productVariables.ClangCoverage) {
1107 extraFlags = append(extraFlags, "--collect_code_coverage")
1108 }
1109
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001110 cqueryCmdRequest := context.createBazelCommand(config, bazel.CqueryBuildRootRunName, cqueryCmd, extraFlags...)
1111 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCmdRequest, context.paths, eventHandler)
Wei Licbd181c2022-11-16 08:59:23 -08001112 if cqueryErr != nil {
1113 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001114 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001115 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", context.printableCqueryCommand(cqueryCmdRequest))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001116 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001117 return err
1118 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001119 cqueryResults := map[string]string{}
1120 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1121 if strings.Contains(outputLine, ">>") {
1122 splitLine := strings.SplitN(outputLine, ">>", 2)
1123 cqueryResults[splitLine[0]] = splitLine[1]
1124 }
1125 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001126 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001127 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001128 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001129 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001130 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001131 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001132 }
1133 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001134 return nil
1135}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001136
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001137func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1138 oldContents, err := os.ReadFile(path)
1139 if err != nil || !bytes.Equal(contents, oldContents) {
1140 err = os.WriteFile(path, contents, perm)
1141 }
1142 return nil
1143}
1144
Liz Kammer690fbac2023-02-10 11:11:17 -05001145func (context *mixedBuildBazelContext) runAquery(config Config, ctx invokeBazelContext) error {
1146 eventHandler := ctx.GetEventHandler()
1147 eventHandler.Begin("aquery")
1148 defer eventHandler.End("aquery")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001149 // Issue an aquery command to retrieve action information about the bazel build tree.
1150 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001151 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1152 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001153 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001154 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001155 extraFlags = append(extraFlags, "--collect_code_coverage")
1156 paths := make([]string, 0, 2)
1157 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001158 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001159 // TODO(b/259404593) convert path wildcard to regex values
1160 if p[i] == "*" {
1161 p[i] = ".*"
1162 }
1163 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001164 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1165 }
1166 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1167 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1168 }
1169 if len(paths) > 0 {
1170 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001171 }
1172 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001173 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.AqueryBuildRootRunName, aqueryCmd,
1174 extraFlags...), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001175 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001176 return err
1177 }
Liz Kammer690fbac2023-02-10 11:11:17 -05001178 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001179 return err
1180}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001181
Liz Kammer690fbac2023-02-10 11:11:17 -05001182func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx invokeBazelContext) error {
1183 eventHandler := ctx.GetEventHandler()
1184 eventHandler.Begin("symlinks")
1185 defer eventHandler.End("symlinks")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001186 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1187 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1188 // but some of symlinks may be required to resolve source dependencies of the build.
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001189 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.BazelBuildPhonyRootRunName, buildCmd), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001190 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001191}
Chris Parsonsa798d962020-10-12 23:44:08 -04001192
Liz Kammera4655a92023-02-10 17:17:28 -05001193func (context *mixedBuildBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001194 return context.buildStatements
1195}
1196
Sasha Smundak39a301c2022-12-29 17:11:49 -08001197func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001198 return context.depsets
1199}
1200
Sasha Smundak39a301c2022-12-29 17:11:49 -08001201func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001202 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001203}
1204
Chris Parsonsa798d962020-10-12 23:44:08 -04001205// Singleton used for registering BUILD file ninja dependencies (needed
1206// for correctness of builds which use Bazel.
1207func BazelSingleton() Singleton {
1208 return &bazelSingleton{}
1209}
1210
1211type bazelSingleton struct{}
1212
1213func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001214 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001215 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001216 return
1217 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001218
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001219 // Add ninja file dependencies for files which all bazel invocations require.
1220 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001221 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001222 ctx.AddNinjaFileDeps(bazelBuildList)
1223
Sasha Smundak0e87b182022-12-01 11:46:11 -08001224 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001225 if err != nil {
1226 ctx.Errorf(err.Error())
1227 }
1228 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1229 for _, file := range files {
1230 ctx.AddNinjaFileDeps(file)
1231 }
1232
Chris Parsons1a7aca02022-04-25 22:35:15 -04001233 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1234 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001235 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001236 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1237 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001238 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1239 }
1240 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001241 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1242 if artifactPath == "bazel-out/volatile-status.txt" {
1243 // See https://bazel.build/docs/user-manual#workspace-status
1244 orderOnlies = append(orderOnlies, pathInBazelOut)
1245 } else {
1246 outputs = append(outputs, pathInBazelOut)
1247 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001248 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001249 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001250 ctx.Build(pctx, BuildParams{
1251 Rule: blueprint.Phony,
1252 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1253 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001254 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001255 })
1256 }
1257
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001258 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1259 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001260 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Liz Kammera4655a92023-02-10 17:17:28 -05001261 // nil build statements are a valid case where we do not create an action because it is
1262 // unnecessary or handled by other processing
1263 if buildStatement == nil {
1264 continue
1265 }
Sasha Smundak1da064c2022-06-08 16:36:16 -07001266 if len(buildStatement.Command) > 0 {
1267 rule := NewRuleBuilder(pctx, ctx)
1268 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1269 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1270 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1271 continue
1272 }
1273 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1274 // and thus require special treatment. If BuildStatement were an interface implementing
1275 // buildRule(ctx) function, the code here would just call it.
1276 // Unfortunately, the BuildStatement is defined in
1277 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1278 // because this would cause circular dependency. So, until we move aquery processing
1279 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001280 switch buildStatement.Mnemonic {
1281 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001282 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1283 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001284 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001285 // build-runfiles arguments are the manifest file and the target directory
1286 // where it creates the symlink tree according to this manifest (and then
1287 // writes the MANIFEST file to it).
1288 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1289 outManifestPath := outManifest.String()
1290 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1291 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1292 }
1293 outDir := filepath.Dir(outManifestPath)
1294 ctx.Build(pctx, BuildParams{
1295 Rule: buildRunfilesRule,
1296 Output: outManifest,
1297 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1298 Description: "symlink tree for " + outDir,
1299 Args: map[string]string{
1300 "outDir": outDir,
1301 },
1302 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001303 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001304 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001305 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001306 }
1307}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001308
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001309// Register bazel-owned build statements (obtained from the aquery invocation).
Liz Kammera4655a92023-02-10 17:17:28 -05001310func createCommand(cmd *RuleBuilderCommand, buildStatement *bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001311 // executionRoot is the action cwd.
1312 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1313
1314 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1315 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001316 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001317 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001318 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001319 }
1320 cmd.Text("&&")
1321 }
1322
1323 for _, pair := range buildStatement.Env {
1324 // Set per-action env variables, if any.
1325 cmd.Flag(pair.Key + "=" + pair.Value)
1326 }
1327
1328 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001329 if len(buildStatement.Command) > 16*1024 {
1330 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1331 WriteFileRule(ctx, commandFile, buildStatement.Command)
1332
1333 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1334 } else {
1335 cmd.Text(buildStatement.Command)
1336 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001337
1338 for _, outputPath := range buildStatement.OutputPaths {
1339 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1340 }
1341 for _, inputPath := range buildStatement.InputPaths {
1342 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1343 }
1344 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1345 otherDepsetName := bazelDepsetName(inputDepsetHash)
1346 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1347 }
1348
1349 if depfile := buildStatement.Depfile; depfile != nil {
1350 // The paths in depfile are relative to `executionRoot`.
1351 // Hence, they need to be corrected by replacing "bazel-out"
1352 // with the full `bazelOutDir`.
1353 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1354 // would be deemed missing.
1355 // (Note: The regexp uses a capture group because the version of sed
1356 // does not support a look-behind pattern.)
1357 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1358 bazelOutDir, *depfile)
1359 cmd.Text(replacement)
1360 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1361 }
1362
1363 for _, symlinkPath := range buildStatement.SymlinkPaths {
1364 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1365 }
1366}
1367
Chris Parsons8d6e4332021-02-22 16:13:50 -05001368func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001369 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001370}
1371
Chris Parsons787fb362021-10-14 18:43:51 -04001372func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001373 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001374 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001375 if key.configKey.osType.Class == Device {
1376 // For the generic Android, the expected result is "target|android", which
1377 // corresponds to the product_variable_config named "android_target" in
1378 // build/bazel/platforms/BUILD.bazel.
1379 arch = "target"
1380 } else {
1381 // Use host platform, which is currently hardcoded to be x86_64.
1382 arch = "x86_64"
1383 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001384 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001385 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001386 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001387 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001388 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001389 }
Yu Liue4312402023-01-18 09:15:31 -08001390 keyString := arch + "|" + osName
1391 if key.configKey.apexKey.WithinApex {
1392 keyString += "|" + withinApexToString(key.configKey.apexKey.WithinApex)
1393 }
1394
1395 if len(key.configKey.apexKey.ApexSdkVersion) > 0 {
1396 keyString += "|" + key.configKey.apexKey.ApexSdkVersion
1397 }
1398
1399 return keyString
Chris Parsons787fb362021-10-14 18:43:51 -04001400}
1401
Chris Parsonsf874e462022-05-10 13:50:12 -04001402func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001403 return configKey{
1404 // use string because Arch is not a valid key in go
1405 arch: ctx.Arch().String(),
1406 osType: ctx.Os(),
1407 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001408}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001409
Yu Liue4312402023-01-18 09:15:31 -08001410func GetConfigKeyApexVariant(ctx BaseModuleContext, apexKey *ApexConfigKey) configKey {
1411 configKey := GetConfigKey(ctx)
1412
1413 if apexKey != nil {
1414 configKey.apexKey = ApexConfigKey{
1415 WithinApex: apexKey.WithinApex,
1416 ApexSdkVersion: apexKey.ApexSdkVersion,
1417 }
1418 }
1419
1420 return configKey
1421}
1422
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001423func bazelDepsetName(contentHash string) string {
1424 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001425}
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001426
1427func EnvironmentVarsFile(config Config) string {
1428 return fmt.Sprintf(bazel.GeneratedBazelFileWarning+`
1429_env = %s
1430
1431env = _env
1432`,
1433 starlark_fmt.PrintStringList(allowedBazelEnvironmentVars, 0),
1434 )
1435}