blob: 47dd161806b934cc8690e9d45673e46ca44a02d6 [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
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700677 // Suppress noise
678 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500679 "--noshow_progress",
680 "--norun_validations",
681 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400682 cmdFlags = append(cmdFlags, extraFlags...)
683
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700684 extraEnv := []string{
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000685 "HOME=" + context.paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200686 pwdPrefix(),
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000687 "BUILD_DIR=" + absolutePath(context.paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700688 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000689 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000690 "OUT_DIR=" + absolutePath(context.paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500691 // Disables local host detection of gcc; toolchain information is defined
692 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700693 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
694 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500695 for _, envvar := range allowedBazelEnvironmentVars {
696 val := config.Getenv(envvar)
697 if val == "" {
698 continue
699 }
700 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
701 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000702 envVars := append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400703
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000704 return bazel.CmdRequest{cmdFlags, envVars}
Jason Wu52cd1942022-09-08 15:37:57 +0000705}
706
Chris Parsonsc9089dc2023-04-24 16:21:27 +0000707func (context *mixedBuildBazelContext) printableCqueryCommand(bazelCmd bazel.CmdRequest) string {
708 args := append([]string{context.paths.bazelPath}, bazelCmd.Argv...)
709 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(args, "\" \"") + "\""
Jason Wu52cd1942022-09-08 15:37:57 +0000710 return outputString
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400711}
712
Sasha Smundak39a301c2022-12-29 17:11:49 -0800713func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500714 // TODO(cparsons): Define configuration transitions programmatically based
715 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400716 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500717#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400718# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500719#####################################################
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400720def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800721 if attr.os == "android" and attr.arch == "target":
722 target = "{PRODUCT}-{VARIANT}"
723 else:
724 target = "{PRODUCT}-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Yu Liue4312402023-01-18 09:15:31 -0800725 apex_name = ""
726 if attr.within_apex:
727 # //build/bazel/rules/apex:apex_name has to be set to a non_empty value,
728 # otherwise //build/bazel/rules/apex:non_apex will be true and the
729 # "-D__ANDROID_APEX__" compiler flag will be missing. Apex_name is used
730 # in some validation on bazel side which don't really apply in mixed
731 # build because soong will do the work, so we just set it to a fixed
732 # value here.
733 apex_name = "dcla_apex"
734 outputs = {
Cole Faustb85d1a12022-11-08 18:14:01 -0800735 "//command_line_option:platforms": "@soong_injection//product_config_platforms/products/{PRODUCT}-{VARIANT}:%s" % target,
Yu Liue4312402023-01-18 09:15:31 -0800736 "@//build/bazel/rules/apex:within_apex": attr.within_apex,
737 "@//build/bazel/rules/apex:min_sdk_version": attr.apex_sdk_version,
738 "@//build/bazel/rules/apex:apex_name": apex_name,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500739 }
740
Yu Liue4312402023-01-18 09:15:31 -0800741 return outputs
742
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400743_config_node_transition = transition(
744 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500745 inputs = [],
746 outputs = [
747 "//command_line_option:platforms",
Yu Liue4312402023-01-18 09:15:31 -0800748 "@//build/bazel/rules/apex:within_apex",
749 "@//build/bazel/rules/apex:min_sdk_version",
750 "@//build/bazel/rules/apex:apex_name",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500751 ],
752)
753
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400754def _passthrough_rule_impl(ctx):
755 return [DefaultInfo(files = depset(ctx.files.deps))]
756
757config_node = rule(
758 implementation = _passthrough_rule_impl,
759 attrs = {
Yu Liue4312402023-01-18 09:15:31 -0800760 "arch" : attr.string(mandatory = True),
761 "os" : attr.string(mandatory = True),
762 "within_apex" : attr.bool(default = False),
763 "apex_sdk_version" : attr.string(mandatory = True),
764 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400765 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
766 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500767)
768
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400769
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500770# Rule representing the root of the build, to depend on all Bazel targets that
771# are required for the build. Building this target will build the entire Bazel
772# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400773mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400774 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500775 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400776 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500777 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400778)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500779
780def _phony_root_impl(ctx):
781 return []
782
783# Rule to depend on other targets but build nothing.
784# This is useful as follows: building a target of this rule will generate
785# symlink forests for all dependencies of the target, without executing any
786# actions of the build.
787phony_root = rule(
788 implementation = _phony_root_impl,
789 attrs = {"deps" : attr.label_list()},
790)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400791`
Cole Faustb85d1a12022-11-08 18:14:01 -0800792
793 productReplacer := strings.NewReplacer(
794 "{PRODUCT}", context.targetProduct,
795 "{VARIANT}", context.targetBuildVariant)
796
797 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400798}
799
Sasha Smundak39a301c2022-12-29 17:11:49 -0800800func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500801 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
802 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400803 formatString := `
804# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400805load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
806
807%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400808
809mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400810 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000811 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400812)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500813
814phony_root(name = "phonyroot",
815 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000816 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500817)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400818`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400819 configNodeFormatString := `
820config_node(name = "%s",
821 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400822 os = "%s",
Yu Liue4312402023-01-18 09:15:31 -0800823 within_apex = %s,
824 apex_sdk_version = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400825 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000826 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400827)
828`
829
830 configNodesSection := ""
831
Chris Parsons787fb362021-10-14 18:43:51 -0400832 labelsByConfig := map[string][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500833
834 for _, val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200835 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400836 configString := getConfigString(val)
837 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400838 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400839
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500840 // Configs need to be sorted to maintain determinism of the BUILD file.
841 sortedConfigs := make([]string, 0, len(labelsByConfig))
842 for val := range labelsByConfig {
843 sortedConfigs = append(sortedConfigs, val)
844 }
845 sort.Slice(sortedConfigs, func(i, j int) bool { return sortedConfigs[i] < sortedConfigs[j] })
846
Jingwen Chen1e347862021-09-02 12:11:49 +0000847 allLabels := []string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500848 for _, configString := range sortedConfigs {
849 labels := labelsByConfig[configString]
Chris Parsons787fb362021-10-14 18:43:51 -0400850 configTokens := strings.Split(configString, "|")
Yu Liue4312402023-01-18 09:15:31 -0800851 if len(configTokens) < 2 {
Chris Parsons787fb362021-10-14 18:43:51 -0400852 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000853 }
Chris Parsons787fb362021-10-14 18:43:51 -0400854 archString := configTokens[0]
855 osString := configTokens[1]
Yu Liue4312402023-01-18 09:15:31 -0800856 withinApex := "False"
857 apexSdkVerString := ""
Chris Parsons787fb362021-10-14 18:43:51 -0400858 targetString := fmt.Sprintf("%s_%s", osString, archString)
Yu Liue4312402023-01-18 09:15:31 -0800859 if len(configTokens) > 2 {
860 targetString += "_" + configTokens[2]
861 if configTokens[2] == withinApexToString(true) {
862 withinApex = "True"
863 }
864 }
865 if len(configTokens) > 3 {
866 targetString += "_" + configTokens[3]
867 apexSdkVerString = configTokens[3]
868 }
Chris Parsons787fb362021-10-14 18:43:51 -0400869 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
870 labelsString := strings.Join(labels, ",\n ")
Yu Liue4312402023-01-18 09:15:31 -0800871 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, withinApex, apexSdkVerString,
872 labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400873 }
874
Jingwen Chen1e347862021-09-02 12:11:49 +0000875 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400876}
877
Chris Parsons944e7d02021-03-11 11:08:46 -0500878func indent(original string) string {
879 result := ""
880 for _, line := range strings.Split(original, "\n") {
881 result += " " + line + "\n"
882 }
883 return result
884}
885
Chris Parsons808d84c2021-03-09 20:43:32 -0500886// Returns the file contents of the buildroot.cquery file that should be used for the cquery
887// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800888// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500889// and grouped by their request type. The data retrieved for each label depends on its
890// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800891func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400892 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons38851d82023-03-15 00:19:32 -0400893 requestTypes := []cqueryRequest{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500894 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500895 cqueryId := getCqueryId(val)
896 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
Chris Parsons38851d82023-03-15 00:19:32 -0400897 if _, seenKey := requestTypeToCqueryIdEntries[val.requestType]; !seenKey {
898 requestTypes = append(requestTypes, val.requestType)
899 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500900 requestTypeToCqueryIdEntries[val.requestType] =
901 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
902 }
903 labelRegistrationMapSection := ""
904 functionDefSection := ""
905 mainSwitchSection := ""
906
907 mapDeclarationFormatString := `
908%s = {
909 %s
910}
911`
912 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800913def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500914%s
915`
916 mainSwitchSectionFormatString := `
917 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800918 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500919`
920
Chris Parsons38851d82023-03-15 00:19:32 -0400921 for _, requestType := range requestTypes {
Chris Parsons944e7d02021-03-11 11:08:46 -0500922 labelMapName := requestType.Name() + "_Labels"
923 functionName := requestType.Name() + "_Fn"
924 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
925 labelMapName,
926 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
927 functionDefSection += fmt.Sprintf(functionDefFormatString,
928 functionName,
929 indent(requestType.StarlarkFunctionBody()))
930 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
931 labelMapName, functionName)
932 }
933
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400934 formatString := `
935# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400936
Cole Faustb85d1a12022-11-08 18:14:01 -0800937{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500938
Cole Faustb85d1a12022-11-08 18:14:01 -0800939{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500940
941def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400942 # TODO(b/199363072): filegroups and file targets aren't associated with any
943 # specific platform architecture in mixed builds. This is consistent with how
944 # Soong treats filegroups, but it may not be the case with manually-written
945 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500946 buildoptions = build_options(target)
Yu Liue4312402023-01-18 09:15:31 -0800947
Jingwen Chen8f222742021-10-07 12:02:23 +0000948 if buildoptions == None:
949 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400950 # any specific platform architecture in mixed builds, so use the host.
951 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -0800952 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500953 if len(platforms) != 1:
954 # An individual configured target should have only one platform architecture.
955 # Note that it's fine for there to be multiple architectures for the same label,
956 # but each is its own configured target.
957 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -0800958 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -0500959 if platform_name == "host":
960 return "HOST"
Cole Faustb85d1a12022-11-08 18:14:01 -0800961 if not platform_name.startswith("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}"):
962 fail("expected platform name of the form '{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}_android_<arch>' or '{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}_linux_<arch>', but was " + str(platforms))
963 platform_name = platform_name.removeprefix("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}").removeprefix("_")
Yu Liue4312402023-01-18 09:15:31 -0800964 config_key = ""
Cole Faustb85d1a12022-11-08 18:14:01 -0800965 if not platform_name:
Yu Liue4312402023-01-18 09:15:31 -0800966 config_key = "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400967 elif platform_name.startswith("android_"):
Yu Liue4312402023-01-18 09:15:31 -0800968 config_key = platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400969 elif platform_name.startswith("linux_"):
Yu Liue4312402023-01-18 09:15:31 -0800970 config_key = platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400971 else:
Cole Faustb85d1a12022-11-08 18:14:01 -0800972 fail("expected platform name of the form '{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}_android_<arch>' or '{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}_linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500973
Yu Liue4312402023-01-18 09:15:31 -0800974 within_apex = buildoptions.get("//build/bazel/rules/apex:within_apex")
975 apex_sdk_version = buildoptions.get("//build/bazel/rules/apex:min_sdk_version")
976
977 if within_apex:
978 config_key += "|within_apex"
979 if apex_sdk_version != None and len(apex_sdk_version) > 0:
980 config_key += "|" + apex_sdk_version
981
982 return config_key
983
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400984def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500985 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500986
Chris Parsons86dc2c22022-09-28 14:58:41 -0400987 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
988 if id_string.startswith("//"):
989 id_string = "@" + id_string
990
Cole Faustb85d1a12022-11-08 18:14:01 -0800991 {MAIN_SWITCH_SECTION}
992
Chris Parsons944e7d02021-03-11 11:08:46 -0500993 # This target was not requested via cquery, and thus must be a dependency
994 # of a requested target.
995 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400996`
Cole Faustb85d1a12022-11-08 18:14:01 -0800997 replacer := strings.NewReplacer(
998 "{TARGET_PRODUCT}", context.targetProduct,
999 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
1000 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
1001 "{FUNCTION_DEF_SECTION}", functionDefSection,
1002 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001003
Cole Faustb85d1a12022-11-08 18:14:01 -08001004 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001005}
1006
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001007// Returns a path containing build-related metadata required for interfacing
1008// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001009func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001010 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -05001011}
1012
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001013// Returns the path where the contents of the @soong_injection repository live.
1014// It is used by Soong to tell Bazel things it cannot over the command line.
1015func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001016 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001017}
1018
1019// Returns the path of the synthetic Bazel workspace that contains a symlink
1020// forest composed the whole source tree and BUILD files generated by bp2build.
1021func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001022 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001023}
1024
Jingwen Chen8c523582021-06-01 11:19:53 +00001025// Returns the path to the top level out dir ($OUT_DIR).
1026func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001027 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +00001028}
1029
Sasha Smundak4975c822022-11-16 15:28:18 -08001030const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
1031
1032var (
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001033 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
1034 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
1035 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
1036 allBazelCommands = []bazelCommand{aqueryCmd, cqueryCmd, buildCmd}
Sasha Smundak4975c822022-11-16 15:28:18 -08001037)
1038
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001039// Issues commands to Bazel to receive results for all cquery requests
1040// queued in the BazelContext.
Liz Kammer690fbac2023-02-10 11:11:17 -05001041func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx invokeBazelContext) error {
1042 eventHandler := ctx.GetEventHandler()
1043 eventHandler.Begin("bazel")
1044 defer eventHandler.End("bazel")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001045
Sasha Smundak4975c822022-11-16 15:28:18 -08001046 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
1047 if err := os.MkdirAll(metricsDir, 0777); err != nil {
1048 return err
1049 }
1050 }
1051 context.results = make(map[cqueryKey]string)
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001052 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001053 return err
1054 }
1055 if err := context.runAquery(config, ctx); err != nil {
1056 return err
1057 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001058 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001059 return err
1060 }
1061
1062 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001063 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -08001064 return nil
1065}
1066
Liz Kammer690fbac2023-02-10 11:11:17 -05001067func (context *mixedBuildBazelContext) runCquery(config Config, ctx invokeBazelContext) error {
1068 eventHandler := ctx.GetEventHandler()
1069 eventHandler.Begin("cquery")
1070 defer eventHandler.End("cquery")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001071 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +02001072 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
1073 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
1074 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -05001075 if err != nil {
1076 return err
1077 }
1078 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001079 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001080 return err
1081 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001082 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001083 return err
1084 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001085 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001086 return err
1087 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001088 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001089 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001090 return err
1091 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001092
Yu Liue4312402023-01-18 09:15:31 -08001093 extraFlags := []string{"--output=starlark", "--starlark:file=" + absolutePath(cqueryFileRelpath)}
1094 if Bool(config.productVariables.ClangCoverage) {
1095 extraFlags = append(extraFlags, "--collect_code_coverage")
1096 }
1097
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001098 cqueryCmdRequest := context.createBazelCommand(config, bazel.CqueryBuildRootRunName, cqueryCmd, extraFlags...)
1099 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCmdRequest, context.paths, eventHandler)
Wei Licbd181c2022-11-16 08:59:23 -08001100 if cqueryErr != nil {
1101 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001102 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001103 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", context.printableCqueryCommand(cqueryCmdRequest))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001104 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001105 return err
1106 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001107 cqueryResults := map[string]string{}
1108 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1109 if strings.Contains(outputLine, ">>") {
1110 splitLine := strings.SplitN(outputLine, ">>", 2)
1111 cqueryResults[splitLine[0]] = splitLine[1]
1112 }
1113 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001114 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001115 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001116 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001117 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001118 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001119 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001120 }
1121 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001122 return nil
1123}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001124
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001125func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1126 oldContents, err := os.ReadFile(path)
1127 if err != nil || !bytes.Equal(contents, oldContents) {
1128 err = os.WriteFile(path, contents, perm)
1129 }
1130 return nil
1131}
1132
Liz Kammer690fbac2023-02-10 11:11:17 -05001133func (context *mixedBuildBazelContext) runAquery(config Config, ctx invokeBazelContext) error {
1134 eventHandler := ctx.GetEventHandler()
1135 eventHandler.Begin("aquery")
1136 defer eventHandler.End("aquery")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001137 // Issue an aquery command to retrieve action information about the bazel build tree.
1138 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001139 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1140 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001141 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001142 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001143 extraFlags = append(extraFlags, "--collect_code_coverage")
1144 paths := make([]string, 0, 2)
1145 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001146 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001147 // TODO(b/259404593) convert path wildcard to regex values
1148 if p[i] == "*" {
1149 p[i] = ".*"
1150 }
1151 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001152 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1153 }
1154 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1155 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1156 }
1157 if len(paths) > 0 {
1158 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001159 }
1160 }
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001161 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.AqueryBuildRootRunName, aqueryCmd,
1162 extraFlags...), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001163 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001164 return err
1165 }
Liz Kammer690fbac2023-02-10 11:11:17 -05001166 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001167 return err
1168}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001169
Liz Kammer690fbac2023-02-10 11:11:17 -05001170func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx invokeBazelContext) error {
1171 eventHandler := ctx.GetEventHandler()
1172 eventHandler.Begin("symlinks")
1173 defer eventHandler.End("symlinks")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001174 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1175 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1176 // but some of symlinks may be required to resolve source dependencies of the build.
Chris Parsonsc9089dc2023-04-24 16:21:27 +00001177 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, bazel.BazelBuildPhonyRootRunName, buildCmd), context.paths, eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001178 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001179}
Chris Parsonsa798d962020-10-12 23:44:08 -04001180
Liz Kammera4655a92023-02-10 17:17:28 -05001181func (context *mixedBuildBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001182 return context.buildStatements
1183}
1184
Sasha Smundak39a301c2022-12-29 17:11:49 -08001185func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001186 return context.depsets
1187}
1188
Sasha Smundak39a301c2022-12-29 17:11:49 -08001189func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001190 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001191}
1192
Chris Parsonsa798d962020-10-12 23:44:08 -04001193// Singleton used for registering BUILD file ninja dependencies (needed
1194// for correctness of builds which use Bazel.
1195func BazelSingleton() Singleton {
1196 return &bazelSingleton{}
1197}
1198
1199type bazelSingleton struct{}
1200
1201func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001202 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001203 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001204 return
1205 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001206
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001207 // Add ninja file dependencies for files which all bazel invocations require.
1208 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001209 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001210 ctx.AddNinjaFileDeps(bazelBuildList)
1211
Sasha Smundak0e87b182022-12-01 11:46:11 -08001212 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001213 if err != nil {
1214 ctx.Errorf(err.Error())
1215 }
1216 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1217 for _, file := range files {
1218 ctx.AddNinjaFileDeps(file)
1219 }
1220
Chris Parsons1a7aca02022-04-25 22:35:15 -04001221 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1222 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001223 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001224 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1225 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001226 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1227 }
1228 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001229 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1230 if artifactPath == "bazel-out/volatile-status.txt" {
1231 // See https://bazel.build/docs/user-manual#workspace-status
1232 orderOnlies = append(orderOnlies, pathInBazelOut)
1233 } else {
1234 outputs = append(outputs, pathInBazelOut)
1235 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001236 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001237 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001238 ctx.Build(pctx, BuildParams{
1239 Rule: blueprint.Phony,
1240 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1241 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001242 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001243 })
1244 }
1245
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001246 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1247 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001248 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Liz Kammera4655a92023-02-10 17:17:28 -05001249 // nil build statements are a valid case where we do not create an action because it is
1250 // unnecessary or handled by other processing
1251 if buildStatement == nil {
1252 continue
1253 }
Sasha Smundak1da064c2022-06-08 16:36:16 -07001254 if len(buildStatement.Command) > 0 {
1255 rule := NewRuleBuilder(pctx, ctx)
1256 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1257 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1258 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1259 continue
1260 }
1261 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1262 // and thus require special treatment. If BuildStatement were an interface implementing
1263 // buildRule(ctx) function, the code here would just call it.
1264 // Unfortunately, the BuildStatement is defined in
1265 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1266 // because this would cause circular dependency. So, until we move aquery processing
1267 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001268 switch buildStatement.Mnemonic {
1269 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001270 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1271 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001272 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001273 // build-runfiles arguments are the manifest file and the target directory
1274 // where it creates the symlink tree according to this manifest (and then
1275 // writes the MANIFEST file to it).
1276 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1277 outManifestPath := outManifest.String()
1278 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1279 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1280 }
1281 outDir := filepath.Dir(outManifestPath)
1282 ctx.Build(pctx, BuildParams{
1283 Rule: buildRunfilesRule,
1284 Output: outManifest,
1285 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1286 Description: "symlink tree for " + outDir,
1287 Args: map[string]string{
1288 "outDir": outDir,
1289 },
1290 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001291 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001292 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001293 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001294 }
1295}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001296
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001297// Register bazel-owned build statements (obtained from the aquery invocation).
Liz Kammera4655a92023-02-10 17:17:28 -05001298func createCommand(cmd *RuleBuilderCommand, buildStatement *bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001299 // executionRoot is the action cwd.
1300 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1301
1302 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1303 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001304 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001305 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001306 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001307 }
1308 cmd.Text("&&")
1309 }
1310
1311 for _, pair := range buildStatement.Env {
1312 // Set per-action env variables, if any.
1313 cmd.Flag(pair.Key + "=" + pair.Value)
1314 }
1315
1316 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001317 if len(buildStatement.Command) > 16*1024 {
1318 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1319 WriteFileRule(ctx, commandFile, buildStatement.Command)
1320
1321 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1322 } else {
1323 cmd.Text(buildStatement.Command)
1324 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001325
1326 for _, outputPath := range buildStatement.OutputPaths {
1327 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1328 }
1329 for _, inputPath := range buildStatement.InputPaths {
1330 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1331 }
1332 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1333 otherDepsetName := bazelDepsetName(inputDepsetHash)
1334 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1335 }
1336
1337 if depfile := buildStatement.Depfile; depfile != nil {
1338 // The paths in depfile are relative to `executionRoot`.
1339 // Hence, they need to be corrected by replacing "bazel-out"
1340 // with the full `bazelOutDir`.
1341 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1342 // would be deemed missing.
1343 // (Note: The regexp uses a capture group because the version of sed
1344 // does not support a look-behind pattern.)
1345 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1346 bazelOutDir, *depfile)
1347 cmd.Text(replacement)
1348 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1349 }
1350
1351 for _, symlinkPath := range buildStatement.SymlinkPaths {
1352 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1353 }
1354}
1355
Chris Parsons8d6e4332021-02-22 16:13:50 -05001356func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001357 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001358}
1359
Chris Parsons787fb362021-10-14 18:43:51 -04001360func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001361 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001362 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001363 if key.configKey.osType.Class == Device {
1364 // For the generic Android, the expected result is "target|android", which
1365 // corresponds to the product_variable_config named "android_target" in
1366 // build/bazel/platforms/BUILD.bazel.
1367 arch = "target"
1368 } else {
1369 // Use host platform, which is currently hardcoded to be x86_64.
1370 arch = "x86_64"
1371 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001372 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001373 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001374 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001375 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001376 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001377 }
Yu Liue4312402023-01-18 09:15:31 -08001378 keyString := arch + "|" + osName
1379 if key.configKey.apexKey.WithinApex {
1380 keyString += "|" + withinApexToString(key.configKey.apexKey.WithinApex)
1381 }
1382
1383 if len(key.configKey.apexKey.ApexSdkVersion) > 0 {
1384 keyString += "|" + key.configKey.apexKey.ApexSdkVersion
1385 }
1386
1387 return keyString
Chris Parsons787fb362021-10-14 18:43:51 -04001388}
1389
Chris Parsonsf874e462022-05-10 13:50:12 -04001390func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001391 return configKey{
1392 // use string because Arch is not a valid key in go
1393 arch: ctx.Arch().String(),
1394 osType: ctx.Os(),
1395 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001396}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001397
Yu Liue4312402023-01-18 09:15:31 -08001398func GetConfigKeyApexVariant(ctx BaseModuleContext, apexKey *ApexConfigKey) configKey {
1399 configKey := GetConfigKey(ctx)
1400
1401 if apexKey != nil {
1402 configKey.apexKey = ApexConfigKey{
1403 WithinApex: apexKey.WithinApex,
1404 ApexSdkVersion: apexKey.ApexSdkVersion,
1405 }
1406 }
1407
1408 return configKey
1409}
1410
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001411func bazelDepsetName(contentHash string) string {
1412 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001413}
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001414
1415func EnvironmentVarsFile(config Config) string {
1416 return fmt.Sprintf(bazel.GeneratedBazelFileWarning+`
1417_env = %s
1418
1419env = _env
1420`,
1421 starlark_fmt.PrintStringList(allowedBazelEnvironmentVars, 0),
1422 )
1423}