blob: e7b84e3048da2681cefed57df079daadad2a178a [file] [log] [blame]
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001// Copyright 2020 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package android
16
17import (
18 "bytes"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040019 "fmt"
20 "os"
21 "os/exec"
Usta Shresthaacd5a0c2022-06-22 11:20:50 -040022 "path"
Chris Parsonsa798d962020-10-12 23:44:08 -040023 "path/filepath"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040024 "runtime"
Cole Faust705968d2022-12-14 11:32:05 -080025 "sort"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040026 "strings"
27 "sync"
Chris Parsonsa798d962020-10-12 23:44:08 -040028
Chris Parsonsad876012022-08-20 14:48:32 -040029 "android/soong/android/allowlists"
Chris Parsons944e7d02021-03-11 11:08:46 -050030 "android/soong/bazel/cquery"
Jingwen Chen1e347862021-09-02 12:11:49 +000031 "android/soong/shared"
Sam Delmericocb3c52c2023-02-03 17:40:08 -050032 "android/soong/starlark_fmt"
Liz Kammer337e9032022-08-03 15:49:43 -040033
Chris Parsons1a7aca02022-04-25 22:35:15 -040034 "github.com/google/blueprint"
Liz Kammer690fbac2023-02-10 11:11:17 -050035 "github.com/google/blueprint/metrics"
Liz Kammer8206d4f2021-03-03 16:40:52 -050036
Patrice Arruda05ab2d02020-12-12 06:24:26 +000037 "android/soong/bazel"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040038)
39
Sasha Smundak1da064c2022-06-08 16:36:16 -070040var (
Sasha Smundakc180dbd2022-07-03 14:55:58 -070041 _ = pctx.HostBinToolVariable("bazelBuildRunfilesTool", "build-runfiles")
42 buildRunfilesRule = pctx.AndroidStaticRule("bazelBuildRunfiles", blueprint.RuleParams{
43 Command: "${bazelBuildRunfilesTool} ${in} ${outDir}",
44 Depfile: "",
45 Description: "",
46 CommandDeps: []string{"${bazelBuildRunfilesTool}"},
47 }, "outDir")
Sam Delmericocb3c52c2023-02-03 17:40:08 -050048 allowedBazelEnvironmentVars = []string{
Sam Delmerico700b4d32023-02-10 16:46:28 -050049 // clang-tidy
Sam Delmericocb3c52c2023-02-03 17:40:08 -050050 "ALLOW_LOCAL_TIDY_TRUE",
51 "DEFAULT_TIDY_HEADER_DIRS",
52 "TIDY_TIMEOUT",
53 "WITH_TIDY",
54 "WITH_TIDY_FLAGS",
Sam Delmerico700b4d32023-02-10 16:46:28 -050055 "TIDY_EXTERNAL_VENDOR",
56
Sam Delmericocb3c52c2023-02-03 17:40:08 -050057 "SKIP_ABI_CHECKS",
58 "UNSAFE_DISABLE_APEX_ALLOWED_DEPS_CHECK",
59 "AUTO_ZERO_INITIALIZE",
60 "AUTO_PATTERN_INITIALIZE",
61 "AUTO_UNINITIALIZE",
62 "USE_CCACHE",
63 "LLVM_NEXT",
64 "ALLOW_UNKNOWN_WARNING_OPTION",
65
66 // Overrides the version in the apex_manifest.json. The version is unique for
67 // each branch (internal, aosp, mainline releases, dessert releases). This
68 // enables modules built on an older branch to be installed against a newer
69 // device for development purposes.
70 "OVERRIDE_APEX_MANIFEST_DEFAULT_VERSION",
71 }
Sasha Smundak1da064c2022-06-08 16:36:16 -070072)
73
Chris Parsonsf874e462022-05-10 13:50:12 -040074func init() {
75 RegisterMixedBuildsMutator(InitRegistrationContext)
76}
77
78func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammer337e9032022-08-03 15:49:43 -040079 ctx.FinalDepsMutators(func(ctx RegisterMutatorsContext) {
Chris Parsonsf874e462022-05-10 13:50:12 -040080 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
81 })
82}
83
84func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
85 if m := ctx.Module(); m.Enabled() {
86 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
87 if mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx) {
88 mixedBuildMod.QueueBazelCall(ctx)
89 }
90 }
91 }
92}
93
Liz Kammerf29df7c2021-04-02 13:37:39 -040094type cqueryRequest interface {
95 // Name returns a string name for this request type. Such request type names must be unique,
96 // and must only consist of alphanumeric characters.
97 Name() string
98
99 // StarlarkFunctionBody returns a starlark function body to process this request type.
100 // The returned string is the body of a Starlark function which obtains
101 // all request-relevant information about a target and returns a string containing
102 // this information.
103 // The function should have the following properties:
Cole Faust97d15272022-11-22 14:08:59 -0800104 // - The arguments are `target` (a configured target) and `id_string` (the label + configuration).
Liz Kammerf29df7c2021-04-02 13:37:39 -0400105 // - The return value must be a string.
106 // - The function body should not be indented outside of its own scope.
107 StarlarkFunctionBody() string
108}
109
Chris Parsons787fb362021-10-14 18:43:51 -0400110// Portion of cquery map key to describe target configuration.
111type configKey struct {
Yu Liue4312402023-01-18 09:15:31 -0800112 arch string
113 osType OsType
114 apexKey ApexConfigKey
115}
116
117type ApexConfigKey struct {
118 WithinApex bool
119 ApexSdkVersion string
120}
121
122func (c ApexConfigKey) String() string {
123 return fmt.Sprintf("%s_%s", withinApexToString(c.WithinApex), c.ApexSdkVersion)
124}
125
126func withinApexToString(withinApex bool) string {
127 if withinApex {
128 return "within_apex"
129 }
130 return ""
Chris Parsons787fb362021-10-14 18:43:51 -0400131}
132
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700133func (c configKey) String() string {
Yu Liue4312402023-01-18 09:15:31 -0800134 return fmt.Sprintf("%s::%s::%s", c.arch, c.osType, c.apexKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700135}
136
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400137// Map key to describe bazel cquery requests.
138type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400139 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400140 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400141 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400142}
143
Chris Parsons86dc2c22022-09-28 14:58:41 -0400144func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
145 if strings.HasPrefix(label, "//") {
146 // Normalize Bazel labels to specify main repository explicitly.
147 label = "@" + label
148 }
149 return cqueryKey{label, cqueryRequest, cfgKey}
150}
151
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700152func (c cqueryKey) String() string {
153 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700154}
155
Liz Kammer690fbac2023-02-10 11:11:17 -0500156type invokeBazelContext interface {
157 GetEventHandler() *metrics.EventHandler
158}
159
Chris Parsonsf874e462022-05-10 13:50:12 -0400160// BazelContext is a context object useful for interacting with Bazel during
161// the course of a build. Use of Bazel to evaluate part of the build graph
162// is referred to as a "mixed build". (Some modules are managed by Soong,
163// some are managed by Bazel). To facilitate interop between these build
164// subgraphs, Soong may make requests to Bazel and evaluate their responses
165// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400166type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400167 // Add a cquery request to the bazel request queue. All queued requests
168 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
169 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
170
171 // ** Cquery Results Retrieval Functions
172 // The below functions pertain to retrieving cquery results from a prior
173 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400174
175 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400176 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500177
Chris Parsons944e7d02021-03-11 11:08:46 -0500178 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400179 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400180
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000181 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400182 // TODO(b/232976601): Remove.
183 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000184
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700185 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400186 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700187
Sasha Smundakedd16662022-10-07 14:44:50 -0700188 // Returns the results of the GetCcUnstrippedInfo query
189 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
190
Chris Parsonsf874e462022-05-10 13:50:12 -0400191 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400192
193 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800194 // queued in the BazelContext. The ctx argument is optional and is only
195 // used for performance data collection
Liz Kammer690fbac2023-02-10 11:11:17 -0500196 InvokeBazel(config Config, ctx invokeBazelContext) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400197
Chris Parsonsad876012022-08-20 14:48:32 -0400198 // Returns true if Bazel handling is enabled for the module with the given name.
199 // Note that this only implies "bazel mixed build" allowlisting. The caller
200 // should independently verify the module is eligible for Bazel handling
201 // (for example, that it is MixedBuildBuildable).
Yu Liue4312402023-01-18 09:15:31 -0800202 IsModuleNameAllowed(moduleName string, withinApex bool) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500203
Yu Liubfb23622023-02-22 10:42:15 -0800204 IsModuleDclaAllowed(moduleName string) bool
205
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500206 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
207 OutputBase() string
208
209 // Returns build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500210 BuildStatementsToRegister() []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400211
212 // Returns the depsets defined in Bazel's aquery response.
213 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400214}
215
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400216type bazelRunner interface {
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500217 createBazelCommand(config Config, paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) *exec.Cmd
Liz Kammer690fbac2023-02-10 11:11:17 -0500218 issueBazelCommand(bazelCmd *exec.Cmd, eventHandler *metrics.EventHandler) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400219}
220
221type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000222 homeDir string
223 bazelPath string
224 outputBase string
225 workspaceDir string
226 soongOutDir string
227 metricsDir string
228 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400229}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400230
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400231// A context object which tracks queued requests that need to be made to Bazel,
232// and their results after the requests have been made.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800233type mixedBuildBazelContext struct {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400234 bazelRunner
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500235 paths *bazelPaths
236 // cquery requests that have not yet been issued to Bazel. This list is maintained
237 // in a sorted state, and is guaranteed to have no duplicates.
238 requests []cqueryKey
239 requestMutex sync.Mutex // requests can be written in parallel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400240
241 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500242
243 // Build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500244 buildStatements []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400245
246 // Depsets which should be used for Bazel's build statements.
247 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400248
249 // Per-module allowlist/denylist functionality to control whether analysis of
250 // modules are handled by Bazel. For modules which do not have a Bazel definition
251 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
252 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
253 // Per-module denylist to opt modules out of bazel handling.
254 bazelDisabledModules map[string]bool
255 // Per-module allowlist to opt modules in to bazel handling.
256 bazelEnabledModules map[string]bool
Yu Liue4312402023-01-18 09:15:31 -0800257 // DCLA modules are enabled when used in apex.
258 bazelDclaEnabledModules map[string]bool
Chris Parsonsad876012022-08-20 14:48:32 -0400259 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
260 modulesDefaultToBazel bool
Cole Faustb85d1a12022-11-08 18:14:01 -0800261
262 targetProduct string
263 targetBuildVariant string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400264}
265
Sasha Smundak39a301c2022-12-29 17:11:49 -0800266var _ BazelContext = &mixedBuildBazelContext{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400267
268// A bazel context to use when Bazel is disabled.
269type noopBazelContext struct{}
270
271var _ BazelContext = noopBazelContext{}
272
273// A bazel context to use for tests.
274type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400275 OutputBaseDir string
276
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000277 LabelToOutputFiles map[string][]string
278 LabelToCcInfo map[string]cquery.CcInfo
279 LabelToPythonBinary map[string]string
Liz Kammerbe6a7122022-11-04 16:05:11 -0400280 LabelToApexInfo map[string]cquery.ApexInfo
Sasha Smundakedd16662022-10-07 14:44:50 -0700281 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
Yu Liue4312402023-01-18 09:15:31 -0800282
283 BazelRequests map[string]bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400284}
285
Yu Liue4312402023-01-18 09:15:31 -0800286func (m MockBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
287 key := BuildMockBazelContextRequestKey(label, requestType, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
288 if m.BazelRequests == nil {
289 m.BazelRequests = make(map[string]bool)
290 }
291 m.BazelRequests[key] = true
Chris Parsons8d6e4332021-02-22 16:13:50 -0500292}
293
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700294func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500295 result, ok := m.LabelToOutputFiles[label]
296 if !ok {
297 return []string{}, fmt.Errorf("no target with label %q in LabelToOutputFiles", label)
298 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400299 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400300}
301
Yu Liue4312402023-01-18 09:15:31 -0800302func (m MockBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500303 result, ok := m.LabelToCcInfo[label]
304 if !ok {
Yu Liue4312402023-01-18 09:15:31 -0800305 key := BuildMockBazelContextResultKey(label, cfgKey.arch, cfgKey.osType, cfgKey.apexKey)
306 result, ok = m.LabelToCcInfo[key]
307 if !ok {
308 return cquery.CcInfo{}, fmt.Errorf("no target with label %q in LabelToCcInfo", label)
309 }
Sam Delmericoce39f832023-01-23 14:04:24 -0500310 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400311 return result, nil
312}
313
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700314func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500315 result, ok := m.LabelToPythonBinary[label]
316 if !ok {
317 return "", fmt.Errorf("no target with label %q in LabelToPythonBinary", label)
318 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400319 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000320}
321
Liz Kammerbe6a7122022-11-04 16:05:11 -0400322func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500323 result, ok := m.LabelToApexInfo[label]
324 if !ok {
325 return cquery.ApexInfo{}, fmt.Errorf("no target with label %q in LabelToApexInfo", label)
326 }
Liz Kammer0e255ef2022-11-04 16:07:04 -0400327 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700328}
329
Sasha Smundakedd16662022-10-07 14:44:50 -0700330func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500331 result, ok := m.LabelToCcBinary[label]
332 if !ok {
333 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no target with label %q in LabelToCcBinary", label)
334 }
Sasha Smundakedd16662022-10-07 14:44:50 -0700335 return result, nil
336}
337
Liz Kammer690fbac2023-02-10 11:11:17 -0500338func (m MockBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400339 panic("unimplemented")
340}
341
Yu Liue4312402023-01-18 09:15:31 -0800342func (m MockBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400343 return true
344}
345
Yu Liubfb23622023-02-22 10:42:15 -0800346func (m MockBazelContext) IsModuleDclaAllowed(_ string) bool {
347 return true
348}
349
Liz Kammera92e8442021-04-07 20:25:21 -0400350func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500351
Liz Kammera4655a92023-02-10 17:17:28 -0500352func (m MockBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
353 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500354}
355
Chris Parsons1a7aca02022-04-25 22:35:15 -0400356func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
357 return []bazel.AqueryDepset{}
358}
359
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400360var _ BazelContext = MockBazelContext{}
361
Yu Liue4312402023-01-18 09:15:31 -0800362func BuildMockBazelContextRequestKey(label string, request cqueryRequest, arch string, osType OsType, apexKey ApexConfigKey) string {
363 cfgKey := configKey{
364 arch: arch,
365 osType: osType,
366 apexKey: apexKey,
367 }
368
369 return strings.Join([]string{label, request.Name(), cfgKey.String()}, "_")
370}
371
372func BuildMockBazelContextResultKey(label string, arch string, osType OsType, apexKey ApexConfigKey) string {
373 cfgKey := configKey{
374 arch: arch,
375 osType: osType,
376 apexKey: apexKey,
377 }
378
379 return strings.Join([]string{label, cfgKey.String()}, "_")
380}
381
Sasha Smundak39a301c2022-12-29 17:11:49 -0800382func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400383 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400384 bazelCtx.requestMutex.Lock()
385 defer bazelCtx.requestMutex.Unlock()
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500386
387 // Insert key into requests, maintaining the sort, and only if it's not duplicate.
388 keyString := key.String()
389 foundEqual := false
390 notLessThanKeyString := func(i int) bool {
391 s := bazelCtx.requests[i].String()
392 v := strings.Compare(s, keyString)
393 if v == 0 {
394 foundEqual = true
395 }
396 return v >= 0
397 }
398 targetIndex := sort.Search(len(bazelCtx.requests), notLessThanKeyString)
399 if foundEqual {
400 return
401 }
402
403 if targetIndex == len(bazelCtx.requests) {
404 bazelCtx.requests = append(bazelCtx.requests, key)
405 } else {
406 bazelCtx.requests = append(bazelCtx.requests[:targetIndex+1], bazelCtx.requests[targetIndex:]...)
407 bazelCtx.requests[targetIndex] = key
408 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400409}
410
Sasha Smundak39a301c2022-12-29 17:11:49 -0800411func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400412 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400413 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500414 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400415
Chris Parsonsf874e462022-05-10 13:50:12 -0400416 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400417 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400418 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400419}
420
Sasha Smundak39a301c2022-12-29 17:11:49 -0800421func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400422 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400423 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000424 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400425 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000426 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400427 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 +0000428}
429
Sasha Smundak39a301c2022-12-29 17:11:49 -0800430func (bazelCtx *mixedBuildBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400431 key := makeCqueryKey(label, cquery.GetPythonBinary, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400432 if rawString, ok := bazelCtx.results[key]; ok {
433 bazelOutput := strings.TrimSpace(rawString)
434 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
435 }
436 return "", fmt.Errorf("no bazel response found for %v", key)
437}
438
Sasha Smundak39a301c2022-12-29 17:11:49 -0800439func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400440 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700441 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500442 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700443 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400444 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700445}
446
Sasha Smundak39a301c2022-12-29 17:11:49 -0800447func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700448 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
449 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500450 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700451 }
452 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
453}
454
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700455func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500456 panic("unimplemented")
457}
458
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700459func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500460 panic("unimplemented")
461}
462
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700463func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400464 panic("unimplemented")
465}
466
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700467func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000468 panic("unimplemented")
469}
470
Liz Kammerbe6a7122022-11-04 16:05:11 -0400471func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700472 panic("unimplemented")
473}
474
Sasha Smundakedd16662022-10-07 14:44:50 -0700475func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
476 //TODO implement me
477 panic("implement me")
478}
479
Liz Kammer690fbac2023-02-10 11:11:17 -0500480func (n noopBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400481 panic("unimplemented")
482}
483
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500484func (m noopBazelContext) OutputBase() string {
485 return ""
486}
487
Yu Liue4312402023-01-18 09:15:31 -0800488func (n noopBazelContext) IsModuleNameAllowed(_ string, _ bool) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400489 return false
490}
491
Yu Liubfb23622023-02-22 10:42:15 -0800492func (n noopBazelContext) IsModuleDclaAllowed(_ string) bool {
493 return false
494}
495
Liz Kammera4655a92023-02-10 17:17:28 -0500496func (m noopBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
497 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500498}
499
Chris Parsons1a7aca02022-04-25 22:35:15 -0400500func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
501 return []bazel.AqueryDepset{}
502}
503
Yu Liue4312402023-01-18 09:15:31 -0800504func addToStringSet(set map[string]bool, items []string) {
505 for _, item := range items {
506 set[item] = true
507 }
508}
509
Cole Faust705968d2022-12-14 11:32:05 -0800510func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400511 disabledModules := map[string]bool{}
512 enabledModules := map[string]bool{}
513
Cole Faust705968d2022-12-14 11:32:05 -0800514 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400515 case BazelProdMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800516 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800517 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000518 enabledModules[enabledAdHocModule] = true
519 }
MarkDacekb78465d2022-10-18 20:10:16 +0000520 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400521 // Staging mode includes all prod modules plus all staging modules.
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800522 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
523 addToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800524 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000525 enabledModules[enabledAdHocModule] = true
526 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400527 case BazelDevMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800528 addToStringSet(disabledModules, allowlists.MixedBuildsDisabledList)
Chris Parsonsef615e52022-08-18 22:04:11 -0400529 default:
Cole Faust705968d2022-12-14 11:32:05 -0800530 panic("Expected BazelProdMode, BazelStagingMode, or BazelDevMode")
531 }
532 return enabledModules, disabledModules
533}
534
535func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
536 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
537 enabledList := make([]string, 0, len(enabledModules))
538 for module := range enabledModules {
539 if !disabledModules[module] {
540 enabledList = append(enabledList, module)
541 }
542 }
543 sort.Strings(enabledList)
544 return enabledList
545}
546
547func NewBazelContext(c *config) (BazelContext, error) {
548 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode && c.BuildMode != BazelDevMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400549 return noopBazelContext{}, nil
550 }
551
Cole Faust705968d2022-12-14 11:32:05 -0800552 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
553
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800554 paths := bazelPaths{
555 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400556 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800557 var missing []string
558 vars := []struct {
559 name string
560 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000561
562 // True if the environment variable needs to be tracked so that changes to the variable
563 // cause the ninja file to be regenerated, false otherwise. False should only be set for
564 // environment variables that have no effect on the generated ninja file.
565 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800566 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000567 {"BAZEL_HOME", &paths.homeDir, true},
568 {"BAZEL_PATH", &paths.bazelPath, true},
569 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
570 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
571 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
572 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800573 }
574 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000575 if v.track {
576 if s := c.Getenv(v.name); len(s) > 1 {
577 *v.ptr = s
578 continue
579 }
580 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800581 *v.ptr = s
582 } else {
583 missing = append(missing, v.name)
584 }
585 }
586 if len(missing) > 0 {
587 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
588 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800589
590 targetBuildVariant := "user"
591 if c.Eng() {
592 targetBuildVariant = "eng"
593 } else if c.Debuggable() {
594 targetBuildVariant = "userdebug"
595 }
596 targetProduct := "unknown"
597 if c.HasDeviceProduct() {
598 targetProduct = c.DeviceProduct()
599 }
Yu Liue4312402023-01-18 09:15:31 -0800600 dclaMixedBuildsEnabledList := []string{}
601 if c.BuildMode == BazelProdMode {
602 dclaMixedBuildsEnabledList = allowlists.ProdDclaMixedBuildsEnabledList
603 } else if c.BuildMode == BazelStagingMode {
604 dclaMixedBuildsEnabledList = append(allowlists.ProdDclaMixedBuildsEnabledList,
605 allowlists.StagingDclaMixedBuildsEnabledList...)
606 }
607 dclaEnabledModules := map[string]bool{}
608 addToStringSet(dclaEnabledModules, dclaMixedBuildsEnabledList)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800609 return &mixedBuildBazelContext{
Chris Parsons9402ca82023-02-23 17:28:06 -0500610 bazelRunner: &builtinBazelRunner{c.UseBazelProxy, absolutePath(c.outDir)},
Yu Liue4312402023-01-18 09:15:31 -0800611 paths: &paths,
612 modulesDefaultToBazel: c.BuildMode == BazelDevMode,
613 bazelEnabledModules: enabledModules,
614 bazelDisabledModules: disabledModules,
615 bazelDclaEnabledModules: dclaEnabledModules,
616 targetProduct: targetProduct,
617 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400618 }, nil
619}
620
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400621func (p *bazelPaths) BazelMetricsDir() string {
622 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000623}
624
Yu Liue4312402023-01-18 09:15:31 -0800625func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string, withinApex bool) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400626 if context.bazelDisabledModules[moduleName] {
627 return false
628 }
629 if context.bazelEnabledModules[moduleName] {
630 return true
631 }
Yu Liubfb23622023-02-22 10:42:15 -0800632 if withinApex && context.IsModuleDclaAllowed(moduleName) {
Yu Liue4312402023-01-18 09:15:31 -0800633 return true
634 }
635
Chris Parsonsad876012022-08-20 14:48:32 -0400636 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400637}
638
Yu Liubfb23622023-02-22 10:42:15 -0800639func (context *mixedBuildBazelContext) IsModuleDclaAllowed(moduleName string) bool {
640 return context.bazelDclaEnabledModules[moduleName]
641}
642
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400643func pwdPrefix() string {
644 // Darwin doesn't have /proc
645 if runtime.GOOS != "darwin" {
646 return "PWD=/proc/self/cwd"
647 }
648 return ""
649}
650
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400651type bazelCommand struct {
652 command string
653 // query or label
654 expression string
655}
656
657type mockBazelRunner struct {
658 bazelCommandResults map[bazelCommand]string
Jason Wu52cd1942022-09-08 15:37:57 +0000659 // use *exec.Cmd as a key to get the bazelCommand, the map will be used in issueBazelCommand()
660 // Register createBazelCommand() invocations. Later, an
661 // issueBazelCommand() invocation can be mapped to the *exec.Cmd instance
662 // and then to the expected result via bazelCommandResults
663 tokens map[*exec.Cmd]bazelCommand
664 commands []bazelCommand
665 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400666}
667
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500668func (r *mockBazelRunner) createBazelCommand(_ Config, _ *bazelPaths, _ bazel.RunName,
Jason Wu52cd1942022-09-08 15:37:57 +0000669 command bazelCommand, extraFlags ...string) *exec.Cmd {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400670 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700671 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Jason Wu52cd1942022-09-08 15:37:57 +0000672 cmd := &exec.Cmd{}
673 if r.tokens == nil {
674 r.tokens = make(map[*exec.Cmd]bazelCommand)
675 }
676 r.tokens[cmd] = command
677 return cmd
678}
679
Liz Kammer690fbac2023-02-10 11:11:17 -0500680func (r *mockBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd, _ *metrics.EventHandler) (string, string, error) {
Jason Wu52cd1942022-09-08 15:37:57 +0000681 if command, ok := r.tokens[bazelCmd]; ok {
682 return r.bazelCommandResults[command], "", nil
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400683 }
684 return "", "", nil
685}
686
Chris Parsons9402ca82023-02-23 17:28:06 -0500687type builtinBazelRunner struct {
688 useBazelProxy bool
689 outDir string
690}
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400691
Chris Parsons808d84c2021-03-09 20:43:32 -0500692// Issues the given bazel command with given build label and additional flags.
693// Returns (stdout, stderr, error). The first and second return values are strings
694// containing the stdout and stderr of the run command, and an error is returned if
695// the invocation returned an error code.
Liz Kammer690fbac2023-02-10 11:11:17 -0500696func (r *builtinBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd, eventHandler *metrics.EventHandler) (string, string, error) {
Chris Parsons9402ca82023-02-23 17:28:06 -0500697 if r.useBazelProxy {
698 eventHandler.Begin("client_proxy")
699 defer eventHandler.End("client_proxy")
700 proxyClient := bazel.NewProxyClient(r.outDir)
701 // Omit the arg containing the Bazel binary, as that is handled by the proxy
702 // server.
703 bazelFlags := bazelCmd.Args[1:]
704 // TODO(b/270989498): Refactor these functions to not take exec.Cmd, as its
705 // not actually executed for client proxying.
706 resp, err := proxyClient.IssueCommand(bazel.CmdRequest{bazelFlags, bazelCmd.Env})
707
708 if err != nil {
709 return "", "", err
710 }
711 if len(resp.ErrorString) > 0 {
712 return "", "", fmt.Errorf(resp.ErrorString)
713 }
714 return resp.Stdout, resp.Stderr, nil
Jason Wu52cd1942022-09-08 15:37:57 +0000715 } else {
Chris Parsons9402ca82023-02-23 17:28:06 -0500716 eventHandler.Begin("bazel command")
717 defer eventHandler.End("bazel command")
718 stderr := &bytes.Buffer{}
719 bazelCmd.Stderr = stderr
720 if output, err := bazelCmd.Output(); err != nil {
721 return "", string(stderr.Bytes()),
722 fmt.Errorf("bazel command failed: %s\n---command---\n%s\n---env---\n%s\n---stderr---\n%s---",
723 err, bazelCmd, strings.Join(bazelCmd.Env, "\n"), stderr)
724 } else {
725 return string(output), string(stderr.Bytes()), nil
726 }
Jason Wu52cd1942022-09-08 15:37:57 +0000727 }
728}
729
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500730func (r *builtinBazelRunner) createBazelCommand(config Config, paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Jason Wu52cd1942022-09-08 15:37:57 +0000731 extraFlags ...string) *exec.Cmd {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000732 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000733 "--output_base=" + absolutePath(paths.outputBase),
734 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700735 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700736 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700737 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400738
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700739 // Set default platforms to canonicalized values for mixed builds requests.
740 // If these are set in the bazelrc, they will have values that are
741 // non-canonicalized to @sourceroot labels, and thus be invalid when
742 // referenced from the buildroot.
743 //
744 // The actual platform values here may be overridden by configuration
745 // transitions from the buildroot.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700746 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Cole Faustb85d1a12022-11-08 18:14:01 -0800747
748 // We don't need to set --host_platforms because it's set in bazelrc files
749 // that the bazel shell script wrapper passes
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700750
751 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
752 "--experimental_repository_disable_download",
753
754 // Suppress noise
755 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500756 "--noshow_progress",
757 "--norun_validations",
758 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400759 cmdFlags = append(cmdFlags, extraFlags...)
760
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400761 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200762 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700763 extraEnv := []string{
764 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200765 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700766 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700767 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000768 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700769 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500770 // Disables local host detection of gcc; toolchain information is defined
771 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700772 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
773 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500774 for _, envvar := range allowedBazelEnvironmentVars {
775 val := config.Getenv(envvar)
776 if val == "" {
777 continue
778 }
779 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
780 }
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700781 bazelCmd.Env = append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400782
Jason Wu52cd1942022-09-08 15:37:57 +0000783 return bazelCmd
784}
785
786func printableCqueryCommand(bazelCmd *exec.Cmd) string {
787 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(bazelCmd.Args, "\" \"") + "\""
788 return outputString
789
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400790}
791
Sasha Smundak39a301c2022-12-29 17:11:49 -0800792func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500793 // TODO(cparsons): Define configuration transitions programmatically based
794 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400795 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500796#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400797# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500798#####################################################
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400799def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800800 if attr.os == "android" and attr.arch == "target":
801 target = "{PRODUCT}-{VARIANT}"
802 else:
803 target = "{PRODUCT}-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Yu Liue4312402023-01-18 09:15:31 -0800804 apex_name = ""
805 if attr.within_apex:
806 # //build/bazel/rules/apex:apex_name has to be set to a non_empty value,
807 # otherwise //build/bazel/rules/apex:non_apex will be true and the
808 # "-D__ANDROID_APEX__" compiler flag will be missing. Apex_name is used
809 # in some validation on bazel side which don't really apply in mixed
810 # build because soong will do the work, so we just set it to a fixed
811 # value here.
812 apex_name = "dcla_apex"
813 outputs = {
Cole Faustb85d1a12022-11-08 18:14:01 -0800814 "//command_line_option:platforms": "@soong_injection//product_config_platforms/products/{PRODUCT}-{VARIANT}:%s" % target,
Yu Liue4312402023-01-18 09:15:31 -0800815 "@//build/bazel/rules/apex:within_apex": attr.within_apex,
816 "@//build/bazel/rules/apex:min_sdk_version": attr.apex_sdk_version,
817 "@//build/bazel/rules/apex:apex_name": apex_name,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500818 }
819
Yu Liue4312402023-01-18 09:15:31 -0800820 return outputs
821
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400822_config_node_transition = transition(
823 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500824 inputs = [],
825 outputs = [
826 "//command_line_option:platforms",
Yu Liue4312402023-01-18 09:15:31 -0800827 "@//build/bazel/rules/apex:within_apex",
828 "@//build/bazel/rules/apex:min_sdk_version",
829 "@//build/bazel/rules/apex:apex_name",
Chris Parsons8d6e4332021-02-22 16:13:50 -0500830 ],
831)
832
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400833def _passthrough_rule_impl(ctx):
834 return [DefaultInfo(files = depset(ctx.files.deps))]
835
836config_node = rule(
837 implementation = _passthrough_rule_impl,
838 attrs = {
Yu Liue4312402023-01-18 09:15:31 -0800839 "arch" : attr.string(mandatory = True),
840 "os" : attr.string(mandatory = True),
841 "within_apex" : attr.bool(default = False),
842 "apex_sdk_version" : attr.string(mandatory = True),
843 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400844 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
845 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500846)
847
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400848
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500849# Rule representing the root of the build, to depend on all Bazel targets that
850# are required for the build. Building this target will build the entire Bazel
851# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400852mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400853 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500854 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400855 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500856 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400857)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500858
859def _phony_root_impl(ctx):
860 return []
861
862# Rule to depend on other targets but build nothing.
863# This is useful as follows: building a target of this rule will generate
864# symlink forests for all dependencies of the target, without executing any
865# actions of the build.
866phony_root = rule(
867 implementation = _phony_root_impl,
868 attrs = {"deps" : attr.label_list()},
869)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400870`
Cole Faustb85d1a12022-11-08 18:14:01 -0800871
872 productReplacer := strings.NewReplacer(
873 "{PRODUCT}", context.targetProduct,
874 "{VARIANT}", context.targetBuildVariant)
875
876 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400877}
878
Sasha Smundak39a301c2022-12-29 17:11:49 -0800879func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500880 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
881 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400882 formatString := `
883# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400884load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
885
886%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400887
888mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400889 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000890 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400891)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500892
893phony_root(name = "phonyroot",
894 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000895 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500896)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400897`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400898 configNodeFormatString := `
899config_node(name = "%s",
900 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400901 os = "%s",
Yu Liue4312402023-01-18 09:15:31 -0800902 within_apex = %s,
903 apex_sdk_version = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400904 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000905 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400906)
907`
908
909 configNodesSection := ""
910
Chris Parsons787fb362021-10-14 18:43:51 -0400911 labelsByConfig := map[string][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500912
913 for _, val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200914 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400915 configString := getConfigString(val)
916 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400917 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400918
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500919 // Configs need to be sorted to maintain determinism of the BUILD file.
920 sortedConfigs := make([]string, 0, len(labelsByConfig))
921 for val := range labelsByConfig {
922 sortedConfigs = append(sortedConfigs, val)
923 }
924 sort.Slice(sortedConfigs, func(i, j int) bool { return sortedConfigs[i] < sortedConfigs[j] })
925
Jingwen Chen1e347862021-09-02 12:11:49 +0000926 allLabels := []string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500927 for _, configString := range sortedConfigs {
928 labels := labelsByConfig[configString]
Chris Parsons787fb362021-10-14 18:43:51 -0400929 configTokens := strings.Split(configString, "|")
Yu Liue4312402023-01-18 09:15:31 -0800930 if len(configTokens) < 2 {
Chris Parsons787fb362021-10-14 18:43:51 -0400931 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000932 }
Chris Parsons787fb362021-10-14 18:43:51 -0400933 archString := configTokens[0]
934 osString := configTokens[1]
Yu Liue4312402023-01-18 09:15:31 -0800935 withinApex := "False"
936 apexSdkVerString := ""
Chris Parsons787fb362021-10-14 18:43:51 -0400937 targetString := fmt.Sprintf("%s_%s", osString, archString)
Yu Liue4312402023-01-18 09:15:31 -0800938 if len(configTokens) > 2 {
939 targetString += "_" + configTokens[2]
940 if configTokens[2] == withinApexToString(true) {
941 withinApex = "True"
942 }
943 }
944 if len(configTokens) > 3 {
945 targetString += "_" + configTokens[3]
946 apexSdkVerString = configTokens[3]
947 }
Chris Parsons787fb362021-10-14 18:43:51 -0400948 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
949 labelsString := strings.Join(labels, ",\n ")
Yu Liue4312402023-01-18 09:15:31 -0800950 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, withinApex, apexSdkVerString,
951 labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400952 }
953
Jingwen Chen1e347862021-09-02 12:11:49 +0000954 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400955}
956
Chris Parsons944e7d02021-03-11 11:08:46 -0500957func indent(original string) string {
958 result := ""
959 for _, line := range strings.Split(original, "\n") {
960 result += " " + line + "\n"
961 }
962 return result
963}
964
Chris Parsons808d84c2021-03-09 20:43:32 -0500965// Returns the file contents of the buildroot.cquery file that should be used for the cquery
966// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800967// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500968// and grouped by their request type. The data retrieved for each label depends on its
969// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800970func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400971 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500972 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500973 cqueryId := getCqueryId(val)
974 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
975 requestTypeToCqueryIdEntries[val.requestType] =
976 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
977 }
978 labelRegistrationMapSection := ""
979 functionDefSection := ""
980 mainSwitchSection := ""
981
982 mapDeclarationFormatString := `
983%s = {
984 %s
985}
986`
987 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800988def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500989%s
990`
991 mainSwitchSectionFormatString := `
992 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800993 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500994`
995
Usta Shrestha0b52d832022-02-04 21:37:39 -0500996 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500997 labelMapName := requestType.Name() + "_Labels"
998 functionName := requestType.Name() + "_Fn"
999 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
1000 labelMapName,
1001 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
1002 functionDefSection += fmt.Sprintf(functionDefFormatString,
1003 functionName,
1004 indent(requestType.StarlarkFunctionBody()))
1005 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
1006 labelMapName, functionName)
1007 }
1008
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001009 formatString := `
1010# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001011
Usta Shrestha79fccef2022-09-02 18:37:40 -04001012# a drop-in replacement for json.encode(), not available in cquery environment
1013# TODO(cparsons): bring json module in and remove this function
1014def json_encode(input):
1015 # Avoiding recursion by limiting
1016 # - a dict to contain anything except a dict
1017 # - a list to contain only primitives
1018 def encode_primitive(p):
1019 t = type(p)
1020 if t == "string" or t == "int":
1021 return repr(p)
Cole Faustb85d1a12022-11-08 18:14:01 -08001022 fail("unsupported value '%s' of type '%s'" % (p, type(p)))
Usta Shrestha79fccef2022-09-02 18:37:40 -04001023
1024 def encode_list(list):
Cole Faustb85d1a12022-11-08 18:14:01 -08001025 return "[%s]" % ", ".join([encode_primitive(item) for item in list])
Usta Shrestha79fccef2022-09-02 18:37:40 -04001026
1027 def encode_list_or_primitive(v):
1028 return encode_list(v) if type(v) == "list" else encode_primitive(v)
1029
1030 if type(input) == "dict":
1031 # TODO(juu): the result is read line by line so can't use '\n' yet
Cole Faustb85d1a12022-11-08 18:14:01 -08001032 kv_pairs = [("%s: %s" % (encode_primitive(k), encode_list_or_primitive(v))) for (k, v) in input.items()]
1033 return "{ %s }" % ", ".join(kv_pairs)
Usta Shrestha79fccef2022-09-02 18:37:40 -04001034 else:
1035 return encode_list_or_primitive(input)
1036
Cole Faustb85d1a12022-11-08 18:14:01 -08001037{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001038
Cole Faustb85d1a12022-11-08 18:14:01 -08001039{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001040
1041def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -04001042 # TODO(b/199363072): filegroups and file targets aren't associated with any
1043 # specific platform architecture in mixed builds. This is consistent with how
1044 # Soong treats filegroups, but it may not be the case with manually-written
1045 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -05001046 buildoptions = build_options(target)
Yu Liue4312402023-01-18 09:15:31 -08001047
Jingwen Chen8f222742021-10-07 12:02:23 +00001048 if buildoptions == None:
1049 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -04001050 # any specific platform architecture in mixed builds, so use the host.
1051 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -08001052 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -05001053 if len(platforms) != 1:
1054 # An individual configured target should have only one platform architecture.
1055 # Note that it's fine for there to be multiple architectures for the same label,
1056 # but each is its own configured target.
1057 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -08001058 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -05001059 if platform_name == "host":
1060 return "HOST"
Cole Faustb85d1a12022-11-08 18:14:01 -08001061 if not platform_name.startswith("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}"):
1062 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))
1063 platform_name = platform_name.removeprefix("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}").removeprefix("_")
Yu Liue4312402023-01-18 09:15:31 -08001064 config_key = ""
Cole Faustb85d1a12022-11-08 18:14:01 -08001065 if not platform_name:
Yu Liue4312402023-01-18 09:15:31 -08001066 config_key = "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -04001067 elif platform_name.startswith("android_"):
Yu Liue4312402023-01-18 09:15:31 -08001068 config_key = platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -04001069 elif platform_name.startswith("linux_"):
Yu Liue4312402023-01-18 09:15:31 -08001070 config_key = platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -04001071 else:
Cole Faustb85d1a12022-11-08 18:14:01 -08001072 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 -05001073
Yu Liue4312402023-01-18 09:15:31 -08001074 within_apex = buildoptions.get("//build/bazel/rules/apex:within_apex")
1075 apex_sdk_version = buildoptions.get("//build/bazel/rules/apex:min_sdk_version")
1076
1077 if within_apex:
1078 config_key += "|within_apex"
1079 if apex_sdk_version != None and len(apex_sdk_version) > 0:
1080 config_key += "|" + apex_sdk_version
1081
1082 return config_key
1083
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001084def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -05001085 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -05001086
Chris Parsons86dc2c22022-09-28 14:58:41 -04001087 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
1088 if id_string.startswith("//"):
1089 id_string = "@" + id_string
1090
Cole Faustb85d1a12022-11-08 18:14:01 -08001091 {MAIN_SWITCH_SECTION}
1092
Chris Parsons944e7d02021-03-11 11:08:46 -05001093 # This target was not requested via cquery, and thus must be a dependency
1094 # of a requested target.
1095 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001096`
Cole Faustb85d1a12022-11-08 18:14:01 -08001097 replacer := strings.NewReplacer(
1098 "{TARGET_PRODUCT}", context.targetProduct,
1099 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
1100 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
1101 "{FUNCTION_DEF_SECTION}", functionDefSection,
1102 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001103
Cole Faustb85d1a12022-11-08 18:14:01 -08001104 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001105}
1106
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001107// Returns a path containing build-related metadata required for interfacing
1108// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001109func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001110 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -05001111}
1112
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001113// Returns the path where the contents of the @soong_injection repository live.
1114// It is used by Soong to tell Bazel things it cannot over the command line.
1115func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001116 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001117}
1118
1119// Returns the path of the synthetic Bazel workspace that contains a symlink
1120// forest composed the whole source tree and BUILD files generated by bp2build.
1121func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001122 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001123}
1124
Jingwen Chen8c523582021-06-01 11:19:53 +00001125// Returns the path to the top level out dir ($OUT_DIR).
1126func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001127 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +00001128}
1129
Sasha Smundak4975c822022-11-16 15:28:18 -08001130const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
1131
1132var (
1133 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
1134 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
1135 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
1136)
1137
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001138// Issues commands to Bazel to receive results for all cquery requests
1139// queued in the BazelContext.
Liz Kammer690fbac2023-02-10 11:11:17 -05001140func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx invokeBazelContext) error {
1141 eventHandler := ctx.GetEventHandler()
1142 eventHandler.Begin("bazel")
1143 defer eventHandler.End("bazel")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001144
Sasha Smundak4975c822022-11-16 15:28:18 -08001145 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
1146 if err := os.MkdirAll(metricsDir, 0777); err != nil {
1147 return err
1148 }
1149 }
1150 context.results = make(map[cqueryKey]string)
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001151 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001152 return err
1153 }
1154 if err := context.runAquery(config, ctx); err != nil {
1155 return err
1156 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001157 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001158 return err
1159 }
1160
1161 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001162 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -08001163 return nil
1164}
1165
Liz Kammer690fbac2023-02-10 11:11:17 -05001166func (context *mixedBuildBazelContext) runCquery(config Config, ctx invokeBazelContext) error {
1167 eventHandler := ctx.GetEventHandler()
1168 eventHandler.Begin("cquery")
1169 defer eventHandler.End("cquery")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001170 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +02001171 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
1172 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
1173 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -05001174 if err != nil {
1175 return err
1176 }
1177 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001178 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001179 return err
1180 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001181 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001182 return err
1183 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001184 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001185 return err
1186 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001187 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001188 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001189 return err
1190 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001191
Yu Liue4312402023-01-18 09:15:31 -08001192 extraFlags := []string{"--output=starlark", "--starlark:file=" + absolutePath(cqueryFileRelpath)}
1193 if Bool(config.productVariables.ClangCoverage) {
1194 extraFlags = append(extraFlags, "--collect_code_coverage")
1195 }
1196
1197 cqueryCommandWithFlag := context.createBazelCommand(config, context.paths, bazel.CqueryBuildRootRunName, cqueryCmd, extraFlags...)
Liz Kammer690fbac2023-02-10 11:11:17 -05001198 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCommandWithFlag, eventHandler)
Wei Licbd181c2022-11-16 08:59:23 -08001199 if cqueryErr != nil {
1200 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001201 }
Jason Wu52cd1942022-09-08 15:37:57 +00001202 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", printableCqueryCommand(cqueryCommandWithFlag))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001203 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001204 return err
1205 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001206 cqueryResults := map[string]string{}
1207 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1208 if strings.Contains(outputLine, ">>") {
1209 splitLine := strings.SplitN(outputLine, ">>", 2)
1210 cqueryResults[splitLine[0]] = splitLine[1]
1211 }
1212 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001213 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001214 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001215 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001216 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001217 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001218 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001219 }
1220 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001221 return nil
1222}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001223
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001224func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1225 oldContents, err := os.ReadFile(path)
1226 if err != nil || !bytes.Equal(contents, oldContents) {
1227 err = os.WriteFile(path, contents, perm)
1228 }
1229 return nil
1230}
1231
Liz Kammer690fbac2023-02-10 11:11:17 -05001232func (context *mixedBuildBazelContext) runAquery(config Config, ctx invokeBazelContext) error {
1233 eventHandler := ctx.GetEventHandler()
1234 eventHandler.Begin("aquery")
1235 defer eventHandler.End("aquery")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001236 // Issue an aquery command to retrieve action information about the bazel build tree.
1237 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001238 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1239 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001240 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001241 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001242 extraFlags = append(extraFlags, "--collect_code_coverage")
1243 paths := make([]string, 0, 2)
1244 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001245 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001246 // TODO(b/259404593) convert path wildcard to regex values
1247 if p[i] == "*" {
1248 p[i] = ".*"
1249 }
1250 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001251 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1252 }
1253 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1254 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1255 }
1256 if len(paths) > 0 {
1257 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001258 }
1259 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001260 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
Liz Kammer690fbac2023-02-10 11:11:17 -05001261 extraFlags...), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001262 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001263 return err
1264 }
Liz Kammer690fbac2023-02-10 11:11:17 -05001265 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001266 return err
1267}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001268
Liz Kammer690fbac2023-02-10 11:11:17 -05001269func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx invokeBazelContext) error {
1270 eventHandler := ctx.GetEventHandler()
1271 eventHandler.Begin("symlinks")
1272 defer eventHandler.End("symlinks")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001273 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1274 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1275 // but some of symlinks may be required to resolve source dependencies of the build.
Liz Kammer690fbac2023-02-10 11:11:17 -05001276 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001277 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001278}
Chris Parsonsa798d962020-10-12 23:44:08 -04001279
Liz Kammera4655a92023-02-10 17:17:28 -05001280func (context *mixedBuildBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001281 return context.buildStatements
1282}
1283
Sasha Smundak39a301c2022-12-29 17:11:49 -08001284func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001285 return context.depsets
1286}
1287
Sasha Smundak39a301c2022-12-29 17:11:49 -08001288func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001289 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001290}
1291
Chris Parsonsa798d962020-10-12 23:44:08 -04001292// Singleton used for registering BUILD file ninja dependencies (needed
1293// for correctness of builds which use Bazel.
1294func BazelSingleton() Singleton {
1295 return &bazelSingleton{}
1296}
1297
1298type bazelSingleton struct{}
1299
1300func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001301 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001302 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001303 return
1304 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001305
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001306 // Add ninja file dependencies for files which all bazel invocations require.
1307 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001308 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001309 ctx.AddNinjaFileDeps(bazelBuildList)
1310
Sasha Smundak0e87b182022-12-01 11:46:11 -08001311 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001312 if err != nil {
1313 ctx.Errorf(err.Error())
1314 }
1315 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1316 for _, file := range files {
1317 ctx.AddNinjaFileDeps(file)
1318 }
1319
Chris Parsons1a7aca02022-04-25 22:35:15 -04001320 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1321 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001322 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001323 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1324 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001325 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1326 }
1327 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001328 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1329 if artifactPath == "bazel-out/volatile-status.txt" {
1330 // See https://bazel.build/docs/user-manual#workspace-status
1331 orderOnlies = append(orderOnlies, pathInBazelOut)
1332 } else {
1333 outputs = append(outputs, pathInBazelOut)
1334 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001335 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001336 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001337 ctx.Build(pctx, BuildParams{
1338 Rule: blueprint.Phony,
1339 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1340 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001341 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001342 })
1343 }
1344
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001345 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1346 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001347 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Liz Kammera4655a92023-02-10 17:17:28 -05001348 // nil build statements are a valid case where we do not create an action because it is
1349 // unnecessary or handled by other processing
1350 if buildStatement == nil {
1351 continue
1352 }
Sasha Smundak1da064c2022-06-08 16:36:16 -07001353 if len(buildStatement.Command) > 0 {
1354 rule := NewRuleBuilder(pctx, ctx)
1355 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1356 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1357 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1358 continue
1359 }
1360 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1361 // and thus require special treatment. If BuildStatement were an interface implementing
1362 // buildRule(ctx) function, the code here would just call it.
1363 // Unfortunately, the BuildStatement is defined in
1364 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1365 // because this would cause circular dependency. So, until we move aquery processing
1366 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001367 switch buildStatement.Mnemonic {
1368 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001369 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1370 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001371 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001372 // build-runfiles arguments are the manifest file and the target directory
1373 // where it creates the symlink tree according to this manifest (and then
1374 // writes the MANIFEST file to it).
1375 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1376 outManifestPath := outManifest.String()
1377 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1378 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1379 }
1380 outDir := filepath.Dir(outManifestPath)
1381 ctx.Build(pctx, BuildParams{
1382 Rule: buildRunfilesRule,
1383 Output: outManifest,
1384 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1385 Description: "symlink tree for " + outDir,
1386 Args: map[string]string{
1387 "outDir": outDir,
1388 },
1389 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001390 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001391 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001392 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001393 }
1394}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001395
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001396// Register bazel-owned build statements (obtained from the aquery invocation).
Liz Kammera4655a92023-02-10 17:17:28 -05001397func createCommand(cmd *RuleBuilderCommand, buildStatement *bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001398 // executionRoot is the action cwd.
1399 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1400
1401 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1402 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001403 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001404 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001405 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001406 }
1407 cmd.Text("&&")
1408 }
1409
1410 for _, pair := range buildStatement.Env {
1411 // Set per-action env variables, if any.
1412 cmd.Flag(pair.Key + "=" + pair.Value)
1413 }
1414
1415 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001416 if len(buildStatement.Command) > 16*1024 {
1417 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1418 WriteFileRule(ctx, commandFile, buildStatement.Command)
1419
1420 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1421 } else {
1422 cmd.Text(buildStatement.Command)
1423 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001424
1425 for _, outputPath := range buildStatement.OutputPaths {
1426 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1427 }
1428 for _, inputPath := range buildStatement.InputPaths {
1429 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1430 }
1431 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1432 otherDepsetName := bazelDepsetName(inputDepsetHash)
1433 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1434 }
1435
1436 if depfile := buildStatement.Depfile; depfile != nil {
1437 // The paths in depfile are relative to `executionRoot`.
1438 // Hence, they need to be corrected by replacing "bazel-out"
1439 // with the full `bazelOutDir`.
1440 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1441 // would be deemed missing.
1442 // (Note: The regexp uses a capture group because the version of sed
1443 // does not support a look-behind pattern.)
1444 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1445 bazelOutDir, *depfile)
1446 cmd.Text(replacement)
1447 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1448 }
1449
1450 for _, symlinkPath := range buildStatement.SymlinkPaths {
1451 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1452 }
1453}
1454
Chris Parsons8d6e4332021-02-22 16:13:50 -05001455func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001456 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001457}
1458
Chris Parsons787fb362021-10-14 18:43:51 -04001459func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001460 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001461 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001462 if key.configKey.osType.Class == Device {
1463 // For the generic Android, the expected result is "target|android", which
1464 // corresponds to the product_variable_config named "android_target" in
1465 // build/bazel/platforms/BUILD.bazel.
1466 arch = "target"
1467 } else {
1468 // Use host platform, which is currently hardcoded to be x86_64.
1469 arch = "x86_64"
1470 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001471 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001472 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001473 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001474 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001475 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001476 }
Yu Liue4312402023-01-18 09:15:31 -08001477 keyString := arch + "|" + osName
1478 if key.configKey.apexKey.WithinApex {
1479 keyString += "|" + withinApexToString(key.configKey.apexKey.WithinApex)
1480 }
1481
1482 if len(key.configKey.apexKey.ApexSdkVersion) > 0 {
1483 keyString += "|" + key.configKey.apexKey.ApexSdkVersion
1484 }
1485
1486 return keyString
Chris Parsons787fb362021-10-14 18:43:51 -04001487}
1488
Chris Parsonsf874e462022-05-10 13:50:12 -04001489func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001490 return configKey{
1491 // use string because Arch is not a valid key in go
1492 arch: ctx.Arch().String(),
1493 osType: ctx.Os(),
1494 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001495}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001496
Yu Liue4312402023-01-18 09:15:31 -08001497func GetConfigKeyApexVariant(ctx BaseModuleContext, apexKey *ApexConfigKey) configKey {
1498 configKey := GetConfigKey(ctx)
1499
1500 if apexKey != nil {
1501 configKey.apexKey = ApexConfigKey{
1502 WithinApex: apexKey.WithinApex,
1503 ApexSdkVersion: apexKey.ApexSdkVersion,
1504 }
1505 }
1506
1507 return configKey
1508}
1509
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001510func bazelDepsetName(contentHash string) string {
1511 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001512}
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001513
1514func EnvironmentVarsFile(config Config) string {
1515 return fmt.Sprintf(bazel.GeneratedBazelFileWarning+`
1516_env = %s
1517
1518env = _env
1519`,
1520 starlark_fmt.PrintStringList(allowedBazelEnvironmentVars, 0),
1521 )
1522}