blob: 9c273d9a3336979145ffced64ad6855bc958ba2c [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
Zi Wanga4f7dae2023-04-17 20:07:26 -070066 "UNBUNDLED_BUILD_TARGET_SDK_WITH_API_FINGERPRINT",
67
Sam Delmericocb3c52c2023-02-03 17:40:08 -050068 // Overrides the version in the apex_manifest.json. The version is unique for
69 // each branch (internal, aosp, mainline releases, dessert releases). This
70 // enables modules built on an older branch to be installed against a newer
71 // device for development purposes.
72 "OVERRIDE_APEX_MANIFEST_DEFAULT_VERSION",
73 }
Sasha Smundak1da064c2022-06-08 16:36:16 -070074)
75
Chris Parsonsf874e462022-05-10 13:50:12 -040076func init() {
77 RegisterMixedBuildsMutator(InitRegistrationContext)
78}
79
80func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammer337e9032022-08-03 15:49:43 -040081 ctx.FinalDepsMutators(func(ctx RegisterMutatorsContext) {
Chris Parsonsf874e462022-05-10 13:50:12 -040082 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
83 })
84}
85
86func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
87 if m := ctx.Module(); m.Enabled() {
88 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
MarkDacek9c094ca2023-03-16 19:15:19 +000089 queueMixedBuild := mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx)
90 if queueMixedBuild {
Chris Parsonsf874e462022-05-10 13:50:12 -040091 mixedBuildMod.QueueBazelCall(ctx)
MarkDacek9c094ca2023-03-16 19:15:19 +000092 } else if _, ok := ctx.Config().bazelForceEnabledModules[m.Name()]; ok {
93 // TODO(b/273910287) - remove this once --ensure_allowlist_integrity is added
94 ctx.ModuleErrorf("Attempted to force enable an unready module: %s. Did you forget to Bp2BuildDefaultTrue its directory?\n", m.Name())
Chris Parsonsf874e462022-05-10 13:50:12 -040095 }
96 }
97 }
98}
99
Liz Kammerf29df7c2021-04-02 13:37:39 -0400100type cqueryRequest interface {
101 // Name returns a string name for this request type. Such request type names must be unique,
102 // and must only consist of alphanumeric characters.
103 Name() string
104
105 // StarlarkFunctionBody returns a starlark function body to process this request type.
106 // The returned string is the body of a Starlark function which obtains
107 // all request-relevant information about a target and returns a string containing
108 // this information.
109 // The function should have the following properties:
Cole Faust97d15272022-11-22 14:08:59 -0800110 // - The arguments are `target` (a configured target) and `id_string` (the label + configuration).
Liz Kammerf29df7c2021-04-02 13:37:39 -0400111 // - The return value must be a string.
112 // - The function body should not be indented outside of its own scope.
113 StarlarkFunctionBody() string
114}
115
Chris Parsons787fb362021-10-14 18:43:51 -0400116// Portion of cquery map key to describe target configuration.
117type configKey struct {
Yu Liue4312402023-01-18 09:15:31 -0800118 arch string
119 osType OsType
120 apexKey ApexConfigKey
121}
122
123type ApexConfigKey struct {
124 WithinApex bool
125 ApexSdkVersion string
126}
127
128func (c ApexConfigKey) String() string {
129 return fmt.Sprintf("%s_%s", withinApexToString(c.WithinApex), c.ApexSdkVersion)
130}
131
132func withinApexToString(withinApex bool) string {
133 if withinApex {
134 return "within_apex"
135 }
136 return ""
Chris Parsons787fb362021-10-14 18:43:51 -0400137}
138
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700139func (c configKey) String() string {
Yu Liue4312402023-01-18 09:15:31 -0800140 return fmt.Sprintf("%s::%s::%s", c.arch, c.osType, c.apexKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700141}
142
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400143// Map key to describe bazel cquery requests.
144type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400145 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400146 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400147 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400148}
149
Chris Parsons86dc2c22022-09-28 14:58:41 -0400150func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
151 if strings.HasPrefix(label, "//") {
152 // Normalize Bazel labels to specify main repository explicitly.
153 label = "@" + label
154 }
155 return cqueryKey{label, cqueryRequest, cfgKey}
156}
157
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700158func (c cqueryKey) String() string {
159 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700160}
161
Liz Kammer690fbac2023-02-10 11:11:17 -0500162type invokeBazelContext interface {
163 GetEventHandler() *metrics.EventHandler
164}
165
Chris Parsonsf874e462022-05-10 13:50:12 -0400166// BazelContext is a context object useful for interacting with Bazel during
167// the course of a build. Use of Bazel to evaluate part of the build graph
168// is referred to as a "mixed build". (Some modules are managed by Soong,
169// some are managed by Bazel). To facilitate interop between these build
170// subgraphs, Soong may make requests to Bazel and evaluate their responses
171// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400172type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400173 // Add a cquery request to the bazel request queue. All queued requests
174 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
175 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
176
177 // ** Cquery Results Retrieval Functions
178 // The below functions pertain to retrieving cquery results from a prior
179 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400180
181 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400182 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500183
Chris Parsons944e7d02021-03-11 11:08:46 -0500184 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400185 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400186
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000187 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400188 // TODO(b/232976601): Remove.
189 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000190
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700191 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400192 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700193
Sasha Smundakedd16662022-10-07 14:44:50 -0700194 // Returns the results of the GetCcUnstrippedInfo query
195 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
196
Chris Parsonsf874e462022-05-10 13:50:12 -0400197 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400198
199 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800200 // queued in the BazelContext. The ctx argument is optional and is only
201 // used for performance data collection
Liz Kammer690fbac2023-02-10 11:11:17 -0500202 InvokeBazel(config Config, ctx invokeBazelContext) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400203
Chris Parsonsad876012022-08-20 14:48:32 -0400204 // Returns true if Bazel handling is enabled for the module with the given name.
205 // Note that this only implies "bazel mixed build" allowlisting. The caller
206 // should independently verify the module is eligible for Bazel handling
207 // (for example, that it is MixedBuildBuildable).
Yu Liue4312402023-01-18 09:15:31 -0800208 IsModuleNameAllowed(moduleName string, withinApex bool) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500209
Yu Liubfb23622023-02-22 10:42:15 -0800210 IsModuleDclaAllowed(moduleName string) bool
211
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500212 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
213 OutputBase() string
214
215 // Returns build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500216 BuildStatementsToRegister() []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400217
218 // Returns the depsets defined in Bazel's aquery response.
219 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400220}
221
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400222type bazelRunner interface {
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500223 createBazelCommand(config Config, paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) *exec.Cmd
Liz Kammer690fbac2023-02-10 11:11:17 -0500224 issueBazelCommand(bazelCmd *exec.Cmd, eventHandler *metrics.EventHandler) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400225}
226
227type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000228 homeDir string
229 bazelPath string
230 outputBase string
231 workspaceDir string
232 soongOutDir string
233 metricsDir string
234 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400235}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400236
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400237// A context object which tracks queued requests that need to be made to Bazel,
238// and their results after the requests have been made.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800239type mixedBuildBazelContext struct {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400240 bazelRunner
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500241 paths *bazelPaths
242 // cquery requests that have not yet been issued to Bazel. This list is maintained
243 // in a sorted state, and is guaranteed to have no duplicates.
244 requests []cqueryKey
245 requestMutex sync.Mutex // requests can be written in parallel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400246
247 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500248
249 // Build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500250 buildStatements []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400251
252 // Depsets which should be used for Bazel's build statements.
253 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400254
255 // Per-module allowlist/denylist functionality to control whether analysis of
256 // modules are handled by Bazel. For modules which do not have a Bazel definition
257 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
258 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
259 // Per-module denylist to opt modules out of bazel handling.
260 bazelDisabledModules map[string]bool
261 // Per-module allowlist to opt modules in to bazel handling.
262 bazelEnabledModules map[string]bool
Yu Liue4312402023-01-18 09:15:31 -0800263 // DCLA modules are enabled when used in apex.
264 bazelDclaEnabledModules map[string]bool
Chris Parsonsad876012022-08-20 14:48:32 -0400265 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
266 modulesDefaultToBazel bool
Cole Faustb85d1a12022-11-08 18:14:01 -0800267
268 targetProduct string
269 targetBuildVariant string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400270}
271
Sasha Smundak39a301c2022-12-29 17:11:49 -0800272var _ BazelContext = &mixedBuildBazelContext{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400273
274// A bazel context to use when Bazel is disabled.
275type noopBazelContext struct{}
276
277var _ BazelContext = noopBazelContext{}
278
279// A bazel context to use for tests.
280type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400281 OutputBaseDir string
282
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000283 LabelToOutputFiles map[string][]string
284 LabelToCcInfo map[string]cquery.CcInfo
285 LabelToPythonBinary map[string]string
Liz Kammerbe6a7122022-11-04 16:05:11 -0400286 LabelToApexInfo map[string]cquery.ApexInfo
Sasha Smundakedd16662022-10-07 14:44:50 -0700287 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
Yu Liue4312402023-01-18 09:15:31 -0800288
289 BazelRequests map[string]bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400290}
291
Yu Liue4312402023-01-18 09:15:31 -0800292func (m MockBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
293 key := BuildMockBazelContextRequestKey(label, requestType, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
294 if m.BazelRequests == nil {
295 m.BazelRequests = make(map[string]bool)
296 }
297 m.BazelRequests[key] = true
Chris Parsons8d6e4332021-02-22 16:13:50 -0500298}
299
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700300func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500301 result, ok := m.LabelToOutputFiles[label]
302 if !ok {
303 return []string{}, fmt.Errorf("no target with label %q in LabelToOutputFiles", label)
304 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400305 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400306}
307
Yu Liue4312402023-01-18 09:15:31 -0800308func (m MockBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500309 result, ok := m.LabelToCcInfo[label]
310 if !ok {
Yu Liue4312402023-01-18 09:15:31 -0800311 key := BuildMockBazelContextResultKey(label, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
312 result, ok = m.LabelToCcInfo[key]
313 if !ok {
314 return cquery.CcInfo{}, fmt.Errorf("no target with label %q in LabelToCcInfo", label)
315 }
Sam Delmericoce39f832023-01-23 14:04:24 -0500316 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400317 return result, nil
318}
319
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700320func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500321 result, ok := m.LabelToPythonBinary[label]
322 if !ok {
323 return "", fmt.Errorf("no target with label %q in LabelToPythonBinary", label)
324 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400325 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000326}
327
Liz Kammerbe6a7122022-11-04 16:05:11 -0400328func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500329 result, ok := m.LabelToApexInfo[label]
330 if !ok {
331 return cquery.ApexInfo{}, fmt.Errorf("no target with label %q in LabelToApexInfo", label)
332 }
Liz Kammer0e255ef2022-11-04 16:07:04 -0400333 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700334}
335
Sasha Smundakedd16662022-10-07 14:44:50 -0700336func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500337 result, ok := m.LabelToCcBinary[label]
338 if !ok {
339 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no target with label %q in LabelToCcBinary", label)
340 }
Sasha Smundakedd16662022-10-07 14:44:50 -0700341 return result, nil
342}
343
Liz Kammer690fbac2023-02-10 11:11:17 -0500344func (m MockBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400345 panic("unimplemented")
346}
347
Yu Liue4312402023-01-18 09:15:31 -0800348func (m MockBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400349 return true
350}
351
Yu Liubfb23622023-02-22 10:42:15 -0800352func (m MockBazelContext) IsModuleDclaAllowed(_ string) bool {
353 return true
354}
355
Liz Kammera92e8442021-04-07 20:25:21 -0400356func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500357
Liz Kammera4655a92023-02-10 17:17:28 -0500358func (m MockBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
359 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500360}
361
Chris Parsons1a7aca02022-04-25 22:35:15 -0400362func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
363 return []bazel.AqueryDepset{}
364}
365
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400366var _ BazelContext = MockBazelContext{}
367
Yu Liue4312402023-01-18 09:15:31 -0800368func BuildMockBazelContextRequestKey(label string, request cqueryRequest, arch string, osType OsType, apexKey ApexConfigKey) string {
369 cfgKey := configKey{
370 arch: arch,
371 osType: osType,
372 apexKey: apexKey,
373 }
374
375 return strings.Join([]string{label, request.Name(), cfgKey.String()}, "_")
376}
377
378func BuildMockBazelContextResultKey(label string, arch string, osType OsType, apexKey ApexConfigKey) string {
379 cfgKey := configKey{
380 arch: arch,
381 osType: osType,
382 apexKey: apexKey,
383 }
384
385 return strings.Join([]string{label, cfgKey.String()}, "_")
386}
387
Sasha Smundak39a301c2022-12-29 17:11:49 -0800388func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400389 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400390 bazelCtx.requestMutex.Lock()
391 defer bazelCtx.requestMutex.Unlock()
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500392
393 // Insert key into requests, maintaining the sort, and only if it's not duplicate.
394 keyString := key.String()
395 foundEqual := false
396 notLessThanKeyString := func(i int) bool {
397 s := bazelCtx.requests[i].String()
398 v := strings.Compare(s, keyString)
399 if v == 0 {
400 foundEqual = true
401 }
402 return v >= 0
403 }
404 targetIndex := sort.Search(len(bazelCtx.requests), notLessThanKeyString)
405 if foundEqual {
406 return
407 }
408
409 if targetIndex == len(bazelCtx.requests) {
410 bazelCtx.requests = append(bazelCtx.requests, key)
411 } else {
412 bazelCtx.requests = append(bazelCtx.requests[:targetIndex+1], bazelCtx.requests[targetIndex:]...)
413 bazelCtx.requests[targetIndex] = key
414 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400415}
416
Sasha Smundak39a301c2022-12-29 17:11:49 -0800417func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400418 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400419 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500420 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400421
Chris Parsonsf874e462022-05-10 13:50:12 -0400422 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400423 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400424 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400425}
426
Sasha Smundak39a301c2022-12-29 17:11:49 -0800427func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400428 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400429 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000430 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400431 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000432 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400433 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 +0000434}
435
Sasha Smundak39a301c2022-12-29 17:11:49 -0800436func (bazelCtx *mixedBuildBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400437 key := makeCqueryKey(label, cquery.GetPythonBinary, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400438 if rawString, ok := bazelCtx.results[key]; ok {
439 bazelOutput := strings.TrimSpace(rawString)
440 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
441 }
442 return "", fmt.Errorf("no bazel response found for %v", key)
443}
444
Sasha Smundak39a301c2022-12-29 17:11:49 -0800445func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400446 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700447 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500448 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700449 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400450 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700451}
452
Sasha Smundak39a301c2022-12-29 17:11:49 -0800453func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700454 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
455 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500456 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700457 }
458 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
459}
460
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700461func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500462 panic("unimplemented")
463}
464
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700465func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500466 panic("unimplemented")
467}
468
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700469func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400470 panic("unimplemented")
471}
472
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700473func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000474 panic("unimplemented")
475}
476
Liz Kammerbe6a7122022-11-04 16:05:11 -0400477func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700478 panic("unimplemented")
479}
480
Sasha Smundakedd16662022-10-07 14:44:50 -0700481func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
482 //TODO implement me
483 panic("implement me")
484}
485
Liz Kammer690fbac2023-02-10 11:11:17 -0500486func (n noopBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400487 panic("unimplemented")
488}
489
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500490func (m noopBazelContext) OutputBase() string {
491 return ""
492}
493
Yu Liue4312402023-01-18 09:15:31 -0800494func (n noopBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400495 return false
496}
497
Yu Liubfb23622023-02-22 10:42:15 -0800498func (n noopBazelContext) IsModuleDclaAllowed(_ string) bool {
499 return false
500}
501
Liz Kammera4655a92023-02-10 17:17:28 -0500502func (m noopBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
503 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500504}
505
Chris Parsons1a7aca02022-04-25 22:35:15 -0400506func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
507 return []bazel.AqueryDepset{}
508}
509
Yu Liue4312402023-01-18 09:15:31 -0800510func addToStringSet(set map[string]bool, items []string) {
511 for _, item := range items {
512 set[item] = true
513 }
514}
515
Cole Faust705968d2022-12-14 11:32:05 -0800516func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400517 disabledModules := map[string]bool{}
518 enabledModules := map[string]bool{}
519
Cole Faust705968d2022-12-14 11:32:05 -0800520 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400521 case BazelProdMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800522 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800523 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000524 enabledModules[enabledAdHocModule] = true
525 }
MarkDacekb78465d2022-10-18 20:10:16 +0000526 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400527 // Staging mode includes all prod modules plus all staging modules.
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800528 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
529 addToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800530 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000531 enabledModules[enabledAdHocModule] = true
532 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400533 case BazelDevMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800534 addToStringSet(disabledModules, allowlists.MixedBuildsDisabledList)
Chris Parsonsef615e52022-08-18 22:04:11 -0400535 default:
Cole Faust705968d2022-12-14 11:32:05 -0800536 panic("Expected BazelProdMode, BazelStagingMode, or BazelDevMode")
537 }
538 return enabledModules, disabledModules
539}
540
541func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
542 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
543 enabledList := make([]string, 0, len(enabledModules))
544 for module := range enabledModules {
545 if !disabledModules[module] {
546 enabledList = append(enabledList, module)
547 }
548 }
549 sort.Strings(enabledList)
550 return enabledList
551}
552
553func NewBazelContext(c *config) (BazelContext, error) {
554 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode && c.BuildMode != BazelDevMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400555 return noopBazelContext{}, nil
556 }
557
Cole Faust705968d2022-12-14 11:32:05 -0800558 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
559
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800560 paths := bazelPaths{
561 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400562 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800563 var missing []string
564 vars := []struct {
565 name string
566 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000567
568 // True if the environment variable needs to be tracked so that changes to the variable
569 // cause the ninja file to be regenerated, false otherwise. False should only be set for
570 // environment variables that have no effect on the generated ninja file.
571 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800572 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000573 {"BAZEL_HOME", &paths.homeDir, true},
574 {"BAZEL_PATH", &paths.bazelPath, true},
575 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
576 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
577 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
578 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800579 }
580 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000581 if v.track {
582 if s := c.Getenv(v.name); len(s) > 1 {
583 *v.ptr = s
584 continue
585 }
586 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800587 *v.ptr = s
588 } else {
589 missing = append(missing, v.name)
590 }
591 }
592 if len(missing) > 0 {
593 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
594 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800595
596 targetBuildVariant := "user"
597 if c.Eng() {
598 targetBuildVariant = "eng"
599 } else if c.Debuggable() {
600 targetBuildVariant = "userdebug"
601 }
602 targetProduct := "unknown"
603 if c.HasDeviceProduct() {
604 targetProduct = c.DeviceProduct()
605 }
Yu Liue4312402023-01-18 09:15:31 -0800606 dclaMixedBuildsEnabledList := []string{}
607 if c.BuildMode == BazelProdMode {
608 dclaMixedBuildsEnabledList = allowlists.ProdDclaMixedBuildsEnabledList
609 } else if c.BuildMode == BazelStagingMode {
610 dclaMixedBuildsEnabledList = append(allowlists.ProdDclaMixedBuildsEnabledList,
611 allowlists.StagingDclaMixedBuildsEnabledList...)
612 }
613 dclaEnabledModules := map[string]bool{}
614 addToStringSet(dclaEnabledModules, dclaMixedBuildsEnabledList)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800615 return &mixedBuildBazelContext{
Chris Parsons9402ca82023-02-23 17:28:06 -0500616 bazelRunner: &builtinBazelRunner{c.UseBazelProxy, absolutePath(c.outDir)},
Yu Liue4312402023-01-18 09:15:31 -0800617 paths: &paths,
618 modulesDefaultToBazel: c.BuildMode == BazelDevMode,
619 bazelEnabledModules: enabledModules,
620 bazelDisabledModules: disabledModules,
621 bazelDclaEnabledModules: dclaEnabledModules,
622 targetProduct: targetProduct,
623 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400624 }, nil
625}
626
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400627func (p *bazelPaths) BazelMetricsDir() string {
628 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000629}
630
Yu Liue4312402023-01-18 09:15:31 -0800631func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string, withinApex bool) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400632 if context.bazelDisabledModules[moduleName] {
633 return false
634 }
635 if context.bazelEnabledModules[moduleName] {
636 return true
637 }
Yu Liubfb23622023-02-22 10:42:15 -0800638 if withinApex && context.IsModuleDclaAllowed(moduleName) {
Yu Liue4312402023-01-18 09:15:31 -0800639 return true
640 }
641
Chris Parsonsad876012022-08-20 14:48:32 -0400642 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400643}
644
Yu Liubfb23622023-02-22 10:42:15 -0800645func (context *mixedBuildBazelContext) IsModuleDclaAllowed(moduleName string) bool {
646 return context.bazelDclaEnabledModules[moduleName]
647}
648
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400649func pwdPrefix() string {
650 // Darwin doesn't have /proc
651 if runtime.GOOS != "darwin" {
652 return "PWD=/proc/self/cwd"
653 }
654 return ""
655}
656
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400657type bazelCommand struct {
658 command string
659 // query or label
660 expression string
661}
662
663type mockBazelRunner struct {
664 bazelCommandResults map[bazelCommand]string
Jason Wu52cd1942022-09-08 15:37:57 +0000665 // use *exec.Cmd as a key to get the bazelCommand, the map will be used in issueBazelCommand()
666 // Register createBazelCommand() invocations. Later, an
667 // issueBazelCommand() invocation can be mapped to the *exec.Cmd instance
668 // and then to the expected result via bazelCommandResults
669 tokens map[*exec.Cmd]bazelCommand
670 commands []bazelCommand
671 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400672}
673
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500674func (r *mockBazelRunner) createBazelCommand(_ Config, _ *bazelPaths, _ bazel.RunName,
Jason Wu52cd1942022-09-08 15:37:57 +0000675 command bazelCommand, extraFlags ...string) *exec.Cmd {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400676 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700677 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Jason Wu52cd1942022-09-08 15:37:57 +0000678 cmd := &exec.Cmd{}
679 if r.tokens == nil {
680 r.tokens = make(map[*exec.Cmd]bazelCommand)
681 }
682 r.tokens[cmd] = command
683 return cmd
684}
685
Liz Kammer690fbac2023-02-10 11:11:17 -0500686func (r *mockBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd, _ *metrics.EventHandler) (string, string, error) {
Jason Wu52cd1942022-09-08 15:37:57 +0000687 if command, ok := r.tokens[bazelCmd]; ok {
688 return r.bazelCommandResults[command], "", nil
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400689 }
690 return "", "", nil
691}
692
Chris Parsons9402ca82023-02-23 17:28:06 -0500693type builtinBazelRunner struct {
694 useBazelProxy bool
695 outDir string
696}
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400697
Chris Parsons808d84c2021-03-09 20:43:32 -0500698// Issues the given bazel command with given build label and additional flags.
699// Returns (stdout, stderr, error). The first and second return values are strings
700// containing the stdout and stderr of the run command, and an error is returned if
701// the invocation returned an error code.
Liz Kammer690fbac2023-02-10 11:11:17 -0500702func (r *builtinBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd, eventHandler *metrics.EventHandler) (string, string, error) {
Chris Parsons9402ca82023-02-23 17:28:06 -0500703 if r.useBazelProxy {
704 eventHandler.Begin("client_proxy")
705 defer eventHandler.End("client_proxy")
706 proxyClient := bazel.NewProxyClient(r.outDir)
707 // Omit the arg containing the Bazel binary, as that is handled by the proxy
708 // server.
709 bazelFlags := bazelCmd.Args[1:]
710 // TODO(b/270989498): Refactor these functions to not take exec.Cmd, as its
711 // not actually executed for client proxying.
712 resp, err := proxyClient.IssueCommand(bazel.CmdRequest{bazelFlags, bazelCmd.Env})
713
714 if err != nil {
715 return "", "", err
716 }
717 if len(resp.ErrorString) > 0 {
718 return "", "", fmt.Errorf(resp.ErrorString)
719 }
720 return resp.Stdout, resp.Stderr, nil
Jason Wu52cd1942022-09-08 15:37:57 +0000721 } else {
Chris Parsons9402ca82023-02-23 17:28:06 -0500722 eventHandler.Begin("bazel command")
723 defer eventHandler.End("bazel command")
724 stderr := &bytes.Buffer{}
725 bazelCmd.Stderr = stderr
726 if output, err := bazelCmd.Output(); err != nil {
727 return "", string(stderr.Bytes()),
728 fmt.Errorf("bazel command failed: %s\n---command---\n%s\n---env---\n%s\n---stderr---\n%s---",
729 err, bazelCmd, strings.Join(bazelCmd.Env, "\n"), stderr)
730 } else {
731 return string(output), string(stderr.Bytes()), nil
732 }
Jason Wu52cd1942022-09-08 15:37:57 +0000733 }
734}
735
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500736func (r *builtinBazelRunner) createBazelCommand(config Config, paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Jason Wu52cd1942022-09-08 15:37:57 +0000737 extraFlags ...string) *exec.Cmd {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000738 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000739 "--output_base=" + absolutePath(paths.outputBase),
740 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700741 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700742 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700743 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400744
Cole Faustb85d1a12022-11-08 18:14:01 -0800745 // We don't need to set --host_platforms because it's set in bazelrc files
746 // that the bazel shell script wrapper passes
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700747
748 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
749 "--experimental_repository_disable_download",
750
751 // Suppress noise
752 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500753 "--noshow_progress",
754 "--norun_validations",
755 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400756 cmdFlags = append(cmdFlags, extraFlags...)
757
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400758 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200759 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700760 extraEnv := []string{
761 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200762 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700763 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700764 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000765 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700766 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500767 // Disables local host detection of gcc; toolchain information is defined
768 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700769 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
770 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500771 for _, envvar := range allowedBazelEnvironmentVars {
772 val := config.Getenv(envvar)
773 if val == "" {
774 continue
775 }
776 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
777 }
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700778 bazelCmd.Env = append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400779
Jason Wu52cd1942022-09-08 15:37:57 +0000780 return bazelCmd
781}
782
783func printableCqueryCommand(bazelCmd *exec.Cmd) string {
784 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(bazelCmd.Args, "\" \"") + "\""
785 return outputString
786
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400787}
788
Sasha Smundak39a301c2022-12-29 17:11:49 -0800789func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500790 // TODO(cparsons): Define configuration transitions programmatically based
791 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400792 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500793#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400794# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500795#####################################################
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400796def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800797 if attr.os == "android" and attr.arch == "target":
798 target = "{PRODUCT}-{VARIANT}"
799 else:
800 target = "{PRODUCT}-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Yu Liue4312402023-01-18 09:15:31 -0800801 apex_name = ""
802 if attr.within_apex:
803 # //build/bazel/rules/apex:apex_name has to be set to a non_empty value,
804 # otherwise //build/bazel/rules/apex:non_apex will be true and the
805 # "-D__ANDROID_APEX__" compiler flag will be missing. Apex_name is used
806 # in some validation on bazel side which don't really apply in mixed
807 # build because soong will do the work, so we just set it to a fixed
808 # value here.
809 apex_name = "dcla_apex"
810 outputs = {
Cole Faustb85d1a12022-11-08 18:14:01 -0800811 "//command_line_option:platforms": "@soong_injection//product_config_platforms/products/{PRODUCT}-{VARIANT}:%s" % target,
Yu Liue4312402023-01-18 09:15:31 -0800812 "@//build/bazel/rules/apex:within_apex": attr.within_apex,
813 "@//build/bazel/rules/apex:min_sdk_version": attr.apex_sdk_version,
814 "@//build/bazel/rules/apex:apex_name": apex_name,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500815 }
816
Yu Liue4312402023-01-18 09:15:31 -0800817 return outputs
818
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400819_config_node_transition = transition(
820 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500821 inputs = [],
822 outputs = [
823 "//command_line_option:platforms",
Yu Liue4312402023-01-18 09:15:31 -0800824 "@//build/bazel/rules/apex:within_apex",
825 "@//build/bazel/rules/apex:min_sdk_version",
826 "@//build/bazel/rules/apex:apex_name",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500827 ],
828)
829
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400830def _passthrough_rule_impl(ctx):
831 return [DefaultInfo(files = depset(ctx.files.deps))]
832
833config_node = rule(
834 implementation = _passthrough_rule_impl,
835 attrs = {
Yu Liue4312402023-01-18 09:15:31 -0800836 "arch" : attr.string(mandatory = True),
837 "os" : attr.string(mandatory = True),
838 "within_apex" : attr.bool(default = False),
839 "apex_sdk_version" : attr.string(mandatory = True),
840 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400841 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
842 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500843)
844
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400845
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500846# Rule representing the root of the build, to depend on all Bazel targets that
847# are required for the build. Building this target will build the entire Bazel
848# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400849mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400850 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500851 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400852 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500853 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400854)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500855
856def _phony_root_impl(ctx):
857 return []
858
859# Rule to depend on other targets but build nothing.
860# This is useful as follows: building a target of this rule will generate
861# symlink forests for all dependencies of the target, without executing any
862# actions of the build.
863phony_root = rule(
864 implementation = _phony_root_impl,
865 attrs = {"deps" : attr.label_list()},
866)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400867`
Cole Faustb85d1a12022-11-08 18:14:01 -0800868
869 productReplacer := strings.NewReplacer(
870 "{PRODUCT}", context.targetProduct,
871 "{VARIANT}", context.targetBuildVariant)
872
873 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400874}
875
Sasha Smundak39a301c2022-12-29 17:11:49 -0800876func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500877 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
878 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400879 formatString := `
880# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400881load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
882
883%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400884
885mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400886 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000887 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400888)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500889
890phony_root(name = "phonyroot",
891 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000892 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500893)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400894`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400895 configNodeFormatString := `
896config_node(name = "%s",
897 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400898 os = "%s",
Yu Liue4312402023-01-18 09:15:31 -0800899 within_apex = %s,
900 apex_sdk_version = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400901 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000902 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400903)
904`
905
906 configNodesSection := ""
907
Chris Parsons787fb362021-10-14 18:43:51 -0400908 labelsByConfig := map[string][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500909
910 for _, val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200911 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400912 configString := getConfigString(val)
913 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400914 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400915
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500916 // Configs need to be sorted to maintain determinism of the BUILD file.
917 sortedConfigs := make([]string, 0, len(labelsByConfig))
918 for val := range labelsByConfig {
919 sortedConfigs = append(sortedConfigs, val)
920 }
921 sort.Slice(sortedConfigs, func(i, j int) bool { return sortedConfigs[i] < sortedConfigs[j] })
922
Jingwen Chen1e347862021-09-02 12:11:49 +0000923 allLabels := []string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500924 for _, configString := range sortedConfigs {
925 labels := labelsByConfig[configString]
Chris Parsons787fb362021-10-14 18:43:51 -0400926 configTokens := strings.Split(configString, "|")
Yu Liue4312402023-01-18 09:15:31 -0800927 if len(configTokens) < 2 {
Chris Parsons787fb362021-10-14 18:43:51 -0400928 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000929 }
Chris Parsons787fb362021-10-14 18:43:51 -0400930 archString := configTokens[0]
931 osString := configTokens[1]
Yu Liue4312402023-01-18 09:15:31 -0800932 withinApex := "False"
933 apexSdkVerString := ""
Chris Parsons787fb362021-10-14 18:43:51 -0400934 targetString := fmt.Sprintf("%s_%s", osString, archString)
Yu Liue4312402023-01-18 09:15:31 -0800935 if len(configTokens) > 2 {
936 targetString += "_" + configTokens[2]
937 if configTokens[2] == withinApexToString(true) {
938 withinApex = "True"
939 }
940 }
941 if len(configTokens) > 3 {
942 targetString += "_" + configTokens[3]
943 apexSdkVerString = configTokens[3]
944 }
Chris Parsons787fb362021-10-14 18:43:51 -0400945 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
946 labelsString := strings.Join(labels, ",\n ")
Yu Liue4312402023-01-18 09:15:31 -0800947 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, withinApex, apexSdkVerString,
948 labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400949 }
950
Jingwen Chen1e347862021-09-02 12:11:49 +0000951 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400952}
953
Chris Parsons944e7d02021-03-11 11:08:46 -0500954func indent(original string) string {
955 result := ""
956 for _, line := range strings.Split(original, "\n") {
957 result += " " + line + "\n"
958 }
959 return result
960}
961
Chris Parsons808d84c2021-03-09 20:43:32 -0500962// Returns the file contents of the buildroot.cquery file that should be used for the cquery
963// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800964// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500965// and grouped by their request type. The data retrieved for each label depends on its
966// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800967func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400968 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons38851d82023-03-15 00:19:32 -0400969 requestTypes := []cqueryRequest{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500970 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500971 cqueryId := getCqueryId(val)
972 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
Chris Parsons38851d82023-03-15 00:19:32 -0400973 if _, seenKey := requestTypeToCqueryIdEntries[val.requestType]; !seenKey {
974 requestTypes = append(requestTypes, val.requestType)
975 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500976 requestTypeToCqueryIdEntries[val.requestType] =
977 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
978 }
979 labelRegistrationMapSection := ""
980 functionDefSection := ""
981 mainSwitchSection := ""
982
983 mapDeclarationFormatString := `
984%s = {
985 %s
986}
987`
988 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800989def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500990%s
991`
992 mainSwitchSectionFormatString := `
993 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800994 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500995`
996
Chris Parsons38851d82023-03-15 00:19:32 -0400997 for _, requestType := range requestTypes {
Chris Parsons944e7d02021-03-11 11:08:46 -0500998 labelMapName := requestType.Name() + "_Labels"
999 functionName := requestType.Name() + "_Fn"
1000 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
1001 labelMapName,
1002 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
1003 functionDefSection += fmt.Sprintf(functionDefFormatString,
1004 functionName,
1005 indent(requestType.StarlarkFunctionBody()))
1006 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
1007 labelMapName, functionName)
1008 }
1009
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001010 formatString := `
1011# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001012
Cole Faustb85d1a12022-11-08 18:14:01 -08001013{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001014
Cole Faustb85d1a12022-11-08 18:14:01 -08001015{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001016
1017def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -04001018 # TODO(b/199363072): filegroups and file targets aren't associated with any
1019 # specific platform architecture in mixed builds. This is consistent with how
1020 # Soong treats filegroups, but it may not be the case with manually-written
1021 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -05001022 buildoptions = build_options(target)
Yu Liue4312402023-01-18 09:15:31 -08001023
Jingwen Chen8f222742021-10-07 12:02:23 +00001024 if buildoptions == None:
1025 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -04001026 # any specific platform architecture in mixed builds, so use the host.
1027 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -08001028 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -05001029 if len(platforms) != 1:
1030 # An individual configured target should have only one platform architecture.
1031 # Note that it's fine for there to be multiple architectures for the same label,
1032 # but each is its own configured target.
1033 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -08001034 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -05001035 if platform_name == "host":
1036 return "HOST"
Cole Faustb85d1a12022-11-08 18:14:01 -08001037 if not platform_name.startswith("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}"):
1038 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))
1039 platform_name = platform_name.removeprefix("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}").removeprefix("_")
Yu Liue4312402023-01-18 09:15:31 -08001040 config_key = ""
Cole Faustb85d1a12022-11-08 18:14:01 -08001041 if not platform_name:
Yu Liue4312402023-01-18 09:15:31 -08001042 config_key = "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -04001043 elif platform_name.startswith("android_"):
Yu Liue4312402023-01-18 09:15:31 -08001044 config_key = platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -04001045 elif platform_name.startswith("linux_"):
Yu Liue4312402023-01-18 09:15:31 -08001046 config_key = platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -04001047 else:
Cole Faustb85d1a12022-11-08 18:14:01 -08001048 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 -05001049
Yu Liue4312402023-01-18 09:15:31 -08001050 within_apex = buildoptions.get("//build/bazel/rules/apex:within_apex")
1051 apex_sdk_version = buildoptions.get("//build/bazel/rules/apex:min_sdk_version")
1052
1053 if within_apex:
1054 config_key += "|within_apex"
1055 if apex_sdk_version != None and len(apex_sdk_version) > 0:
1056 config_key += "|" + apex_sdk_version
1057
1058 return config_key
1059
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001060def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -05001061 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -05001062
Chris Parsons86dc2c22022-09-28 14:58:41 -04001063 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
1064 if id_string.startswith("//"):
1065 id_string = "@" + id_string
1066
Cole Faustb85d1a12022-11-08 18:14:01 -08001067 {MAIN_SWITCH_SECTION}
1068
Chris Parsons944e7d02021-03-11 11:08:46 -05001069 # This target was not requested via cquery, and thus must be a dependency
1070 # of a requested target.
1071 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001072`
Cole Faustb85d1a12022-11-08 18:14:01 -08001073 replacer := strings.NewReplacer(
1074 "{TARGET_PRODUCT}", context.targetProduct,
1075 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
1076 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
1077 "{FUNCTION_DEF_SECTION}", functionDefSection,
1078 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001079
Cole Faustb85d1a12022-11-08 18:14:01 -08001080 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001081}
1082
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001083// Returns a path containing build-related metadata required for interfacing
1084// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001085func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001086 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -05001087}
1088
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001089// Returns the path where the contents of the @soong_injection repository live.
1090// It is used by Soong to tell Bazel things it cannot over the command line.
1091func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001092 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001093}
1094
1095// Returns the path of the synthetic Bazel workspace that contains a symlink
1096// forest composed the whole source tree and BUILD files generated by bp2build.
1097func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001098 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001099}
1100
Jingwen Chen8c523582021-06-01 11:19:53 +00001101// Returns the path to the top level out dir ($OUT_DIR).
1102func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001103 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +00001104}
1105
Sasha Smundak4975c822022-11-16 15:28:18 -08001106const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
1107
1108var (
1109 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
1110 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
1111 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
1112)
1113
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001114// Issues commands to Bazel to receive results for all cquery requests
1115// queued in the BazelContext.
Liz Kammer690fbac2023-02-10 11:11:17 -05001116func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx invokeBazelContext) error {
1117 eventHandler := ctx.GetEventHandler()
1118 eventHandler.Begin("bazel")
1119 defer eventHandler.End("bazel")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001120
Sasha Smundak4975c822022-11-16 15:28:18 -08001121 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
1122 if err := os.MkdirAll(metricsDir, 0777); err != nil {
1123 return err
1124 }
1125 }
1126 context.results = make(map[cqueryKey]string)
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001127 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001128 return err
1129 }
1130 if err := context.runAquery(config, ctx); err != nil {
1131 return err
1132 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001133 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001134 return err
1135 }
1136
1137 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001138 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -08001139 return nil
1140}
1141
Liz Kammer690fbac2023-02-10 11:11:17 -05001142func (context *mixedBuildBazelContext) runCquery(config Config, ctx invokeBazelContext) error {
1143 eventHandler := ctx.GetEventHandler()
1144 eventHandler.Begin("cquery")
1145 defer eventHandler.End("cquery")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001146 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +02001147 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
1148 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
1149 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -05001150 if err != nil {
1151 return err
1152 }
1153 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001154 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001155 return err
1156 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001157 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001158 return err
1159 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001160 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001161 return err
1162 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001163 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001164 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001165 return err
1166 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001167
Yu Liue4312402023-01-18 09:15:31 -08001168 extraFlags := []string{"--output=starlark", "--starlark:file=" + absolutePath(cqueryFileRelpath)}
1169 if Bool(config.productVariables.ClangCoverage) {
1170 extraFlags = append(extraFlags, "--collect_code_coverage")
1171 }
1172
1173 cqueryCommandWithFlag := context.createBazelCommand(config, context.paths, bazel.CqueryBuildRootRunName, cqueryCmd, extraFlags...)
Liz Kammer690fbac2023-02-10 11:11:17 -05001174 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCommandWithFlag, eventHandler)
Wei Licbd181c2022-11-16 08:59:23 -08001175 if cqueryErr != nil {
1176 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001177 }
Jason Wu52cd1942022-09-08 15:37:57 +00001178 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", printableCqueryCommand(cqueryCommandWithFlag))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001179 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001180 return err
1181 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001182 cqueryResults := map[string]string{}
1183 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1184 if strings.Contains(outputLine, ">>") {
1185 splitLine := strings.SplitN(outputLine, ">>", 2)
1186 cqueryResults[splitLine[0]] = splitLine[1]
1187 }
1188 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001189 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001190 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001191 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001192 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001193 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001194 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001195 }
1196 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001197 return nil
1198}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001199
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001200func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1201 oldContents, err := os.ReadFile(path)
1202 if err != nil || !bytes.Equal(contents, oldContents) {
1203 err = os.WriteFile(path, contents, perm)
1204 }
1205 return nil
1206}
1207
Liz Kammer690fbac2023-02-10 11:11:17 -05001208func (context *mixedBuildBazelContext) runAquery(config Config, ctx invokeBazelContext) error {
1209 eventHandler := ctx.GetEventHandler()
1210 eventHandler.Begin("aquery")
1211 defer eventHandler.End("aquery")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001212 // Issue an aquery command to retrieve action information about the bazel build tree.
1213 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001214 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1215 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001216 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001217 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001218 extraFlags = append(extraFlags, "--collect_code_coverage")
1219 paths := make([]string, 0, 2)
1220 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001221 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001222 // TODO(b/259404593) convert path wildcard to regex values
1223 if p[i] == "*" {
1224 p[i] = ".*"
1225 }
1226 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001227 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1228 }
1229 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1230 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1231 }
1232 if len(paths) > 0 {
1233 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001234 }
1235 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001236 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
Liz Kammer690fbac2023-02-10 11:11:17 -05001237 extraFlags...), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001238 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001239 return err
1240 }
Liz Kammer690fbac2023-02-10 11:11:17 -05001241 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001242 return err
1243}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001244
Liz Kammer690fbac2023-02-10 11:11:17 -05001245func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx invokeBazelContext) error {
1246 eventHandler := ctx.GetEventHandler()
1247 eventHandler.Begin("symlinks")
1248 defer eventHandler.End("symlinks")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001249 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1250 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1251 // but some of symlinks may be required to resolve source dependencies of the build.
Liz Kammer690fbac2023-02-10 11:11:17 -05001252 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001253 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001254}
Chris Parsonsa798d962020-10-12 23:44:08 -04001255
Liz Kammera4655a92023-02-10 17:17:28 -05001256func (context *mixedBuildBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001257 return context.buildStatements
1258}
1259
Sasha Smundak39a301c2022-12-29 17:11:49 -08001260func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001261 return context.depsets
1262}
1263
Sasha Smundak39a301c2022-12-29 17:11:49 -08001264func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001265 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001266}
1267
Chris Parsonsa798d962020-10-12 23:44:08 -04001268// Singleton used for registering BUILD file ninja dependencies (needed
1269// for correctness of builds which use Bazel.
1270func BazelSingleton() Singleton {
1271 return &bazelSingleton{}
1272}
1273
1274type bazelSingleton struct{}
1275
1276func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001277 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001278 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001279 return
1280 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001281
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001282 // Add ninja file dependencies for files which all bazel invocations require.
1283 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001284 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001285 ctx.AddNinjaFileDeps(bazelBuildList)
1286
Sasha Smundak0e87b182022-12-01 11:46:11 -08001287 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001288 if err != nil {
1289 ctx.Errorf(err.Error())
1290 }
1291 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1292 for _, file := range files {
1293 ctx.AddNinjaFileDeps(file)
1294 }
1295
Chris Parsons1a7aca02022-04-25 22:35:15 -04001296 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1297 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001298 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001299 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1300 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001301 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1302 }
1303 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001304 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1305 if artifactPath == "bazel-out/volatile-status.txt" {
1306 // See https://bazel.build/docs/user-manual#workspace-status
1307 orderOnlies = append(orderOnlies, pathInBazelOut)
1308 } else {
1309 outputs = append(outputs, pathInBazelOut)
1310 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001311 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001312 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001313 ctx.Build(pctx, BuildParams{
1314 Rule: blueprint.Phony,
1315 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1316 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001317 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001318 })
1319 }
1320
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001321 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1322 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001323 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Liz Kammera4655a92023-02-10 17:17:28 -05001324 // nil build statements are a valid case where we do not create an action because it is
1325 // unnecessary or handled by other processing
1326 if buildStatement == nil {
1327 continue
1328 }
Sasha Smundak1da064c2022-06-08 16:36:16 -07001329 if len(buildStatement.Command) > 0 {
1330 rule := NewRuleBuilder(pctx, ctx)
1331 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1332 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1333 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1334 continue
1335 }
1336 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1337 // and thus require special treatment. If BuildStatement were an interface implementing
1338 // buildRule(ctx) function, the code here would just call it.
1339 // Unfortunately, the BuildStatement is defined in
1340 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1341 // because this would cause circular dependency. So, until we move aquery processing
1342 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001343 switch buildStatement.Mnemonic {
1344 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001345 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1346 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001347 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001348 // build-runfiles arguments are the manifest file and the target directory
1349 // where it creates the symlink tree according to this manifest (and then
1350 // writes the MANIFEST file to it).
1351 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1352 outManifestPath := outManifest.String()
1353 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1354 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1355 }
1356 outDir := filepath.Dir(outManifestPath)
1357 ctx.Build(pctx, BuildParams{
1358 Rule: buildRunfilesRule,
1359 Output: outManifest,
1360 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1361 Description: "symlink tree for " + outDir,
1362 Args: map[string]string{
1363 "outDir": outDir,
1364 },
1365 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001366 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001367 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001368 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001369 }
1370}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001371
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001372// Register bazel-owned build statements (obtained from the aquery invocation).
Liz Kammera4655a92023-02-10 17:17:28 -05001373func createCommand(cmd *RuleBuilderCommand, buildStatement *bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001374 // executionRoot is the action cwd.
1375 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1376
1377 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1378 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001379 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001380 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001381 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001382 }
1383 cmd.Text("&&")
1384 }
1385
1386 for _, pair := range buildStatement.Env {
1387 // Set per-action env variables, if any.
1388 cmd.Flag(pair.Key + "=" + pair.Value)
1389 }
1390
1391 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001392 if len(buildStatement.Command) > 16*1024 {
1393 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1394 WriteFileRule(ctx, commandFile, buildStatement.Command)
1395
1396 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1397 } else {
1398 cmd.Text(buildStatement.Command)
1399 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001400
1401 for _, outputPath := range buildStatement.OutputPaths {
1402 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1403 }
1404 for _, inputPath := range buildStatement.InputPaths {
1405 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1406 }
1407 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1408 otherDepsetName := bazelDepsetName(inputDepsetHash)
1409 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1410 }
1411
1412 if depfile := buildStatement.Depfile; depfile != nil {
1413 // The paths in depfile are relative to `executionRoot`.
1414 // Hence, they need to be corrected by replacing "bazel-out"
1415 // with the full `bazelOutDir`.
1416 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1417 // would be deemed missing.
1418 // (Note: The regexp uses a capture group because the version of sed
1419 // does not support a look-behind pattern.)
1420 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1421 bazelOutDir, *depfile)
1422 cmd.Text(replacement)
1423 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1424 }
1425
1426 for _, symlinkPath := range buildStatement.SymlinkPaths {
1427 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1428 }
1429}
1430
Chris Parsons8d6e4332021-02-22 16:13:50 -05001431func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001432 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001433}
1434
Chris Parsons787fb362021-10-14 18:43:51 -04001435func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001436 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001437 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001438 if key.configKey.osType.Class == Device {
1439 // For the generic Android, the expected result is "target|android", which
1440 // corresponds to the product_variable_config named "android_target" in
1441 // build/bazel/platforms/BUILD.bazel.
1442 arch = "target"
1443 } else {
1444 // Use host platform, which is currently hardcoded to be x86_64.
1445 arch = "x86_64"
1446 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001447 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001448 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001449 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001450 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001451 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001452 }
Yu Liue4312402023-01-18 09:15:31 -08001453 keyString := arch + "|" + osName
1454 if key.configKey.apexKey.WithinApex {
1455 keyString += "|" + withinApexToString(key.configKey.apexKey.WithinApex)
1456 }
1457
1458 if len(key.configKey.apexKey.ApexSdkVersion) > 0 {
1459 keyString += "|" + key.configKey.apexKey.ApexSdkVersion
1460 }
1461
1462 return keyString
Chris Parsons787fb362021-10-14 18:43:51 -04001463}
1464
Chris Parsonsf874e462022-05-10 13:50:12 -04001465func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001466 return configKey{
1467 // use string because Arch is not a valid key in go
1468 arch: ctx.Arch().String(),
1469 osType: ctx.Os(),
1470 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001471}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001472
Yu Liue4312402023-01-18 09:15:31 -08001473func GetConfigKeyApexVariant(ctx BaseModuleContext, apexKey *ApexConfigKey) configKey {
1474 configKey := GetConfigKey(ctx)
1475
1476 if apexKey != nil {
1477 configKey.apexKey = ApexConfigKey{
1478 WithinApex: apexKey.WithinApex,
1479 ApexSdkVersion: apexKey.ApexSdkVersion,
1480 }
1481 }
1482
1483 return configKey
1484}
1485
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001486func bazelDepsetName(contentHash string) string {
1487 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001488}
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001489
1490func EnvironmentVarsFile(config Config) string {
1491 return fmt.Sprintf(bazel.GeneratedBazelFileWarning+`
1492_env = %s
1493
1494env = _env
1495`,
1496 starlark_fmt.PrintStringList(allowedBazelEnvironmentVars, 0),
1497 )
1498}