blob: 3a459f181ec70b772cdaeaab09c2c367f4917e5b [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"
21 "os/exec"
Usta Shresthaacd5a0c2022-06-22 11:20:50 -040022 "path"
Chris Parsonsa798d962020-10-12 23:44:08 -040023 "path/filepath"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040024 "runtime"
Cole Faust705968d2022-12-14 11:32:05 -080025 "sort"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040026 "strings"
27 "sync"
Chris Parsonsa798d962020-10-12 23:44:08 -040028
Chris Parsonsad876012022-08-20 14:48:32 -040029 "android/soong/android/allowlists"
Chris Parsons944e7d02021-03-11 11:08:46 -050030 "android/soong/bazel/cquery"
Jingwen Chen1e347862021-09-02 12:11:49 +000031 "android/soong/shared"
Sam Delmericocb3c52c2023-02-03 17:40:08 -050032 "android/soong/starlark_fmt"
Liz Kammer337e9032022-08-03 15:49:43 -040033
Chris Parsons1a7aca02022-04-25 22:35:15 -040034 "github.com/google/blueprint"
Liz Kammer690fbac2023-02-10 11:11:17 -050035 "github.com/google/blueprint/metrics"
Liz Kammer8206d4f2021-03-03 16:40:52 -050036
Patrice Arruda05ab2d02020-12-12 06:24:26 +000037 "android/soong/bazel"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040038)
39
Sasha Smundak1da064c2022-06-08 16:36:16 -070040var (
Sasha Smundakc180dbd2022-07-03 14:55:58 -070041 _ = pctx.HostBinToolVariable("bazelBuildRunfilesTool", "build-runfiles")
42 buildRunfilesRule = pctx.AndroidStaticRule("bazelBuildRunfiles", blueprint.RuleParams{
43 Command: "${bazelBuildRunfilesTool} ${in} ${outDir}",
44 Depfile: "",
45 Description: "",
46 CommandDeps: []string{"${bazelBuildRunfilesTool}"},
47 }, "outDir")
Sam Delmericocb3c52c2023-02-03 17:40:08 -050048 allowedBazelEnvironmentVars = []string{
Sam Delmerico700b4d32023-02-10 16:46:28 -050049 // clang-tidy
Sam Delmericocb3c52c2023-02-03 17:40:08 -050050 "ALLOW_LOCAL_TIDY_TRUE",
51 "DEFAULT_TIDY_HEADER_DIRS",
52 "TIDY_TIMEOUT",
53 "WITH_TIDY",
54 "WITH_TIDY_FLAGS",
Sam Delmerico700b4d32023-02-10 16:46:28 -050055 "TIDY_EXTERNAL_VENDOR",
56
Sam Delmericocb3c52c2023-02-03 17:40:08 -050057 "SKIP_ABI_CHECKS",
58 "UNSAFE_DISABLE_APEX_ALLOWED_DEPS_CHECK",
59 "AUTO_ZERO_INITIALIZE",
60 "AUTO_PATTERN_INITIALIZE",
61 "AUTO_UNINITIALIZE",
62 "USE_CCACHE",
63 "LLVM_NEXT",
64 "ALLOW_UNKNOWN_WARNING_OPTION",
65
66 // Overrides the version in the apex_manifest.json. The version is unique for
67 // each branch (internal, aosp, mainline releases, dessert releases). This
68 // enables modules built on an older branch to be installed against a newer
69 // device for development purposes.
70 "OVERRIDE_APEX_MANIFEST_DEFAULT_VERSION",
71 }
Sasha Smundak1da064c2022-06-08 16:36:16 -070072)
73
Chris Parsonsf874e462022-05-10 13:50:12 -040074func init() {
75 RegisterMixedBuildsMutator(InitRegistrationContext)
76}
77
78func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammer337e9032022-08-03 15:49:43 -040079 ctx.FinalDepsMutators(func(ctx RegisterMutatorsContext) {
Chris Parsonsf874e462022-05-10 13:50:12 -040080 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
81 })
82}
83
84func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
85 if m := ctx.Module(); m.Enabled() {
86 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
87 if mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx) {
88 mixedBuildMod.QueueBazelCall(ctx)
89 }
90 }
91 }
92}
93
Liz Kammerf29df7c2021-04-02 13:37:39 -040094type cqueryRequest interface {
95 // Name returns a string name for this request type. Such request type names must be unique,
96 // and must only consist of alphanumeric characters.
97 Name() string
98
99 // StarlarkFunctionBody returns a starlark function body to process this request type.
100 // The returned string is the body of a Starlark function which obtains
101 // all request-relevant information about a target and returns a string containing
102 // this information.
103 // The function should have the following properties:
Cole Faust97d15272022-11-22 14:08:59 -0800104 // - The arguments are `target` (a configured target) and `id_string` (the label + configuration).
Liz Kammerf29df7c2021-04-02 13:37:39 -0400105 // - The return value must be a string.
106 // - The function body should not be indented outside of its own scope.
107 StarlarkFunctionBody() string
108}
109
Chris Parsons787fb362021-10-14 18:43:51 -0400110// Portion of cquery map key to describe target configuration.
111type configKey struct {
Yu Liue4312402023-01-18 09:15:31 -0800112 arch string
113 osType OsType
114 apexKey ApexConfigKey
115}
116
117type ApexConfigKey struct {
118 WithinApex bool
119 ApexSdkVersion string
120}
121
122func (c ApexConfigKey) String() string {
123 return fmt.Sprintf("%s_%s", withinApexToString(c.WithinApex), c.ApexSdkVersion)
124}
125
126func withinApexToString(withinApex bool) string {
127 if withinApex {
128 return "within_apex"
129 }
130 return ""
Chris Parsons787fb362021-10-14 18:43:51 -0400131}
132
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700133func (c configKey) String() string {
Yu Liue4312402023-01-18 09:15:31 -0800134 return fmt.Sprintf("%s::%s::%s", c.arch, c.osType, c.apexKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700135}
136
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400137// Map key to describe bazel cquery requests.
138type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400139 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400140 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400141 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400142}
143
Chris Parsons86dc2c22022-09-28 14:58:41 -0400144func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
145 if strings.HasPrefix(label, "//") {
146 // Normalize Bazel labels to specify main repository explicitly.
147 label = "@" + label
148 }
149 return cqueryKey{label, cqueryRequest, cfgKey}
150}
151
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700152func (c cqueryKey) String() string {
153 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700154}
155
Liz Kammer690fbac2023-02-10 11:11:17 -0500156type invokeBazelContext interface {
157 GetEventHandler() *metrics.EventHandler
158}
159
Chris Parsonsf874e462022-05-10 13:50:12 -0400160// BazelContext is a context object useful for interacting with Bazel during
161// the course of a build. Use of Bazel to evaluate part of the build graph
162// is referred to as a "mixed build". (Some modules are managed by Soong,
163// some are managed by Bazel). To facilitate interop between these build
164// subgraphs, Soong may make requests to Bazel and evaluate their responses
165// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400166type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400167 // Add a cquery request to the bazel request queue. All queued requests
168 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
169 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
170
171 // ** Cquery Results Retrieval Functions
172 // The below functions pertain to retrieving cquery results from a prior
173 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400174
175 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400176 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500177
Chris Parsons944e7d02021-03-11 11:08:46 -0500178 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400179 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400180
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000181 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400182 // TODO(b/232976601): Remove.
183 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000184
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700185 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400186 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700187
Sasha Smundakedd16662022-10-07 14:44:50 -0700188 // Returns the results of the GetCcUnstrippedInfo query
189 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
190
Chris Parsonsf874e462022-05-10 13:50:12 -0400191 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400192
193 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800194 // queued in the BazelContext. The ctx argument is optional and is only
195 // used for performance data collection
Liz Kammer690fbac2023-02-10 11:11:17 -0500196 InvokeBazel(config Config, ctx invokeBazelContext) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400197
Chris Parsonsad876012022-08-20 14:48:32 -0400198 // Returns true if Bazel handling is enabled for the module with the given name.
199 // Note that this only implies "bazel mixed build" allowlisting. The caller
200 // should independently verify the module is eligible for Bazel handling
201 // (for example, that it is MixedBuildBuildable).
Yu Liue4312402023-01-18 09:15:31 -0800202 IsModuleNameAllowed(moduleName string, withinApex bool) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500203
204 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
205 OutputBase() string
206
207 // Returns build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500208 BuildStatementsToRegister() []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400209
210 // Returns the depsets defined in Bazel's aquery response.
211 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400212}
213
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400214type bazelRunner interface {
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500215 createBazelCommand(config Config, paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) *exec.Cmd
Liz Kammer690fbac2023-02-10 11:11:17 -0500216 issueBazelCommand(bazelCmd *exec.Cmd, 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
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700312func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500313 result, ok := m.LabelToPythonBinary[label]
314 if !ok {
315 return "", fmt.Errorf("no target with label %q in LabelToPythonBinary", label)
316 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400317 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000318}
319
Liz Kammerbe6a7122022-11-04 16:05:11 -0400320func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500321 result, ok := m.LabelToApexInfo[label]
322 if !ok {
323 return cquery.ApexInfo{}, fmt.Errorf("no target with label %q in LabelToApexInfo", label)
324 }
Liz Kammer0e255ef2022-11-04 16:07:04 -0400325 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700326}
327
Sasha Smundakedd16662022-10-07 14:44:50 -0700328func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500329 result, ok := m.LabelToCcBinary[label]
330 if !ok {
331 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no target with label %q in LabelToCcBinary", label)
332 }
Sasha Smundakedd16662022-10-07 14:44:50 -0700333 return result, nil
334}
335
Liz Kammer690fbac2023-02-10 11:11:17 -0500336func (m MockBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400337 panic("unimplemented")
338}
339
Yu Liue4312402023-01-18 09:15:31 -0800340func (m MockBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400341 return true
342}
343
Liz Kammera92e8442021-04-07 20:25:21 -0400344func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500345
Liz Kammera4655a92023-02-10 17:17:28 -0500346func (m MockBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
347 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500348}
349
Chris Parsons1a7aca02022-04-25 22:35:15 -0400350func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
351 return []bazel.AqueryDepset{}
352}
353
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400354var _ BazelContext = MockBazelContext{}
355
Yu Liue4312402023-01-18 09:15:31 -0800356func BuildMockBazelContextRequestKey(label string, request cqueryRequest, arch string, osType OsType, apexKey ApexConfigKey) string {
357 cfgKey := configKey{
358 arch: arch,
359 osType: osType,
360 apexKey: apexKey,
361 }
362
363 return strings.Join([]string{label, request.Name(), cfgKey.String()}, "_")
364}
365
366func BuildMockBazelContextResultKey(label string, arch string, osType OsType, apexKey ApexConfigKey) string {
367 cfgKey := configKey{
368 arch: arch,
369 osType: osType,
370 apexKey: apexKey,
371 }
372
373 return strings.Join([]string{label, cfgKey.String()}, "_")
374}
375
Sasha Smundak39a301c2022-12-29 17:11:49 -0800376func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400377 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400378 bazelCtx.requestMutex.Lock()
379 defer bazelCtx.requestMutex.Unlock()
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500380
381 // Insert key into requests, maintaining the sort, and only if it's not duplicate.
382 keyString := key.String()
383 foundEqual := false
384 notLessThanKeyString := func(i int) bool {
385 s := bazelCtx.requests[i].String()
386 v := strings.Compare(s, keyString)
387 if v == 0 {
388 foundEqual = true
389 }
390 return v >= 0
391 }
392 targetIndex := sort.Search(len(bazelCtx.requests), notLessThanKeyString)
393 if foundEqual {
394 return
395 }
396
397 if targetIndex == len(bazelCtx.requests) {
398 bazelCtx.requests = append(bazelCtx.requests, key)
399 } else {
400 bazelCtx.requests = append(bazelCtx.requests[:targetIndex+1], bazelCtx.requests[targetIndex:]...)
401 bazelCtx.requests[targetIndex] = key
402 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400403}
404
Sasha Smundak39a301c2022-12-29 17:11:49 -0800405func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400406 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400407 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500408 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400409
Chris Parsonsf874e462022-05-10 13:50:12 -0400410 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400411 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400412 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400413}
414
Sasha Smundak39a301c2022-12-29 17:11:49 -0800415func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400416 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400417 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000418 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400419 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000420 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400421 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 +0000422}
423
Sasha Smundak39a301c2022-12-29 17:11:49 -0800424func (bazelCtx *mixedBuildBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400425 key := makeCqueryKey(label, cquery.GetPythonBinary, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400426 if rawString, ok := bazelCtx.results[key]; ok {
427 bazelOutput := strings.TrimSpace(rawString)
428 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
429 }
430 return "", fmt.Errorf("no bazel response found for %v", key)
431}
432
Sasha Smundak39a301c2022-12-29 17:11:49 -0800433func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400434 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700435 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500436 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700437 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400438 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700439}
440
Sasha Smundak39a301c2022-12-29 17:11:49 -0800441func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700442 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
443 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500444 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700445 }
446 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
447}
448
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700449func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500450 panic("unimplemented")
451}
452
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700453func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500454 panic("unimplemented")
455}
456
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700457func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400458 panic("unimplemented")
459}
460
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700461func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000462 panic("unimplemented")
463}
464
Liz Kammerbe6a7122022-11-04 16:05:11 -0400465func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700466 panic("unimplemented")
467}
468
Sasha Smundakedd16662022-10-07 14:44:50 -0700469func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
470 //TODO implement me
471 panic("implement me")
472}
473
Liz Kammer690fbac2023-02-10 11:11:17 -0500474func (n noopBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400475 panic("unimplemented")
476}
477
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500478func (m noopBazelContext) OutputBase() string {
479 return ""
480}
481
Yu Liue4312402023-01-18 09:15:31 -0800482func (n noopBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400483 return false
484}
485
Liz Kammera4655a92023-02-10 17:17:28 -0500486func (m noopBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
487 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500488}
489
Chris Parsons1a7aca02022-04-25 22:35:15 -0400490func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
491 return []bazel.AqueryDepset{}
492}
493
Yu Liue4312402023-01-18 09:15:31 -0800494func addToStringSet(set map[string]bool, items []string) {
495 for _, item := range items {
496 set[item] = true
497 }
498}
499
Cole Faust705968d2022-12-14 11:32:05 -0800500func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400501 disabledModules := map[string]bool{}
502 enabledModules := map[string]bool{}
503
Cole Faust705968d2022-12-14 11:32:05 -0800504 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400505 case BazelProdMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800506 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800507 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000508 enabledModules[enabledAdHocModule] = true
509 }
MarkDacekb78465d2022-10-18 20:10:16 +0000510 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400511 // Staging mode includes all prod modules plus all staging modules.
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800512 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
513 addToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800514 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000515 enabledModules[enabledAdHocModule] = true
516 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400517 case BazelDevMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800518 addToStringSet(disabledModules, allowlists.MixedBuildsDisabledList)
Chris Parsonsef615e52022-08-18 22:04:11 -0400519 default:
Cole Faust705968d2022-12-14 11:32:05 -0800520 panic("Expected BazelProdMode, BazelStagingMode, or BazelDevMode")
521 }
522 return enabledModules, disabledModules
523}
524
525func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
526 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
527 enabledList := make([]string, 0, len(enabledModules))
528 for module := range enabledModules {
529 if !disabledModules[module] {
530 enabledList = append(enabledList, module)
531 }
532 }
533 sort.Strings(enabledList)
534 return enabledList
535}
536
537func NewBazelContext(c *config) (BazelContext, error) {
538 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode && c.BuildMode != BazelDevMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400539 return noopBazelContext{}, nil
540 }
541
Cole Faust705968d2022-12-14 11:32:05 -0800542 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
543
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800544 paths := bazelPaths{
545 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400546 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800547 var missing []string
548 vars := []struct {
549 name string
550 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000551
552 // True if the environment variable needs to be tracked so that changes to the variable
553 // cause the ninja file to be regenerated, false otherwise. False should only be set for
554 // environment variables that have no effect on the generated ninja file.
555 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800556 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000557 {"BAZEL_HOME", &paths.homeDir, true},
558 {"BAZEL_PATH", &paths.bazelPath, true},
559 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
560 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
561 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
562 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800563 }
564 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000565 if v.track {
566 if s := c.Getenv(v.name); len(s) > 1 {
567 *v.ptr = s
568 continue
569 }
570 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800571 *v.ptr = s
572 } else {
573 missing = append(missing, v.name)
574 }
575 }
576 if len(missing) > 0 {
577 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
578 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800579
580 targetBuildVariant := "user"
581 if c.Eng() {
582 targetBuildVariant = "eng"
583 } else if c.Debuggable() {
584 targetBuildVariant = "userdebug"
585 }
586 targetProduct := "unknown"
587 if c.HasDeviceProduct() {
588 targetProduct = c.DeviceProduct()
589 }
Yu Liue4312402023-01-18 09:15:31 -0800590 dclaMixedBuildsEnabledList := []string{}
591 if c.BuildMode == BazelProdMode {
592 dclaMixedBuildsEnabledList = allowlists.ProdDclaMixedBuildsEnabledList
593 } else if c.BuildMode == BazelStagingMode {
594 dclaMixedBuildsEnabledList = append(allowlists.ProdDclaMixedBuildsEnabledList,
595 allowlists.StagingDclaMixedBuildsEnabledList...)
596 }
597 dclaEnabledModules := map[string]bool{}
598 addToStringSet(dclaEnabledModules, dclaMixedBuildsEnabledList)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800599 return &mixedBuildBazelContext{
Yu Liue4312402023-01-18 09:15:31 -0800600 bazelRunner: &builtinBazelRunner{},
601 paths: &paths,
602 modulesDefaultToBazel: c.BuildMode == BazelDevMode,
603 bazelEnabledModules: enabledModules,
604 bazelDisabledModules: disabledModules,
605 bazelDclaEnabledModules: dclaEnabledModules,
606 targetProduct: targetProduct,
607 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400608 }, nil
609}
610
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400611func (p *bazelPaths) BazelMetricsDir() string {
612 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000613}
614
Yu Liue4312402023-01-18 09:15:31 -0800615func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string, withinApex bool) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400616 if context.bazelDisabledModules[moduleName] {
617 return false
618 }
619 if context.bazelEnabledModules[moduleName] {
620 return true
621 }
Yu Liue4312402023-01-18 09:15:31 -0800622 if withinApex && context.bazelDclaEnabledModules[moduleName] {
623 return true
624 }
625
Chris Parsonsad876012022-08-20 14:48:32 -0400626 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400627}
628
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400629func pwdPrefix() string {
630 // Darwin doesn't have /proc
631 if runtime.GOOS != "darwin" {
632 return "PWD=/proc/self/cwd"
633 }
634 return ""
635}
636
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400637type bazelCommand struct {
638 command string
639 // query or label
640 expression string
641}
642
643type mockBazelRunner struct {
644 bazelCommandResults map[bazelCommand]string
Jason Wu52cd1942022-09-08 15:37:57 +0000645 // use *exec.Cmd as a key to get the bazelCommand, the map will be used in issueBazelCommand()
646 // Register createBazelCommand() invocations. Later, an
647 // issueBazelCommand() invocation can be mapped to the *exec.Cmd instance
648 // and then to the expected result via bazelCommandResults
649 tokens map[*exec.Cmd]bazelCommand
650 commands []bazelCommand
651 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400652}
653
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500654func (r *mockBazelRunner) createBazelCommand(_ Config, _ *bazelPaths, _ bazel.RunName,
Jason Wu52cd1942022-09-08 15:37:57 +0000655 command bazelCommand, extraFlags ...string) *exec.Cmd {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400656 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700657 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Jason Wu52cd1942022-09-08 15:37:57 +0000658 cmd := &exec.Cmd{}
659 if r.tokens == nil {
660 r.tokens = make(map[*exec.Cmd]bazelCommand)
661 }
662 r.tokens[cmd] = command
663 return cmd
664}
665
Liz Kammer690fbac2023-02-10 11:11:17 -0500666func (r *mockBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd, _ *metrics.EventHandler) (string, string, error) {
Jason Wu52cd1942022-09-08 15:37:57 +0000667 if command, ok := r.tokens[bazelCmd]; ok {
668 return r.bazelCommandResults[command], "", nil
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400669 }
670 return "", "", nil
671}
672
673type builtinBazelRunner struct{}
674
Chris Parsons808d84c2021-03-09 20:43:32 -0500675// Issues the given bazel command with given build label and additional flags.
676// Returns (stdout, stderr, error). The first and second return values are strings
677// containing the stdout and stderr of the run command, and an error is returned if
678// the invocation returned an error code.
Liz Kammer690fbac2023-02-10 11:11:17 -0500679func (r *builtinBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd, eventHandler *metrics.EventHandler) (string, string, error) {
680 eventHandler.Begin("bazel command")
681 defer eventHandler.End("bazel command")
Jason Wu52cd1942022-09-08 15:37:57 +0000682 stderr := &bytes.Buffer{}
683 bazelCmd.Stderr = stderr
684 if output, err := bazelCmd.Output(); err != nil {
685 return "", string(stderr.Bytes()),
Sasha Smundak0e87b182022-12-01 11:46:11 -0800686 fmt.Errorf("bazel command failed: %s\n---command---\n%s\n---env---\n%s\n---stderr---\n%s---",
687 err, bazelCmd, strings.Join(bazelCmd.Env, "\n"), stderr)
Jason Wu52cd1942022-09-08 15:37:57 +0000688 } else {
689 return string(output), string(stderr.Bytes()), nil
690 }
691}
692
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500693func (r *builtinBazelRunner) createBazelCommand(config Config, paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Jason Wu52cd1942022-09-08 15:37:57 +0000694 extraFlags ...string) *exec.Cmd {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000695 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000696 "--output_base=" + absolutePath(paths.outputBase),
697 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700698 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700699 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700700 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400701
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700702 // Set default platforms to canonicalized values for mixed builds requests.
703 // If these are set in the bazelrc, they will have values that are
704 // non-canonicalized to @sourceroot labels, and thus be invalid when
705 // referenced from the buildroot.
706 //
707 // The actual platform values here may be overridden by configuration
708 // transitions from the buildroot.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700709 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Cole Faustb85d1a12022-11-08 18:14:01 -0800710
711 // We don't need to set --host_platforms because it's set in bazelrc files
712 // that the bazel shell script wrapper passes
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700713
714 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
715 "--experimental_repository_disable_download",
716
717 // Suppress noise
718 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500719 "--noshow_progress",
720 "--norun_validations",
721 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400722 cmdFlags = append(cmdFlags, extraFlags...)
723
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400724 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200725 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700726 extraEnv := []string{
727 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200728 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700729 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700730 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000731 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700732 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500733 // Disables local host detection of gcc; toolchain information is defined
734 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700735 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
736 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500737 for _, envvar := range allowedBazelEnvironmentVars {
738 val := config.Getenv(envvar)
739 if val == "" {
740 continue
741 }
742 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
743 }
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700744 bazelCmd.Env = append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400745
Jason Wu52cd1942022-09-08 15:37:57 +0000746 return bazelCmd
747}
748
749func printableCqueryCommand(bazelCmd *exec.Cmd) string {
750 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(bazelCmd.Args, "\" \"") + "\""
751 return outputString
752
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400753}
754
Sasha Smundak39a301c2022-12-29 17:11:49 -0800755func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500756 // TODO(cparsons): Define configuration transitions programmatically based
757 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400758 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500759#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400760# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500761#####################################################
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400762def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800763 if attr.os == "android" and attr.arch == "target":
764 target = "{PRODUCT}-{VARIANT}"
765 else:
766 target = "{PRODUCT}-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Yu Liue4312402023-01-18 09:15:31 -0800767 apex_name = ""
768 if attr.within_apex:
769 # //build/bazel/rules/apex:apex_name has to be set to a non_empty value,
770 # otherwise //build/bazel/rules/apex:non_apex will be true and the
771 # "-D__ANDROID_APEX__" compiler flag will be missing. Apex_name is used
772 # in some validation on bazel side which don't really apply in mixed
773 # build because soong will do the work, so we just set it to a fixed
774 # value here.
775 apex_name = "dcla_apex"
776 outputs = {
Cole Faustb85d1a12022-11-08 18:14:01 -0800777 "//command_line_option:platforms": "@soong_injection//product_config_platforms/products/{PRODUCT}-{VARIANT}:%s" % target,
Yu Liue4312402023-01-18 09:15:31 -0800778 "@//build/bazel/rules/apex:within_apex": attr.within_apex,
779 "@//build/bazel/rules/apex:min_sdk_version": attr.apex_sdk_version,
780 "@//build/bazel/rules/apex:apex_name": apex_name,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500781 }
782
Yu Liue4312402023-01-18 09:15:31 -0800783 return outputs
784
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400785_config_node_transition = transition(
786 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500787 inputs = [],
788 outputs = [
789 "//command_line_option:platforms",
Yu Liue4312402023-01-18 09:15:31 -0800790 "@//build/bazel/rules/apex:within_apex",
791 "@//build/bazel/rules/apex:min_sdk_version",
792 "@//build/bazel/rules/apex:apex_name",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500793 ],
794)
795
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400796def _passthrough_rule_impl(ctx):
797 return [DefaultInfo(files = depset(ctx.files.deps))]
798
799config_node = rule(
800 implementation = _passthrough_rule_impl,
801 attrs = {
Yu Liue4312402023-01-18 09:15:31 -0800802 "arch" : attr.string(mandatory = True),
803 "os" : attr.string(mandatory = True),
804 "within_apex" : attr.bool(default = False),
805 "apex_sdk_version" : attr.string(mandatory = True),
806 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400807 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
808 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500809)
810
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400811
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500812# Rule representing the root of the build, to depend on all Bazel targets that
813# are required for the build. Building this target will build the entire Bazel
814# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400815mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400816 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500817 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400818 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500819 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400820)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500821
822def _phony_root_impl(ctx):
823 return []
824
825# Rule to depend on other targets but build nothing.
826# This is useful as follows: building a target of this rule will generate
827# symlink forests for all dependencies of the target, without executing any
828# actions of the build.
829phony_root = rule(
830 implementation = _phony_root_impl,
831 attrs = {"deps" : attr.label_list()},
832)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400833`
Cole Faustb85d1a12022-11-08 18:14:01 -0800834
835 productReplacer := strings.NewReplacer(
836 "{PRODUCT}", context.targetProduct,
837 "{VARIANT}", context.targetBuildVariant)
838
839 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400840}
841
Sasha Smundak39a301c2022-12-29 17:11:49 -0800842func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500843 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
844 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400845 formatString := `
846# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400847load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
848
849%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400850
851mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400852 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000853 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400854)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500855
856phony_root(name = "phonyroot",
857 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000858 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500859)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400860`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400861 configNodeFormatString := `
862config_node(name = "%s",
863 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400864 os = "%s",
Yu Liue4312402023-01-18 09:15:31 -0800865 within_apex = %s,
866 apex_sdk_version = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400867 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000868 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400869)
870`
871
872 configNodesSection := ""
873
Chris Parsons787fb362021-10-14 18:43:51 -0400874 labelsByConfig := map[string][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500875
876 for _, val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200877 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400878 configString := getConfigString(val)
879 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400880 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400881
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500882 // Configs need to be sorted to maintain determinism of the BUILD file.
883 sortedConfigs := make([]string, 0, len(labelsByConfig))
884 for val := range labelsByConfig {
885 sortedConfigs = append(sortedConfigs, val)
886 }
887 sort.Slice(sortedConfigs, func(i, j int) bool { return sortedConfigs[i] < sortedConfigs[j] })
888
Jingwen Chen1e347862021-09-02 12:11:49 +0000889 allLabels := []string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500890 for _, configString := range sortedConfigs {
891 labels := labelsByConfig[configString]
Chris Parsons787fb362021-10-14 18:43:51 -0400892 configTokens := strings.Split(configString, "|")
Yu Liue4312402023-01-18 09:15:31 -0800893 if len(configTokens) < 2 {
Chris Parsons787fb362021-10-14 18:43:51 -0400894 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000895 }
Chris Parsons787fb362021-10-14 18:43:51 -0400896 archString := configTokens[0]
897 osString := configTokens[1]
Yu Liue4312402023-01-18 09:15:31 -0800898 withinApex := "False"
899 apexSdkVerString := ""
Chris Parsons787fb362021-10-14 18:43:51 -0400900 targetString := fmt.Sprintf("%s_%s", osString, archString)
Yu Liue4312402023-01-18 09:15:31 -0800901 if len(configTokens) > 2 {
902 targetString += "_" + configTokens[2]
903 if configTokens[2] == withinApexToString(true) {
904 withinApex = "True"
905 }
906 }
907 if len(configTokens) > 3 {
908 targetString += "_" + configTokens[3]
909 apexSdkVerString = configTokens[3]
910 }
Chris Parsons787fb362021-10-14 18:43:51 -0400911 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
912 labelsString := strings.Join(labels, ",\n ")
Yu Liue4312402023-01-18 09:15:31 -0800913 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, withinApex, apexSdkVerString,
914 labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400915 }
916
Jingwen Chen1e347862021-09-02 12:11:49 +0000917 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400918}
919
Chris Parsons944e7d02021-03-11 11:08:46 -0500920func indent(original string) string {
921 result := ""
922 for _, line := range strings.Split(original, "\n") {
923 result += " " + line + "\n"
924 }
925 return result
926}
927
Chris Parsons808d84c2021-03-09 20:43:32 -0500928// Returns the file contents of the buildroot.cquery file that should be used for the cquery
929// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800930// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500931// and grouped by their request type. The data retrieved for each label depends on its
932// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800933func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400934 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500935 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500936 cqueryId := getCqueryId(val)
937 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
938 requestTypeToCqueryIdEntries[val.requestType] =
939 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
940 }
941 labelRegistrationMapSection := ""
942 functionDefSection := ""
943 mainSwitchSection := ""
944
945 mapDeclarationFormatString := `
946%s = {
947 %s
948}
949`
950 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800951def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500952%s
953`
954 mainSwitchSectionFormatString := `
955 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800956 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500957`
958
Usta Shrestha0b52d832022-02-04 21:37:39 -0500959 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500960 labelMapName := requestType.Name() + "_Labels"
961 functionName := requestType.Name() + "_Fn"
962 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
963 labelMapName,
964 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
965 functionDefSection += fmt.Sprintf(functionDefFormatString,
966 functionName,
967 indent(requestType.StarlarkFunctionBody()))
968 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
969 labelMapName, functionName)
970 }
971
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400972 formatString := `
973# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400974
Usta Shrestha79fccef2022-09-02 18:37:40 -0400975# a drop-in replacement for json.encode(), not available in cquery environment
976# TODO(cparsons): bring json module in and remove this function
977def json_encode(input):
978 # Avoiding recursion by limiting
979 # - a dict to contain anything except a dict
980 # - a list to contain only primitives
981 def encode_primitive(p):
982 t = type(p)
983 if t == "string" or t == "int":
984 return repr(p)
Cole Faustb85d1a12022-11-08 18:14:01 -0800985 fail("unsupported value '%s' of type '%s'" % (p, type(p)))
Usta Shrestha79fccef2022-09-02 18:37:40 -0400986
987 def encode_list(list):
Cole Faustb85d1a12022-11-08 18:14:01 -0800988 return "[%s]" % ", ".join([encode_primitive(item) for item in list])
Usta Shrestha79fccef2022-09-02 18:37:40 -0400989
990 def encode_list_or_primitive(v):
991 return encode_list(v) if type(v) == "list" else encode_primitive(v)
992
993 if type(input) == "dict":
994 # TODO(juu): the result is read line by line so can't use '\n' yet
Cole Faustb85d1a12022-11-08 18:14:01 -0800995 kv_pairs = [("%s: %s" % (encode_primitive(k), encode_list_or_primitive(v))) for (k, v) in input.items()]
996 return "{ %s }" % ", ".join(kv_pairs)
Usta Shrestha79fccef2022-09-02 18:37:40 -0400997 else:
998 return encode_list_or_primitive(input)
999
Cole Faustb85d1a12022-11-08 18:14:01 -08001000{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001001
Cole Faustb85d1a12022-11-08 18:14:01 -08001002{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001003
1004def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -04001005 # TODO(b/199363072): filegroups and file targets aren't associated with any
1006 # specific platform architecture in mixed builds. This is consistent with how
1007 # Soong treats filegroups, but it may not be the case with manually-written
1008 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -05001009 buildoptions = build_options(target)
Yu Liue4312402023-01-18 09:15:31 -08001010
Jingwen Chen8f222742021-10-07 12:02:23 +00001011 if buildoptions == None:
1012 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -04001013 # any specific platform architecture in mixed builds, so use the host.
1014 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -08001015 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -05001016 if len(platforms) != 1:
1017 # An individual configured target should have only one platform architecture.
1018 # Note that it's fine for there to be multiple architectures for the same label,
1019 # but each is its own configured target.
1020 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -08001021 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -05001022 if platform_name == "host":
1023 return "HOST"
Cole Faustb85d1a12022-11-08 18:14:01 -08001024 if not platform_name.startswith("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}"):
1025 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))
1026 platform_name = platform_name.removeprefix("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}").removeprefix("_")
Yu Liue4312402023-01-18 09:15:31 -08001027 config_key = ""
Cole Faustb85d1a12022-11-08 18:14:01 -08001028 if not platform_name:
Yu Liue4312402023-01-18 09:15:31 -08001029 config_key = "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -04001030 elif platform_name.startswith("android_"):
Yu Liue4312402023-01-18 09:15:31 -08001031 config_key = platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -04001032 elif platform_name.startswith("linux_"):
Yu Liue4312402023-01-18 09:15:31 -08001033 config_key = platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -04001034 else:
Cole Faustb85d1a12022-11-08 18:14:01 -08001035 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 -05001036
Yu Liue4312402023-01-18 09:15:31 -08001037 within_apex = buildoptions.get("//build/bazel/rules/apex:within_apex")
1038 apex_sdk_version = buildoptions.get("//build/bazel/rules/apex:min_sdk_version")
1039
1040 if within_apex:
1041 config_key += "|within_apex"
1042 if apex_sdk_version != None and len(apex_sdk_version) > 0:
1043 config_key += "|" + apex_sdk_version
1044
1045 return config_key
1046
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001047def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -05001048 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -05001049
Chris Parsons86dc2c22022-09-28 14:58:41 -04001050 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
1051 if id_string.startswith("//"):
1052 id_string = "@" + id_string
1053
Cole Faustb85d1a12022-11-08 18:14:01 -08001054 {MAIN_SWITCH_SECTION}
1055
Chris Parsons944e7d02021-03-11 11:08:46 -05001056 # This target was not requested via cquery, and thus must be a dependency
1057 # of a requested target.
1058 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001059`
Cole Faustb85d1a12022-11-08 18:14:01 -08001060 replacer := strings.NewReplacer(
1061 "{TARGET_PRODUCT}", context.targetProduct,
1062 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
1063 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
1064 "{FUNCTION_DEF_SECTION}", functionDefSection,
1065 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001066
Cole Faustb85d1a12022-11-08 18:14:01 -08001067 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001068}
1069
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001070// Returns a path containing build-related metadata required for interfacing
1071// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001072func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001073 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -05001074}
1075
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001076// Returns the path where the contents of the @soong_injection repository live.
1077// It is used by Soong to tell Bazel things it cannot over the command line.
1078func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001079 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001080}
1081
1082// Returns the path of the synthetic Bazel workspace that contains a symlink
1083// forest composed the whole source tree and BUILD files generated by bp2build.
1084func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001085 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001086}
1087
Jingwen Chen8c523582021-06-01 11:19:53 +00001088// Returns the path to the top level out dir ($OUT_DIR).
1089func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001090 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +00001091}
1092
Sasha Smundak4975c822022-11-16 15:28:18 -08001093const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
1094
1095var (
1096 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
1097 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
1098 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
1099)
1100
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001101// Issues commands to Bazel to receive results for all cquery requests
1102// queued in the BazelContext.
Liz Kammer690fbac2023-02-10 11:11:17 -05001103func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx invokeBazelContext) error {
1104 eventHandler := ctx.GetEventHandler()
1105 eventHandler.Begin("bazel")
1106 defer eventHandler.End("bazel")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001107
Sasha Smundak4975c822022-11-16 15:28:18 -08001108 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
1109 if err := os.MkdirAll(metricsDir, 0777); err != nil {
1110 return err
1111 }
1112 }
1113 context.results = make(map[cqueryKey]string)
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001114 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001115 return err
1116 }
1117 if err := context.runAquery(config, ctx); err != nil {
1118 return err
1119 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001120 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001121 return err
1122 }
1123
1124 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001125 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -08001126 return nil
1127}
1128
Liz Kammer690fbac2023-02-10 11:11:17 -05001129func (context *mixedBuildBazelContext) runCquery(config Config, ctx invokeBazelContext) error {
1130 eventHandler := ctx.GetEventHandler()
1131 eventHandler.Begin("cquery")
1132 defer eventHandler.End("cquery")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001133 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +02001134 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
1135 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
1136 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -05001137 if err != nil {
1138 return err
1139 }
1140 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001141 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001142 return err
1143 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001144 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001145 return err
1146 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001147 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001148 return err
1149 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001150 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001151 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001152 return err
1153 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001154
Yu Liue4312402023-01-18 09:15:31 -08001155 extraFlags := []string{"--output=starlark", "--starlark:file=" + absolutePath(cqueryFileRelpath)}
1156 if Bool(config.productVariables.ClangCoverage) {
1157 extraFlags = append(extraFlags, "--collect_code_coverage")
1158 }
1159
1160 cqueryCommandWithFlag := context.createBazelCommand(config, context.paths, bazel.CqueryBuildRootRunName, cqueryCmd, extraFlags...)
Liz Kammer690fbac2023-02-10 11:11:17 -05001161 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCommandWithFlag, eventHandler)
Wei Licbd181c2022-11-16 08:59:23 -08001162 if cqueryErr != nil {
1163 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001164 }
Jason Wu52cd1942022-09-08 15:37:57 +00001165 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", printableCqueryCommand(cqueryCommandWithFlag))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001166 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001167 return err
1168 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001169 cqueryResults := map[string]string{}
1170 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1171 if strings.Contains(outputLine, ">>") {
1172 splitLine := strings.SplitN(outputLine, ">>", 2)
1173 cqueryResults[splitLine[0]] = splitLine[1]
1174 }
1175 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001176 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001177 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001178 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001179 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001180 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001181 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001182 }
1183 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001184 return nil
1185}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001186
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001187func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1188 oldContents, err := os.ReadFile(path)
1189 if err != nil || !bytes.Equal(contents, oldContents) {
1190 err = os.WriteFile(path, contents, perm)
1191 }
1192 return nil
1193}
1194
Liz Kammer690fbac2023-02-10 11:11:17 -05001195func (context *mixedBuildBazelContext) runAquery(config Config, ctx invokeBazelContext) error {
1196 eventHandler := ctx.GetEventHandler()
1197 eventHandler.Begin("aquery")
1198 defer eventHandler.End("aquery")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001199 // Issue an aquery command to retrieve action information about the bazel build tree.
1200 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001201 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1202 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001203 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001204 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001205 extraFlags = append(extraFlags, "--collect_code_coverage")
1206 paths := make([]string, 0, 2)
1207 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001208 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001209 // TODO(b/259404593) convert path wildcard to regex values
1210 if p[i] == "*" {
1211 p[i] = ".*"
1212 }
1213 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001214 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1215 }
1216 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1217 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1218 }
1219 if len(paths) > 0 {
1220 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001221 }
1222 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001223 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
Liz Kammer690fbac2023-02-10 11:11:17 -05001224 extraFlags...), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001225 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001226 return err
1227 }
Liz Kammer690fbac2023-02-10 11:11:17 -05001228 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001229 return err
1230}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001231
Liz Kammer690fbac2023-02-10 11:11:17 -05001232func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx invokeBazelContext) error {
1233 eventHandler := ctx.GetEventHandler()
1234 eventHandler.Begin("symlinks")
1235 defer eventHandler.End("symlinks")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001236 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1237 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1238 // but some of symlinks may be required to resolve source dependencies of the build.
Liz Kammer690fbac2023-02-10 11:11:17 -05001239 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001240 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001241}
Chris Parsonsa798d962020-10-12 23:44:08 -04001242
Liz Kammera4655a92023-02-10 17:17:28 -05001243func (context *mixedBuildBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001244 return context.buildStatements
1245}
1246
Sasha Smundak39a301c2022-12-29 17:11:49 -08001247func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001248 return context.depsets
1249}
1250
Sasha Smundak39a301c2022-12-29 17:11:49 -08001251func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001252 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001253}
1254
Chris Parsonsa798d962020-10-12 23:44:08 -04001255// Singleton used for registering BUILD file ninja dependencies (needed
1256// for correctness of builds which use Bazel.
1257func BazelSingleton() Singleton {
1258 return &bazelSingleton{}
1259}
1260
1261type bazelSingleton struct{}
1262
1263func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001264 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001265 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001266 return
1267 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001268
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001269 // Add ninja file dependencies for files which all bazel invocations require.
1270 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001271 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001272 ctx.AddNinjaFileDeps(bazelBuildList)
1273
Sasha Smundak0e87b182022-12-01 11:46:11 -08001274 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001275 if err != nil {
1276 ctx.Errorf(err.Error())
1277 }
1278 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1279 for _, file := range files {
1280 ctx.AddNinjaFileDeps(file)
1281 }
1282
Chris Parsons1a7aca02022-04-25 22:35:15 -04001283 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1284 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001285 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001286 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1287 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001288 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1289 }
1290 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001291 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1292 if artifactPath == "bazel-out/volatile-status.txt" {
1293 // See https://bazel.build/docs/user-manual#workspace-status
1294 orderOnlies = append(orderOnlies, pathInBazelOut)
1295 } else {
1296 outputs = append(outputs, pathInBazelOut)
1297 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001298 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001299 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001300 ctx.Build(pctx, BuildParams{
1301 Rule: blueprint.Phony,
1302 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1303 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001304 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001305 })
1306 }
1307
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001308 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1309 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001310 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Liz Kammera4655a92023-02-10 17:17:28 -05001311 // nil build statements are a valid case where we do not create an action because it is
1312 // unnecessary or handled by other processing
1313 if buildStatement == nil {
1314 continue
1315 }
Sasha Smundak1da064c2022-06-08 16:36:16 -07001316 if len(buildStatement.Command) > 0 {
1317 rule := NewRuleBuilder(pctx, ctx)
1318 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1319 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1320 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1321 continue
1322 }
1323 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1324 // and thus require special treatment. If BuildStatement were an interface implementing
1325 // buildRule(ctx) function, the code here would just call it.
1326 // Unfortunately, the BuildStatement is defined in
1327 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1328 // because this would cause circular dependency. So, until we move aquery processing
1329 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001330 switch buildStatement.Mnemonic {
1331 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001332 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1333 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001334 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001335 // build-runfiles arguments are the manifest file and the target directory
1336 // where it creates the symlink tree according to this manifest (and then
1337 // writes the MANIFEST file to it).
1338 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1339 outManifestPath := outManifest.String()
1340 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1341 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1342 }
1343 outDir := filepath.Dir(outManifestPath)
1344 ctx.Build(pctx, BuildParams{
1345 Rule: buildRunfilesRule,
1346 Output: outManifest,
1347 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1348 Description: "symlink tree for " + outDir,
1349 Args: map[string]string{
1350 "outDir": outDir,
1351 },
1352 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001353 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001354 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001355 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001356 }
1357}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001358
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001359// Register bazel-owned build statements (obtained from the aquery invocation).
Liz Kammera4655a92023-02-10 17:17:28 -05001360func createCommand(cmd *RuleBuilderCommand, buildStatement *bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001361 // executionRoot is the action cwd.
1362 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1363
1364 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1365 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001366 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001367 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001368 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001369 }
1370 cmd.Text("&&")
1371 }
1372
1373 for _, pair := range buildStatement.Env {
1374 // Set per-action env variables, if any.
1375 cmd.Flag(pair.Key + "=" + pair.Value)
1376 }
1377
1378 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001379 if len(buildStatement.Command) > 16*1024 {
1380 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1381 WriteFileRule(ctx, commandFile, buildStatement.Command)
1382
1383 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1384 } else {
1385 cmd.Text(buildStatement.Command)
1386 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001387
1388 for _, outputPath := range buildStatement.OutputPaths {
1389 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1390 }
1391 for _, inputPath := range buildStatement.InputPaths {
1392 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1393 }
1394 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1395 otherDepsetName := bazelDepsetName(inputDepsetHash)
1396 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1397 }
1398
1399 if depfile := buildStatement.Depfile; depfile != nil {
1400 // The paths in depfile are relative to `executionRoot`.
1401 // Hence, they need to be corrected by replacing "bazel-out"
1402 // with the full `bazelOutDir`.
1403 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1404 // would be deemed missing.
1405 // (Note: The regexp uses a capture group because the version of sed
1406 // does not support a look-behind pattern.)
1407 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1408 bazelOutDir, *depfile)
1409 cmd.Text(replacement)
1410 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1411 }
1412
1413 for _, symlinkPath := range buildStatement.SymlinkPaths {
1414 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1415 }
1416}
1417
Chris Parsons8d6e4332021-02-22 16:13:50 -05001418func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001419 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001420}
1421
Chris Parsons787fb362021-10-14 18:43:51 -04001422func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001423 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001424 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001425 if key.configKey.osType.Class == Device {
1426 // For the generic Android, the expected result is "target|android", which
1427 // corresponds to the product_variable_config named "android_target" in
1428 // build/bazel/platforms/BUILD.bazel.
1429 arch = "target"
1430 } else {
1431 // Use host platform, which is currently hardcoded to be x86_64.
1432 arch = "x86_64"
1433 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001434 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001435 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001436 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001437 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001438 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001439 }
Yu Liue4312402023-01-18 09:15:31 -08001440 keyString := arch + "|" + osName
1441 if key.configKey.apexKey.WithinApex {
1442 keyString += "|" + withinApexToString(key.configKey.apexKey.WithinApex)
1443 }
1444
1445 if len(key.configKey.apexKey.ApexSdkVersion) > 0 {
1446 keyString += "|" + key.configKey.apexKey.ApexSdkVersion
1447 }
1448
1449 return keyString
Chris Parsons787fb362021-10-14 18:43:51 -04001450}
1451
Chris Parsonsf874e462022-05-10 13:50:12 -04001452func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001453 return configKey{
1454 // use string because Arch is not a valid key in go
1455 arch: ctx.Arch().String(),
1456 osType: ctx.Os(),
1457 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001458}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001459
Yu Liue4312402023-01-18 09:15:31 -08001460func GetConfigKeyApexVariant(ctx BaseModuleContext, apexKey *ApexConfigKey) configKey {
1461 configKey := GetConfigKey(ctx)
1462
1463 if apexKey != nil {
1464 configKey.apexKey = ApexConfigKey{
1465 WithinApex: apexKey.WithinApex,
1466 ApexSdkVersion: apexKey.ApexSdkVersion,
1467 }
1468 }
1469
1470 return configKey
1471}
1472
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001473func bazelDepsetName(contentHash string) string {
1474 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001475}
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001476
1477func EnvironmentVarsFile(config Config) string {
1478 return fmt.Sprintf(bazel.GeneratedBazelFileWarning+`
1479_env = %s
1480
1481env = _env
1482`,
1483 starlark_fmt.PrintStringList(allowedBazelEnvironmentVars, 0),
1484 )
1485}