blob: debc7a2fdac30b9fc6fec24d1c53ce0082f23df7 [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 {
MarkDacekf47e1422023-04-19 16:47:36 +000089 mixedBuildEnabled := MixedBuildsEnabled(ctx)
90 queueMixedBuild := mixedBuildMod.IsMixedBuildSupported(ctx) && mixedBuildEnabled == MixedBuildEnabled
MarkDacek9c094ca2023-03-16 19:15:19 +000091 if queueMixedBuild {
Chris Parsonsf874e462022-05-10 13:50:12 -040092 mixedBuildMod.QueueBazelCall(ctx)
93 }
94 }
95 }
96}
97
Liz Kammerf29df7c2021-04-02 13:37:39 -040098type cqueryRequest interface {
99 // Name returns a string name for this request type. Such request type names must be unique,
100 // and must only consist of alphanumeric characters.
101 Name() string
102
103 // StarlarkFunctionBody returns a starlark function body to process this request type.
104 // The returned string is the body of a Starlark function which obtains
105 // all request-relevant information about a target and returns a string containing
106 // this information.
107 // The function should have the following properties:
Cole Faust97d15272022-11-22 14:08:59 -0800108 // - The arguments are `target` (a configured target) and `id_string` (the label + configuration).
Liz Kammerf29df7c2021-04-02 13:37:39 -0400109 // - The return value must be a string.
110 // - The function body should not be indented outside of its own scope.
111 StarlarkFunctionBody() string
112}
113
Chris Parsons787fb362021-10-14 18:43:51 -0400114// Portion of cquery map key to describe target configuration.
115type configKey struct {
Yu Liue4312402023-01-18 09:15:31 -0800116 arch string
117 osType OsType
118 apexKey ApexConfigKey
119}
120
121type ApexConfigKey struct {
122 WithinApex bool
123 ApexSdkVersion string
124}
125
126func (c ApexConfigKey) String() string {
127 return fmt.Sprintf("%s_%s", withinApexToString(c.WithinApex), c.ApexSdkVersion)
128}
129
130func withinApexToString(withinApex bool) string {
131 if withinApex {
132 return "within_apex"
133 }
134 return ""
Chris Parsons787fb362021-10-14 18:43:51 -0400135}
136
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700137func (c configKey) String() string {
Yu Liue4312402023-01-18 09:15:31 -0800138 return fmt.Sprintf("%s::%s::%s", c.arch, c.osType, c.apexKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700139}
140
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400141// Map key to describe bazel cquery requests.
142type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400143 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400144 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400145 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400146}
147
Chris Parsons86dc2c22022-09-28 14:58:41 -0400148func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
149 if strings.HasPrefix(label, "//") {
150 // Normalize Bazel labels to specify main repository explicitly.
151 label = "@" + label
152 }
153 return cqueryKey{label, cqueryRequest, cfgKey}
154}
155
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700156func (c cqueryKey) String() string {
157 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700158}
159
Liz Kammer690fbac2023-02-10 11:11:17 -0500160type invokeBazelContext interface {
161 GetEventHandler() *metrics.EventHandler
162}
163
Chris Parsonsf874e462022-05-10 13:50:12 -0400164// BazelContext is a context object useful for interacting with Bazel during
165// the course of a build. Use of Bazel to evaluate part of the build graph
166// is referred to as a "mixed build". (Some modules are managed by Soong,
167// some are managed by Bazel). To facilitate interop between these build
168// subgraphs, Soong may make requests to Bazel and evaluate their responses
169// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400170type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400171 // Add a cquery request to the bazel request queue. All queued requests
172 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
173 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
174
175 // ** Cquery Results Retrieval Functions
176 // The below functions pertain to retrieving cquery results from a prior
177 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400178
179 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400180 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500181
Chris Parsons944e7d02021-03-11 11:08:46 -0500182 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400183 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400184
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000185 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400186 // TODO(b/232976601): Remove.
187 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000188
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700189 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400190 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700191
Sasha Smundakedd16662022-10-07 14:44:50 -0700192 // Returns the results of the GetCcUnstrippedInfo query
193 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
194
Chris Parsonsf874e462022-05-10 13:50:12 -0400195 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400196
197 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800198 // queued in the BazelContext. The ctx argument is optional and is only
199 // used for performance data collection
Liz Kammer690fbac2023-02-10 11:11:17 -0500200 InvokeBazel(config Config, ctx invokeBazelContext) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400201
Chris Parsonsad876012022-08-20 14:48:32 -0400202 // Returns true if Bazel handling is enabled for the module with the given name.
203 // Note that this only implies "bazel mixed build" allowlisting. The caller
204 // should independently verify the module is eligible for Bazel handling
205 // (for example, that it is MixedBuildBuildable).
Yu Liue4312402023-01-18 09:15:31 -0800206 IsModuleNameAllowed(moduleName string, withinApex bool) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500207
Yu Liubfb23622023-02-22 10:42:15 -0800208 IsModuleDclaAllowed(moduleName string) bool
209
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500210 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
211 OutputBase() string
212
213 // Returns build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500214 BuildStatementsToRegister() []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400215
216 // Returns the depsets defined in Bazel's aquery response.
217 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400218}
219
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400220type bazelRunner interface {
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500221 createBazelCommand(config Config, paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) *exec.Cmd
Liz Kammer690fbac2023-02-10 11:11:17 -0500222 issueBazelCommand(bazelCmd *exec.Cmd, eventHandler *metrics.EventHandler) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400223}
224
225type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000226 homeDir string
227 bazelPath string
228 outputBase string
229 workspaceDir string
230 soongOutDir string
231 metricsDir string
232 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400233}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400234
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400235// A context object which tracks queued requests that need to be made to Bazel,
236// and their results after the requests have been made.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800237type mixedBuildBazelContext struct {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400238 bazelRunner
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500239 paths *bazelPaths
240 // cquery requests that have not yet been issued to Bazel. This list is maintained
241 // in a sorted state, and is guaranteed to have no duplicates.
242 requests []cqueryKey
243 requestMutex sync.Mutex // requests can be written in parallel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400244
245 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500246
247 // Build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500248 buildStatements []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400249
250 // Depsets which should be used for Bazel's build statements.
251 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400252
253 // Per-module allowlist/denylist functionality to control whether analysis of
254 // modules are handled by Bazel. For modules which do not have a Bazel definition
255 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
256 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
257 // Per-module denylist to opt modules out of bazel handling.
258 bazelDisabledModules map[string]bool
259 // Per-module allowlist to opt modules in to bazel handling.
260 bazelEnabledModules map[string]bool
Yu Liue4312402023-01-18 09:15:31 -0800261 // DCLA modules are enabled when used in apex.
262 bazelDclaEnabledModules map[string]bool
Chris Parsonsad876012022-08-20 14:48:32 -0400263 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
264 modulesDefaultToBazel bool
Cole Faustb85d1a12022-11-08 18:14:01 -0800265
266 targetProduct string
267 targetBuildVariant string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400268}
269
Sasha Smundak39a301c2022-12-29 17:11:49 -0800270var _ BazelContext = &mixedBuildBazelContext{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400271
272// A bazel context to use when Bazel is disabled.
273type noopBazelContext struct{}
274
275var _ BazelContext = noopBazelContext{}
276
277// A bazel context to use for tests.
278type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400279 OutputBaseDir string
280
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000281 LabelToOutputFiles map[string][]string
282 LabelToCcInfo map[string]cquery.CcInfo
283 LabelToPythonBinary map[string]string
Liz Kammerbe6a7122022-11-04 16:05:11 -0400284 LabelToApexInfo map[string]cquery.ApexInfo
Sasha Smundakedd16662022-10-07 14:44:50 -0700285 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
Yu Liue4312402023-01-18 09:15:31 -0800286
287 BazelRequests map[string]bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400288}
289
Yu Liue4312402023-01-18 09:15:31 -0800290func (m MockBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
291 key := BuildMockBazelContextRequestKey(label, requestType, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
292 if m.BazelRequests == nil {
293 m.BazelRequests = make(map[string]bool)
294 }
295 m.BazelRequests[key] = true
Chris Parsons8d6e4332021-02-22 16:13:50 -0500296}
297
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700298func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500299 result, ok := m.LabelToOutputFiles[label]
300 if !ok {
301 return []string{}, fmt.Errorf("no target with label %q in LabelToOutputFiles", label)
302 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400303 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400304}
305
Yu Liue4312402023-01-18 09:15:31 -0800306func (m MockBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500307 result, ok := m.LabelToCcInfo[label]
308 if !ok {
Yu Liue4312402023-01-18 09:15:31 -0800309 key := BuildMockBazelContextResultKey(label, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
310 result, ok = m.LabelToCcInfo[key]
311 if !ok {
312 return cquery.CcInfo{}, fmt.Errorf("no target with label %q in LabelToCcInfo", label)
313 }
Sam Delmericoce39f832023-01-23 14:04:24 -0500314 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400315 return result, nil
316}
317
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700318func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500319 result, ok := m.LabelToPythonBinary[label]
320 if !ok {
321 return "", fmt.Errorf("no target with label %q in LabelToPythonBinary", label)
322 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400323 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000324}
325
Liz Kammerbe6a7122022-11-04 16:05:11 -0400326func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500327 result, ok := m.LabelToApexInfo[label]
328 if !ok {
329 return cquery.ApexInfo{}, fmt.Errorf("no target with label %q in LabelToApexInfo", label)
330 }
Liz Kammer0e255ef2022-11-04 16:07:04 -0400331 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700332}
333
Sasha Smundakedd16662022-10-07 14:44:50 -0700334func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500335 result, ok := m.LabelToCcBinary[label]
336 if !ok {
337 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no target with label %q in LabelToCcBinary", label)
338 }
Sasha Smundakedd16662022-10-07 14:44:50 -0700339 return result, nil
340}
341
Liz Kammer690fbac2023-02-10 11:11:17 -0500342func (m MockBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400343 panic("unimplemented")
344}
345
Yu Liue4312402023-01-18 09:15:31 -0800346func (m MockBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400347 return true
348}
349
Yu Liubfb23622023-02-22 10:42:15 -0800350func (m MockBazelContext) IsModuleDclaAllowed(_ string) bool {
351 return true
352}
353
Liz Kammera92e8442021-04-07 20:25:21 -0400354func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500355
Liz Kammera4655a92023-02-10 17:17:28 -0500356func (m MockBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
357 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500358}
359
Chris Parsons1a7aca02022-04-25 22:35:15 -0400360func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
361 return []bazel.AqueryDepset{}
362}
363
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400364var _ BazelContext = MockBazelContext{}
365
Yu Liue4312402023-01-18 09:15:31 -0800366func BuildMockBazelContextRequestKey(label string, request cqueryRequest, 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, request.Name(), cfgKey.String()}, "_")
374}
375
376func BuildMockBazelContextResultKey(label string, arch string, osType OsType, apexKey ApexConfigKey) string {
377 cfgKey := configKey{
378 arch: arch,
379 osType: osType,
380 apexKey: apexKey,
381 }
382
383 return strings.Join([]string{label, cfgKey.String()}, "_")
384}
385
Sasha Smundak39a301c2022-12-29 17:11:49 -0800386func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400387 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400388 bazelCtx.requestMutex.Lock()
389 defer bazelCtx.requestMutex.Unlock()
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500390
391 // Insert key into requests, maintaining the sort, and only if it's not duplicate.
392 keyString := key.String()
393 foundEqual := false
394 notLessThanKeyString := func(i int) bool {
395 s := bazelCtx.requests[i].String()
396 v := strings.Compare(s, keyString)
397 if v == 0 {
398 foundEqual = true
399 }
400 return v >= 0
401 }
402 targetIndex := sort.Search(len(bazelCtx.requests), notLessThanKeyString)
403 if foundEqual {
404 return
405 }
406
407 if targetIndex == len(bazelCtx.requests) {
408 bazelCtx.requests = append(bazelCtx.requests, key)
409 } else {
410 bazelCtx.requests = append(bazelCtx.requests[:targetIndex+1], bazelCtx.requests[targetIndex:]...)
411 bazelCtx.requests[targetIndex] = key
412 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400413}
414
Sasha Smundak39a301c2022-12-29 17:11:49 -0800415func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400416 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400417 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500418 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400419
Chris Parsonsf874e462022-05-10 13:50:12 -0400420 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400421 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400422 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400423}
424
Sasha Smundak39a301c2022-12-29 17:11:49 -0800425func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400426 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400427 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000428 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400429 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000430 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400431 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 +0000432}
433
Sasha Smundak39a301c2022-12-29 17:11:49 -0800434func (bazelCtx *mixedBuildBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400435 key := makeCqueryKey(label, cquery.GetPythonBinary, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400436 if rawString, ok := bazelCtx.results[key]; ok {
437 bazelOutput := strings.TrimSpace(rawString)
438 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
439 }
440 return "", fmt.Errorf("no bazel response found for %v", key)
441}
442
Sasha Smundak39a301c2022-12-29 17:11:49 -0800443func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400444 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700445 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500446 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700447 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400448 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700449}
450
Sasha Smundak39a301c2022-12-29 17:11:49 -0800451func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700452 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
453 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500454 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700455 }
456 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
457}
458
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700459func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500460 panic("unimplemented")
461}
462
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700463func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500464 panic("unimplemented")
465}
466
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700467func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400468 panic("unimplemented")
469}
470
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700471func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000472 panic("unimplemented")
473}
474
Liz Kammerbe6a7122022-11-04 16:05:11 -0400475func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700476 panic("unimplemented")
477}
478
Sasha Smundakedd16662022-10-07 14:44:50 -0700479func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
480 //TODO implement me
481 panic("implement me")
482}
483
Liz Kammer690fbac2023-02-10 11:11:17 -0500484func (n noopBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400485 panic("unimplemented")
486}
487
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500488func (m noopBazelContext) OutputBase() string {
489 return ""
490}
491
Yu Liue4312402023-01-18 09:15:31 -0800492func (n noopBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400493 return false
494}
495
Yu Liubfb23622023-02-22 10:42:15 -0800496func (n noopBazelContext) IsModuleDclaAllowed(_ string) bool {
497 return false
498}
499
Liz Kammera4655a92023-02-10 17:17:28 -0500500func (m noopBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
501 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500502}
503
Chris Parsons1a7aca02022-04-25 22:35:15 -0400504func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
505 return []bazel.AqueryDepset{}
506}
507
Yu Liue4312402023-01-18 09:15:31 -0800508func addToStringSet(set map[string]bool, items []string) {
509 for _, item := range items {
510 set[item] = true
511 }
512}
513
Cole Faust705968d2022-12-14 11:32:05 -0800514func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400515 disabledModules := map[string]bool{}
516 enabledModules := map[string]bool{}
517
Cole Faust705968d2022-12-14 11:32:05 -0800518 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400519 case BazelProdMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800520 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800521 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000522 enabledModules[enabledAdHocModule] = true
523 }
MarkDacekb78465d2022-10-18 20:10:16 +0000524 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400525 // Staging mode includes all prod modules plus all staging modules.
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800526 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
527 addToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800528 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000529 enabledModules[enabledAdHocModule] = true
530 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400531 case BazelDevMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800532 addToStringSet(disabledModules, allowlists.MixedBuildsDisabledList)
Chris Parsonsef615e52022-08-18 22:04:11 -0400533 default:
Cole Faust705968d2022-12-14 11:32:05 -0800534 panic("Expected BazelProdMode, BazelStagingMode, or BazelDevMode")
535 }
536 return enabledModules, disabledModules
537}
538
539func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
540 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
541 enabledList := make([]string, 0, len(enabledModules))
542 for module := range enabledModules {
543 if !disabledModules[module] {
544 enabledList = append(enabledList, module)
545 }
546 }
547 sort.Strings(enabledList)
548 return enabledList
549}
550
551func NewBazelContext(c *config) (BazelContext, error) {
552 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode && c.BuildMode != BazelDevMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400553 return noopBazelContext{}, nil
554 }
555
Cole Faust705968d2022-12-14 11:32:05 -0800556 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
557
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800558 paths := bazelPaths{
559 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400560 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800561 var missing []string
562 vars := []struct {
563 name string
564 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000565
566 // True if the environment variable needs to be tracked so that changes to the variable
567 // cause the ninja file to be regenerated, false otherwise. False should only be set for
568 // environment variables that have no effect on the generated ninja file.
569 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800570 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000571 {"BAZEL_HOME", &paths.homeDir, true},
572 {"BAZEL_PATH", &paths.bazelPath, true},
573 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
574 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
575 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
576 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800577 }
578 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000579 if v.track {
580 if s := c.Getenv(v.name); len(s) > 1 {
581 *v.ptr = s
582 continue
583 }
584 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800585 *v.ptr = s
586 } else {
587 missing = append(missing, v.name)
588 }
589 }
590 if len(missing) > 0 {
591 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
592 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800593
594 targetBuildVariant := "user"
595 if c.Eng() {
596 targetBuildVariant = "eng"
597 } else if c.Debuggable() {
598 targetBuildVariant = "userdebug"
599 }
600 targetProduct := "unknown"
601 if c.HasDeviceProduct() {
602 targetProduct = c.DeviceProduct()
603 }
Yu Liue4312402023-01-18 09:15:31 -0800604 dclaMixedBuildsEnabledList := []string{}
605 if c.BuildMode == BazelProdMode {
606 dclaMixedBuildsEnabledList = allowlists.ProdDclaMixedBuildsEnabledList
607 } else if c.BuildMode == BazelStagingMode {
608 dclaMixedBuildsEnabledList = append(allowlists.ProdDclaMixedBuildsEnabledList,
609 allowlists.StagingDclaMixedBuildsEnabledList...)
610 }
611 dclaEnabledModules := map[string]bool{}
612 addToStringSet(dclaEnabledModules, dclaMixedBuildsEnabledList)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800613 return &mixedBuildBazelContext{
Chris Parsons9402ca82023-02-23 17:28:06 -0500614 bazelRunner: &builtinBazelRunner{c.UseBazelProxy, absolutePath(c.outDir)},
Yu Liue4312402023-01-18 09:15:31 -0800615 paths: &paths,
616 modulesDefaultToBazel: c.BuildMode == BazelDevMode,
617 bazelEnabledModules: enabledModules,
618 bazelDisabledModules: disabledModules,
619 bazelDclaEnabledModules: dclaEnabledModules,
620 targetProduct: targetProduct,
621 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400622 }, nil
623}
624
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400625func (p *bazelPaths) BazelMetricsDir() string {
626 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000627}
628
Yu Liue4312402023-01-18 09:15:31 -0800629func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string, withinApex bool) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400630 if context.bazelDisabledModules[moduleName] {
631 return false
632 }
633 if context.bazelEnabledModules[moduleName] {
634 return true
635 }
Yu Liubfb23622023-02-22 10:42:15 -0800636 if withinApex && context.IsModuleDclaAllowed(moduleName) {
Yu Liue4312402023-01-18 09:15:31 -0800637 return true
638 }
639
Chris Parsonsad876012022-08-20 14:48:32 -0400640 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400641}
642
Yu Liubfb23622023-02-22 10:42:15 -0800643func (context *mixedBuildBazelContext) IsModuleDclaAllowed(moduleName string) bool {
644 return context.bazelDclaEnabledModules[moduleName]
645}
646
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400647func pwdPrefix() string {
648 // Darwin doesn't have /proc
649 if runtime.GOOS != "darwin" {
650 return "PWD=/proc/self/cwd"
651 }
652 return ""
653}
654
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400655type bazelCommand struct {
656 command string
657 // query or label
658 expression string
659}
660
661type mockBazelRunner struct {
662 bazelCommandResults map[bazelCommand]string
Jason Wu52cd1942022-09-08 15:37:57 +0000663 // use *exec.Cmd as a key to get the bazelCommand, the map will be used in issueBazelCommand()
664 // Register createBazelCommand() invocations. Later, an
665 // issueBazelCommand() invocation can be mapped to the *exec.Cmd instance
666 // and then to the expected result via bazelCommandResults
667 tokens map[*exec.Cmd]bazelCommand
668 commands []bazelCommand
669 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400670}
671
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500672func (r *mockBazelRunner) createBazelCommand(_ Config, _ *bazelPaths, _ bazel.RunName,
Jason Wu52cd1942022-09-08 15:37:57 +0000673 command bazelCommand, extraFlags ...string) *exec.Cmd {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400674 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700675 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Jason Wu52cd1942022-09-08 15:37:57 +0000676 cmd := &exec.Cmd{}
677 if r.tokens == nil {
678 r.tokens = make(map[*exec.Cmd]bazelCommand)
679 }
680 r.tokens[cmd] = command
681 return cmd
682}
683
Liz Kammer690fbac2023-02-10 11:11:17 -0500684func (r *mockBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd, _ *metrics.EventHandler) (string, string, error) {
Jason Wu52cd1942022-09-08 15:37:57 +0000685 if command, ok := r.tokens[bazelCmd]; ok {
686 return r.bazelCommandResults[command], "", nil
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400687 }
688 return "", "", nil
689}
690
Chris Parsons9402ca82023-02-23 17:28:06 -0500691type builtinBazelRunner struct {
692 useBazelProxy bool
693 outDir string
694}
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400695
Chris Parsons808d84c2021-03-09 20:43:32 -0500696// Issues the given bazel command with given build label and additional flags.
697// Returns (stdout, stderr, error). The first and second return values are strings
698// containing the stdout and stderr of the run command, and an error is returned if
699// the invocation returned an error code.
Liz Kammer690fbac2023-02-10 11:11:17 -0500700func (r *builtinBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd, eventHandler *metrics.EventHandler) (string, string, error) {
Chris Parsons9402ca82023-02-23 17:28:06 -0500701 if r.useBazelProxy {
702 eventHandler.Begin("client_proxy")
703 defer eventHandler.End("client_proxy")
704 proxyClient := bazel.NewProxyClient(r.outDir)
705 // Omit the arg containing the Bazel binary, as that is handled by the proxy
706 // server.
707 bazelFlags := bazelCmd.Args[1:]
708 // TODO(b/270989498): Refactor these functions to not take exec.Cmd, as its
709 // not actually executed for client proxying.
710 resp, err := proxyClient.IssueCommand(bazel.CmdRequest{bazelFlags, bazelCmd.Env})
711
712 if err != nil {
713 return "", "", err
714 }
715 if len(resp.ErrorString) > 0 {
716 return "", "", fmt.Errorf(resp.ErrorString)
717 }
718 return resp.Stdout, resp.Stderr, nil
Jason Wu52cd1942022-09-08 15:37:57 +0000719 } else {
Chris Parsons9402ca82023-02-23 17:28:06 -0500720 eventHandler.Begin("bazel command")
721 defer eventHandler.End("bazel command")
722 stderr := &bytes.Buffer{}
723 bazelCmd.Stderr = stderr
724 if output, err := bazelCmd.Output(); err != nil {
725 return "", string(stderr.Bytes()),
726 fmt.Errorf("bazel command failed: %s\n---command---\n%s\n---env---\n%s\n---stderr---\n%s---",
727 err, bazelCmd, strings.Join(bazelCmd.Env, "\n"), stderr)
728 } else {
729 return string(output), string(stderr.Bytes()), nil
730 }
Jason Wu52cd1942022-09-08 15:37:57 +0000731 }
732}
733
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500734func (r *builtinBazelRunner) createBazelCommand(config Config, paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Jason Wu52cd1942022-09-08 15:37:57 +0000735 extraFlags ...string) *exec.Cmd {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000736 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000737 "--output_base=" + absolutePath(paths.outputBase),
738 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700739 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700740 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700741 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400742
Cole Faustb85d1a12022-11-08 18:14:01 -0800743 // We don't need to set --host_platforms because it's set in bazelrc files
744 // that the bazel shell script wrapper passes
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700745
746 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
747 "--experimental_repository_disable_download",
748
749 // Suppress noise
750 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500751 "--noshow_progress",
752 "--norun_validations",
753 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400754 cmdFlags = append(cmdFlags, extraFlags...)
755
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400756 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200757 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700758 extraEnv := []string{
759 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200760 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700761 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700762 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000763 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700764 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500765 // Disables local host detection of gcc; toolchain information is defined
766 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700767 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
768 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500769 for _, envvar := range allowedBazelEnvironmentVars {
770 val := config.Getenv(envvar)
771 if val == "" {
772 continue
773 }
774 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
775 }
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700776 bazelCmd.Env = append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400777
Jason Wu52cd1942022-09-08 15:37:57 +0000778 return bazelCmd
779}
780
781func printableCqueryCommand(bazelCmd *exec.Cmd) string {
782 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(bazelCmd.Args, "\" \"") + "\""
783 return outputString
784
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400785}
786
Sasha Smundak39a301c2022-12-29 17:11:49 -0800787func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500788 // TODO(cparsons): Define configuration transitions programmatically based
789 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400790 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500791#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400792# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500793#####################################################
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400794def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800795 if attr.os == "android" and attr.arch == "target":
796 target = "{PRODUCT}-{VARIANT}"
797 else:
798 target = "{PRODUCT}-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Yu Liue4312402023-01-18 09:15:31 -0800799 apex_name = ""
800 if attr.within_apex:
801 # //build/bazel/rules/apex:apex_name has to be set to a non_empty value,
802 # otherwise //build/bazel/rules/apex:non_apex will be true and the
803 # "-D__ANDROID_APEX__" compiler flag will be missing. Apex_name is used
804 # in some validation on bazel side which don't really apply in mixed
805 # build because soong will do the work, so we just set it to a fixed
806 # value here.
807 apex_name = "dcla_apex"
808 outputs = {
Cole Faustb85d1a12022-11-08 18:14:01 -0800809 "//command_line_option:platforms": "@soong_injection//product_config_platforms/products/{PRODUCT}-{VARIANT}:%s" % target,
Yu Liue4312402023-01-18 09:15:31 -0800810 "@//build/bazel/rules/apex:within_apex": attr.within_apex,
811 "@//build/bazel/rules/apex:min_sdk_version": attr.apex_sdk_version,
812 "@//build/bazel/rules/apex:apex_name": apex_name,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500813 }
814
Yu Liue4312402023-01-18 09:15:31 -0800815 return outputs
816
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400817_config_node_transition = transition(
818 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500819 inputs = [],
820 outputs = [
821 "//command_line_option:platforms",
Yu Liue4312402023-01-18 09:15:31 -0800822 "@//build/bazel/rules/apex:within_apex",
823 "@//build/bazel/rules/apex:min_sdk_version",
824 "@//build/bazel/rules/apex:apex_name",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500825 ],
826)
827
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400828def _passthrough_rule_impl(ctx):
829 return [DefaultInfo(files = depset(ctx.files.deps))]
830
831config_node = rule(
832 implementation = _passthrough_rule_impl,
833 attrs = {
Yu Liue4312402023-01-18 09:15:31 -0800834 "arch" : attr.string(mandatory = True),
835 "os" : attr.string(mandatory = True),
836 "within_apex" : attr.bool(default = False),
837 "apex_sdk_version" : attr.string(mandatory = True),
838 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400839 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
840 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500841)
842
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400843
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500844# Rule representing the root of the build, to depend on all Bazel targets that
845# are required for the build. Building this target will build the entire Bazel
846# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400847mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400848 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500849 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400850 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500851 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400852)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500853
854def _phony_root_impl(ctx):
855 return []
856
857# Rule to depend on other targets but build nothing.
858# This is useful as follows: building a target of this rule will generate
859# symlink forests for all dependencies of the target, without executing any
860# actions of the build.
861phony_root = rule(
862 implementation = _phony_root_impl,
863 attrs = {"deps" : attr.label_list()},
864)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400865`
Cole Faustb85d1a12022-11-08 18:14:01 -0800866
867 productReplacer := strings.NewReplacer(
868 "{PRODUCT}", context.targetProduct,
869 "{VARIANT}", context.targetBuildVariant)
870
871 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400872}
873
Sasha Smundak39a301c2022-12-29 17:11:49 -0800874func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500875 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
876 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400877 formatString := `
878# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400879load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
880
881%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400882
883mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400884 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000885 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400886)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500887
888phony_root(name = "phonyroot",
889 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000890 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500891)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400892`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400893 configNodeFormatString := `
894config_node(name = "%s",
895 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400896 os = "%s",
Yu Liue4312402023-01-18 09:15:31 -0800897 within_apex = %s,
898 apex_sdk_version = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400899 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000900 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400901)
902`
903
904 configNodesSection := ""
905
Chris Parsons787fb362021-10-14 18:43:51 -0400906 labelsByConfig := map[string][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500907
908 for _, val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200909 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400910 configString := getConfigString(val)
911 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400912 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400913
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500914 // Configs need to be sorted to maintain determinism of the BUILD file.
915 sortedConfigs := make([]string, 0, len(labelsByConfig))
916 for val := range labelsByConfig {
917 sortedConfigs = append(sortedConfigs, val)
918 }
919 sort.Slice(sortedConfigs, func(i, j int) bool { return sortedConfigs[i] < sortedConfigs[j] })
920
Jingwen Chen1e347862021-09-02 12:11:49 +0000921 allLabels := []string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500922 for _, configString := range sortedConfigs {
923 labels := labelsByConfig[configString]
Chris Parsons787fb362021-10-14 18:43:51 -0400924 configTokens := strings.Split(configString, "|")
Yu Liue4312402023-01-18 09:15:31 -0800925 if len(configTokens) < 2 {
Chris Parsons787fb362021-10-14 18:43:51 -0400926 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000927 }
Chris Parsons787fb362021-10-14 18:43:51 -0400928 archString := configTokens[0]
929 osString := configTokens[1]
Yu Liue4312402023-01-18 09:15:31 -0800930 withinApex := "False"
931 apexSdkVerString := ""
Chris Parsons787fb362021-10-14 18:43:51 -0400932 targetString := fmt.Sprintf("%s_%s", osString, archString)
Yu Liue4312402023-01-18 09:15:31 -0800933 if len(configTokens) > 2 {
934 targetString += "_" + configTokens[2]
935 if configTokens[2] == withinApexToString(true) {
936 withinApex = "True"
937 }
938 }
939 if len(configTokens) > 3 {
940 targetString += "_" + configTokens[3]
941 apexSdkVerString = configTokens[3]
942 }
Chris Parsons787fb362021-10-14 18:43:51 -0400943 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
944 labelsString := strings.Join(labels, ",\n ")
Yu Liue4312402023-01-18 09:15:31 -0800945 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, withinApex, apexSdkVerString,
946 labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400947 }
948
Jingwen Chen1e347862021-09-02 12:11:49 +0000949 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400950}
951
Chris Parsons944e7d02021-03-11 11:08:46 -0500952func indent(original string) string {
953 result := ""
954 for _, line := range strings.Split(original, "\n") {
955 result += " " + line + "\n"
956 }
957 return result
958}
959
Chris Parsons808d84c2021-03-09 20:43:32 -0500960// Returns the file contents of the buildroot.cquery file that should be used for the cquery
961// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800962// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500963// and grouped by their request type. The data retrieved for each label depends on its
964// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800965func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400966 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons38851d82023-03-15 00:19:32 -0400967 requestTypes := []cqueryRequest{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500968 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500969 cqueryId := getCqueryId(val)
970 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
Chris Parsons38851d82023-03-15 00:19:32 -0400971 if _, seenKey := requestTypeToCqueryIdEntries[val.requestType]; !seenKey {
972 requestTypes = append(requestTypes, val.requestType)
973 }
Chris Parsons944e7d02021-03-11 11:08:46 -0500974 requestTypeToCqueryIdEntries[val.requestType] =
975 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
976 }
977 labelRegistrationMapSection := ""
978 functionDefSection := ""
979 mainSwitchSection := ""
980
981 mapDeclarationFormatString := `
982%s = {
983 %s
984}
985`
986 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800987def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500988%s
989`
990 mainSwitchSectionFormatString := `
991 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800992 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500993`
994
Chris Parsons38851d82023-03-15 00:19:32 -0400995 for _, requestType := range requestTypes {
Chris Parsons944e7d02021-03-11 11:08:46 -0500996 labelMapName := requestType.Name() + "_Labels"
997 functionName := requestType.Name() + "_Fn"
998 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
999 labelMapName,
1000 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
1001 functionDefSection += fmt.Sprintf(functionDefFormatString,
1002 functionName,
1003 indent(requestType.StarlarkFunctionBody()))
1004 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
1005 labelMapName, functionName)
1006 }
1007
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001008 formatString := `
1009# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001010
Cole Faustb85d1a12022-11-08 18:14:01 -08001011{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001012
Cole Faustb85d1a12022-11-08 18:14:01 -08001013{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001014
1015def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -04001016 # TODO(b/199363072): filegroups and file targets aren't associated with any
1017 # specific platform architecture in mixed builds. This is consistent with how
1018 # Soong treats filegroups, but it may not be the case with manually-written
1019 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -05001020 buildoptions = build_options(target)
Yu Liue4312402023-01-18 09:15:31 -08001021
Jingwen Chen8f222742021-10-07 12:02:23 +00001022 if buildoptions == None:
1023 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -04001024 # any specific platform architecture in mixed builds, so use the host.
1025 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -08001026 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -05001027 if len(platforms) != 1:
1028 # An individual configured target should have only one platform architecture.
1029 # Note that it's fine for there to be multiple architectures for the same label,
1030 # but each is its own configured target.
1031 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -08001032 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -05001033 if platform_name == "host":
1034 return "HOST"
Cole Faustb85d1a12022-11-08 18:14:01 -08001035 if not platform_name.startswith("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}"):
1036 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))
1037 platform_name = platform_name.removeprefix("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}").removeprefix("_")
Yu Liue4312402023-01-18 09:15:31 -08001038 config_key = ""
Cole Faustb85d1a12022-11-08 18:14:01 -08001039 if not platform_name:
Yu Liue4312402023-01-18 09:15:31 -08001040 config_key = "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -04001041 elif platform_name.startswith("android_"):
Yu Liue4312402023-01-18 09:15:31 -08001042 config_key = platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -04001043 elif platform_name.startswith("linux_"):
Yu Liue4312402023-01-18 09:15:31 -08001044 config_key = platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -04001045 else:
Cole Faustb85d1a12022-11-08 18:14:01 -08001046 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 -05001047
Yu Liue4312402023-01-18 09:15:31 -08001048 within_apex = buildoptions.get("//build/bazel/rules/apex:within_apex")
1049 apex_sdk_version = buildoptions.get("//build/bazel/rules/apex:min_sdk_version")
1050
1051 if within_apex:
1052 config_key += "|within_apex"
1053 if apex_sdk_version != None and len(apex_sdk_version) > 0:
1054 config_key += "|" + apex_sdk_version
1055
1056 return config_key
1057
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001058def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -05001059 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -05001060
Chris Parsons86dc2c22022-09-28 14:58:41 -04001061 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
1062 if id_string.startswith("//"):
1063 id_string = "@" + id_string
1064
Cole Faustb85d1a12022-11-08 18:14:01 -08001065 {MAIN_SWITCH_SECTION}
1066
Chris Parsons944e7d02021-03-11 11:08:46 -05001067 # This target was not requested via cquery, and thus must be a dependency
1068 # of a requested target.
1069 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001070`
Cole Faustb85d1a12022-11-08 18:14:01 -08001071 replacer := strings.NewReplacer(
1072 "{TARGET_PRODUCT}", context.targetProduct,
1073 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
1074 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
1075 "{FUNCTION_DEF_SECTION}", functionDefSection,
1076 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001077
Cole Faustb85d1a12022-11-08 18:14:01 -08001078 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001079}
1080
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001081// Returns a path containing build-related metadata required for interfacing
1082// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001083func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001084 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -05001085}
1086
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001087// Returns the path where the contents of the @soong_injection repository live.
1088// It is used by Soong to tell Bazel things it cannot over the command line.
1089func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001090 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001091}
1092
1093// Returns the path of the synthetic Bazel workspace that contains a symlink
1094// forest composed the whole source tree and BUILD files generated by bp2build.
1095func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001096 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001097}
1098
Jingwen Chen8c523582021-06-01 11:19:53 +00001099// Returns the path to the top level out dir ($OUT_DIR).
1100func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001101 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +00001102}
1103
Sasha Smundak4975c822022-11-16 15:28:18 -08001104const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
1105
1106var (
1107 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
1108 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
1109 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
1110)
1111
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001112// Issues commands to Bazel to receive results for all cquery requests
1113// queued in the BazelContext.
Liz Kammer690fbac2023-02-10 11:11:17 -05001114func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx invokeBazelContext) error {
1115 eventHandler := ctx.GetEventHandler()
1116 eventHandler.Begin("bazel")
1117 defer eventHandler.End("bazel")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001118
Sasha Smundak4975c822022-11-16 15:28:18 -08001119 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
1120 if err := os.MkdirAll(metricsDir, 0777); err != nil {
1121 return err
1122 }
1123 }
1124 context.results = make(map[cqueryKey]string)
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001125 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001126 return err
1127 }
1128 if err := context.runAquery(config, ctx); err != nil {
1129 return err
1130 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001131 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001132 return err
1133 }
1134
1135 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001136 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -08001137 return nil
1138}
1139
Liz Kammer690fbac2023-02-10 11:11:17 -05001140func (context *mixedBuildBazelContext) runCquery(config Config, ctx invokeBazelContext) error {
1141 eventHandler := ctx.GetEventHandler()
1142 eventHandler.Begin("cquery")
1143 defer eventHandler.End("cquery")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001144 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +02001145 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
1146 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
1147 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -05001148 if err != nil {
1149 return err
1150 }
1151 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001152 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001153 return err
1154 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001155 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001156 return err
1157 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001158 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001159 return err
1160 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001161 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001162 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001163 return err
1164 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001165
Yu Liue4312402023-01-18 09:15:31 -08001166 extraFlags := []string{"--output=starlark", "--starlark:file=" + absolutePath(cqueryFileRelpath)}
1167 if Bool(config.productVariables.ClangCoverage) {
1168 extraFlags = append(extraFlags, "--collect_code_coverage")
1169 }
1170
1171 cqueryCommandWithFlag := context.createBazelCommand(config, context.paths, bazel.CqueryBuildRootRunName, cqueryCmd, extraFlags...)
Liz Kammer690fbac2023-02-10 11:11:17 -05001172 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCommandWithFlag, eventHandler)
Wei Licbd181c2022-11-16 08:59:23 -08001173 if cqueryErr != nil {
1174 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001175 }
Jason Wu52cd1942022-09-08 15:37:57 +00001176 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", printableCqueryCommand(cqueryCommandWithFlag))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001177 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001178 return err
1179 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001180 cqueryResults := map[string]string{}
1181 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1182 if strings.Contains(outputLine, ">>") {
1183 splitLine := strings.SplitN(outputLine, ">>", 2)
1184 cqueryResults[splitLine[0]] = splitLine[1]
1185 }
1186 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001187 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001188 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001189 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001190 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001191 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001192 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001193 }
1194 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001195 return nil
1196}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001197
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001198func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1199 oldContents, err := os.ReadFile(path)
1200 if err != nil || !bytes.Equal(contents, oldContents) {
1201 err = os.WriteFile(path, contents, perm)
1202 }
1203 return nil
1204}
1205
Liz Kammer690fbac2023-02-10 11:11:17 -05001206func (context *mixedBuildBazelContext) runAquery(config Config, ctx invokeBazelContext) error {
1207 eventHandler := ctx.GetEventHandler()
1208 eventHandler.Begin("aquery")
1209 defer eventHandler.End("aquery")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001210 // Issue an aquery command to retrieve action information about the bazel build tree.
1211 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001212 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1213 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001214 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001215 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001216 extraFlags = append(extraFlags, "--collect_code_coverage")
1217 paths := make([]string, 0, 2)
1218 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001219 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001220 // TODO(b/259404593) convert path wildcard to regex values
1221 if p[i] == "*" {
1222 p[i] = ".*"
1223 }
1224 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001225 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1226 }
1227 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1228 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1229 }
1230 if len(paths) > 0 {
1231 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001232 }
1233 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001234 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
Liz Kammer690fbac2023-02-10 11:11:17 -05001235 extraFlags...), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001236 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001237 return err
1238 }
Liz Kammer690fbac2023-02-10 11:11:17 -05001239 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001240 return err
1241}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001242
Liz Kammer690fbac2023-02-10 11:11:17 -05001243func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx invokeBazelContext) error {
1244 eventHandler := ctx.GetEventHandler()
1245 eventHandler.Begin("symlinks")
1246 defer eventHandler.End("symlinks")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001247 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1248 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1249 // but some of symlinks may be required to resolve source dependencies of the build.
Liz Kammer690fbac2023-02-10 11:11:17 -05001250 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001251 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001252}
Chris Parsonsa798d962020-10-12 23:44:08 -04001253
Liz Kammera4655a92023-02-10 17:17:28 -05001254func (context *mixedBuildBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001255 return context.buildStatements
1256}
1257
Sasha Smundak39a301c2022-12-29 17:11:49 -08001258func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001259 return context.depsets
1260}
1261
Sasha Smundak39a301c2022-12-29 17:11:49 -08001262func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001263 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001264}
1265
Chris Parsonsa798d962020-10-12 23:44:08 -04001266// Singleton used for registering BUILD file ninja dependencies (needed
1267// for correctness of builds which use Bazel.
1268func BazelSingleton() Singleton {
1269 return &bazelSingleton{}
1270}
1271
1272type bazelSingleton struct{}
1273
1274func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001275 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001276 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001277 return
1278 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001279
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001280 // Add ninja file dependencies for files which all bazel invocations require.
1281 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001282 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001283 ctx.AddNinjaFileDeps(bazelBuildList)
1284
Sasha Smundak0e87b182022-12-01 11:46:11 -08001285 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001286 if err != nil {
1287 ctx.Errorf(err.Error())
1288 }
1289 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1290 for _, file := range files {
1291 ctx.AddNinjaFileDeps(file)
1292 }
1293
Chris Parsons1a7aca02022-04-25 22:35:15 -04001294 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1295 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001296 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001297 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1298 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001299 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1300 }
1301 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001302 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1303 if artifactPath == "bazel-out/volatile-status.txt" {
1304 // See https://bazel.build/docs/user-manual#workspace-status
1305 orderOnlies = append(orderOnlies, pathInBazelOut)
1306 } else {
1307 outputs = append(outputs, pathInBazelOut)
1308 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001309 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001310 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001311 ctx.Build(pctx, BuildParams{
1312 Rule: blueprint.Phony,
1313 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1314 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001315 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001316 })
1317 }
1318
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001319 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1320 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001321 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Liz Kammera4655a92023-02-10 17:17:28 -05001322 // nil build statements are a valid case where we do not create an action because it is
1323 // unnecessary or handled by other processing
1324 if buildStatement == nil {
1325 continue
1326 }
Sasha Smundak1da064c2022-06-08 16:36:16 -07001327 if len(buildStatement.Command) > 0 {
1328 rule := NewRuleBuilder(pctx, ctx)
1329 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1330 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1331 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1332 continue
1333 }
1334 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1335 // and thus require special treatment. If BuildStatement were an interface implementing
1336 // buildRule(ctx) function, the code here would just call it.
1337 // Unfortunately, the BuildStatement is defined in
1338 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1339 // because this would cause circular dependency. So, until we move aquery processing
1340 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001341 switch buildStatement.Mnemonic {
1342 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001343 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1344 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001345 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001346 // build-runfiles arguments are the manifest file and the target directory
1347 // where it creates the symlink tree according to this manifest (and then
1348 // writes the MANIFEST file to it).
1349 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1350 outManifestPath := outManifest.String()
1351 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1352 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1353 }
1354 outDir := filepath.Dir(outManifestPath)
1355 ctx.Build(pctx, BuildParams{
1356 Rule: buildRunfilesRule,
1357 Output: outManifest,
1358 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1359 Description: "symlink tree for " + outDir,
1360 Args: map[string]string{
1361 "outDir": outDir,
1362 },
1363 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001364 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001365 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001366 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001367 }
1368}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001369
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001370// Register bazel-owned build statements (obtained from the aquery invocation).
Liz Kammera4655a92023-02-10 17:17:28 -05001371func createCommand(cmd *RuleBuilderCommand, buildStatement *bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001372 // executionRoot is the action cwd.
1373 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1374
1375 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1376 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001377 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001378 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001379 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001380 }
1381 cmd.Text("&&")
1382 }
1383
1384 for _, pair := range buildStatement.Env {
1385 // Set per-action env variables, if any.
1386 cmd.Flag(pair.Key + "=" + pair.Value)
1387 }
1388
1389 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001390 if len(buildStatement.Command) > 16*1024 {
1391 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1392 WriteFileRule(ctx, commandFile, buildStatement.Command)
1393
1394 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1395 } else {
1396 cmd.Text(buildStatement.Command)
1397 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001398
1399 for _, outputPath := range buildStatement.OutputPaths {
1400 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1401 }
1402 for _, inputPath := range buildStatement.InputPaths {
1403 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1404 }
1405 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1406 otherDepsetName := bazelDepsetName(inputDepsetHash)
1407 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1408 }
1409
1410 if depfile := buildStatement.Depfile; depfile != nil {
1411 // The paths in depfile are relative to `executionRoot`.
1412 // Hence, they need to be corrected by replacing "bazel-out"
1413 // with the full `bazelOutDir`.
1414 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1415 // would be deemed missing.
1416 // (Note: The regexp uses a capture group because the version of sed
1417 // does not support a look-behind pattern.)
1418 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1419 bazelOutDir, *depfile)
1420 cmd.Text(replacement)
1421 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1422 }
1423
1424 for _, symlinkPath := range buildStatement.SymlinkPaths {
1425 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1426 }
1427}
1428
Chris Parsons8d6e4332021-02-22 16:13:50 -05001429func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001430 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001431}
1432
Chris Parsons787fb362021-10-14 18:43:51 -04001433func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001434 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001435 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001436 if key.configKey.osType.Class == Device {
1437 // For the generic Android, the expected result is "target|android", which
1438 // corresponds to the product_variable_config named "android_target" in
1439 // build/bazel/platforms/BUILD.bazel.
1440 arch = "target"
1441 } else {
1442 // Use host platform, which is currently hardcoded to be x86_64.
1443 arch = "x86_64"
1444 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001445 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001446 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001447 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001448 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001449 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001450 }
Yu Liue4312402023-01-18 09:15:31 -08001451 keyString := arch + "|" + osName
1452 if key.configKey.apexKey.WithinApex {
1453 keyString += "|" + withinApexToString(key.configKey.apexKey.WithinApex)
1454 }
1455
1456 if len(key.configKey.apexKey.ApexSdkVersion) > 0 {
1457 keyString += "|" + key.configKey.apexKey.ApexSdkVersion
1458 }
1459
1460 return keyString
Chris Parsons787fb362021-10-14 18:43:51 -04001461}
1462
Chris Parsonsf874e462022-05-10 13:50:12 -04001463func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001464 return configKey{
1465 // use string because Arch is not a valid key in go
1466 arch: ctx.Arch().String(),
1467 osType: ctx.Os(),
1468 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001469}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001470
Yu Liue4312402023-01-18 09:15:31 -08001471func GetConfigKeyApexVariant(ctx BaseModuleContext, apexKey *ApexConfigKey) configKey {
1472 configKey := GetConfigKey(ctx)
1473
1474 if apexKey != nil {
1475 configKey.apexKey = ApexConfigKey{
1476 WithinApex: apexKey.WithinApex,
1477 ApexSdkVersion: apexKey.ApexSdkVersion,
1478 }
1479 }
1480
1481 return configKey
1482}
1483
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001484func bazelDepsetName(contentHash string) string {
1485 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001486}
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001487
1488func EnvironmentVarsFile(config Config) string {
1489 return fmt.Sprintf(bazel.GeneratedBazelFileWarning+`
1490_env = %s
1491
1492env = _env
1493`,
1494 starlark_fmt.PrintStringList(allowedBazelEnvironmentVars, 0),
1495 )
1496}