blob: 252437091d2670a50f29ea9a960ae1a7a51a43bf [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"
19 "errors"
20 "fmt"
Chris Parsonsa798d962020-10-12 23:44:08 -040021 "io/ioutil"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040022 "os"
23 "os/exec"
Usta Shresthaacd5a0c2022-06-22 11:20:50 -040024 "path"
Chris Parsonsa798d962020-10-12 23:44:08 -040025 "path/filepath"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040026 "runtime"
27 "strings"
28 "sync"
Chris Parsonsa798d962020-10-12 23:44:08 -040029
Chris Parsonsad876012022-08-20 14:48:32 -040030 "android/soong/android/allowlists"
Chris Parsons944e7d02021-03-11 11:08:46 -050031 "android/soong/bazel/cquery"
Jingwen Chen1e347862021-09-02 12:11:49 +000032 "android/soong/shared"
Liz Kammer337e9032022-08-03 15:49:43 -040033
Chris Parsons1a7aca02022-04-25 22:35:15 -040034 "github.com/google/blueprint"
Liz Kammer8206d4f2021-03-03 16:40:52 -050035
Patrice Arruda05ab2d02020-12-12 06:24:26 +000036 "android/soong/bazel"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040037)
38
Sasha Smundak1da064c2022-06-08 16:36:16 -070039var (
40 writeBazelFile = pctx.AndroidStaticRule("bazelWriteFileRule", blueprint.RuleParams{
41 Command: `sed "s/\\\\n/\n/g" ${out}.rsp >${out}`,
42 Rspfile: "${out}.rsp",
43 RspfileContent: "${content}",
44 }, "content")
Sasha Smundakc180dbd2022-07-03 14:55:58 -070045 _ = pctx.HostBinToolVariable("bazelBuildRunfilesTool", "build-runfiles")
46 buildRunfilesRule = pctx.AndroidStaticRule("bazelBuildRunfiles", blueprint.RuleParams{
47 Command: "${bazelBuildRunfilesTool} ${in} ${outDir}",
48 Depfile: "",
49 Description: "",
50 CommandDeps: []string{"${bazelBuildRunfilesTool}"},
51 }, "outDir")
Sasha Smundak1da064c2022-06-08 16:36:16 -070052)
53
Chris Parsonsf874e462022-05-10 13:50:12 -040054func init() {
55 RegisterMixedBuildsMutator(InitRegistrationContext)
56}
57
58func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammer337e9032022-08-03 15:49:43 -040059 ctx.FinalDepsMutators(func(ctx RegisterMutatorsContext) {
Chris Parsonsf874e462022-05-10 13:50:12 -040060 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
61 })
62}
63
64func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
65 if m := ctx.Module(); m.Enabled() {
66 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
67 if mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx) {
68 mixedBuildMod.QueueBazelCall(ctx)
69 }
70 }
71 }
72}
73
Liz Kammerf29df7c2021-04-02 13:37:39 -040074type cqueryRequest interface {
75 // Name returns a string name for this request type. Such request type names must be unique,
76 // and must only consist of alphanumeric characters.
77 Name() string
78
79 // StarlarkFunctionBody returns a starlark function body to process this request type.
80 // The returned string is the body of a Starlark function which obtains
81 // all request-relevant information about a target and returns a string containing
82 // this information.
83 // The function should have the following properties:
84 // - `target` is the only parameter to this function (a configured target).
85 // - The return value must be a string.
86 // - The function body should not be indented outside of its own scope.
87 StarlarkFunctionBody() string
88}
89
Chris Parsons787fb362021-10-14 18:43:51 -040090// Portion of cquery map key to describe target configuration.
91type configKey struct {
Liz Kammer0940b892022-03-18 15:55:04 -040092 arch string
93 osType OsType
Chris Parsons787fb362021-10-14 18:43:51 -040094}
95
Sasha Smundakfe9a5b82022-07-27 14:51:45 -070096func (c configKey) String() string {
97 return fmt.Sprintf("%s::%s", c.arch, c.osType)
98}
99
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400100// Map key to describe bazel cquery requests.
101type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400102 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400103 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400104 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400105}
106
Chris Parsons86dc2c22022-09-28 14:58:41 -0400107func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
108 if strings.HasPrefix(label, "//") {
109 // Normalize Bazel labels to specify main repository explicitly.
110 label = "@" + label
111 }
112 return cqueryKey{label, cqueryRequest, cfgKey}
113}
114
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700115func (c cqueryKey) String() string {
116 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700117}
118
Chris Parsonsf874e462022-05-10 13:50:12 -0400119// BazelContext is a context object useful for interacting with Bazel during
120// the course of a build. Use of Bazel to evaluate part of the build graph
121// is referred to as a "mixed build". (Some modules are managed by Soong,
122// some are managed by Bazel). To facilitate interop between these build
123// subgraphs, Soong may make requests to Bazel and evaluate their responses
124// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400125type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400126 // Add a cquery request to the bazel request queue. All queued requests
127 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
128 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
129
130 // ** Cquery Results Retrieval Functions
131 // The below functions pertain to retrieving cquery results from a prior
132 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400133
134 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400135 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500136
Chris Parsons944e7d02021-03-11 11:08:46 -0500137 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400138 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400139
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000140 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400141 // TODO(b/232976601): Remove.
142 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000143
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700144 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400145 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700146
Sasha Smundakedd16662022-10-07 14:44:50 -0700147 // Returns the results of the GetCcUnstrippedInfo query
148 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
149
Chris Parsonsf874e462022-05-10 13:50:12 -0400150 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400151
152 // Issues commands to Bazel to receive results for all cquery requests
153 // queued in the BazelContext.
Yu Liu8d82ac52022-05-17 15:13:28 -0700154 InvokeBazel(config Config) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400155
Chris Parsonsad876012022-08-20 14:48:32 -0400156 // Returns true if Bazel handling is enabled for the module with the given name.
157 // Note that this only implies "bazel mixed build" allowlisting. The caller
158 // should independently verify the module is eligible for Bazel handling
159 // (for example, that it is MixedBuildBuildable).
160 BazelAllowlisted(moduleName string) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500161
162 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
163 OutputBase() string
164
165 // Returns build statements which should get registered to reflect Bazel's outputs.
166 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400167
168 // Returns the depsets defined in Bazel's aquery response.
169 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400170}
171
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400172type bazelRunner interface {
Jason Wu52cd1942022-09-08 15:37:57 +0000173 createBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) *exec.Cmd
174 issueBazelCommand(bazelCmd *exec.Cmd) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400175}
176
177type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000178 homeDir string
179 bazelPath string
180 outputBase string
181 workspaceDir string
182 soongOutDir string
183 metricsDir string
184 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400185}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400186
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400187// A context object which tracks queued requests that need to be made to Bazel,
188// and their results after the requests have been made.
189type bazelContext struct {
190 bazelRunner
191 paths *bazelPaths
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400192 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
193 requestMutex sync.Mutex // requests can be written in parallel
194
195 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500196
197 // Build statements which should get registered to reflect Bazel's outputs.
198 buildStatements []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400199
200 // Depsets which should be used for Bazel's build statements.
201 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400202
203 // Per-module allowlist/denylist functionality to control whether analysis of
204 // modules are handled by Bazel. For modules which do not have a Bazel definition
205 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
206 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
207 // Per-module denylist to opt modules out of bazel handling.
208 bazelDisabledModules map[string]bool
209 // Per-module allowlist to opt modules in to bazel handling.
210 bazelEnabledModules map[string]bool
211 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
212 modulesDefaultToBazel bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400213}
214
215var _ BazelContext = &bazelContext{}
216
217// A bazel context to use when Bazel is disabled.
218type noopBazelContext struct{}
219
220var _ BazelContext = noopBazelContext{}
221
222// A bazel context to use for tests.
223type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400224 OutputBaseDir string
225
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000226 LabelToOutputFiles map[string][]string
227 LabelToCcInfo map[string]cquery.CcInfo
228 LabelToPythonBinary map[string]string
Liz Kammerbe6a7122022-11-04 16:05:11 -0400229 LabelToApexInfo map[string]cquery.ApexInfo
Sasha Smundakedd16662022-10-07 14:44:50 -0700230 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400231}
232
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700233func (m MockBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400234 panic("unimplemented")
Chris Parsons8d6e4332021-02-22 16:13:50 -0500235}
236
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700237func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400238 result, _ := m.LabelToOutputFiles[label]
239 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400240}
241
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700242func (m MockBazelContext) GetCcInfo(label string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400243 result, _ := m.LabelToCcInfo[label]
244 return result, nil
245}
246
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700247func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400248 result, _ := m.LabelToPythonBinary[label]
249 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000250}
251
Liz Kammerbe6a7122022-11-04 16:05:11 -0400252func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Liz Kammer0e255ef2022-11-04 16:07:04 -0400253 result, _ := m.LabelToApexInfo[label]
254 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700255}
256
Sasha Smundakedd16662022-10-07 14:44:50 -0700257func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
258 result, _ := m.LabelToCcBinary[label]
259 return result, nil
260}
261
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700262func (m MockBazelContext) InvokeBazel(_ Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400263 panic("unimplemented")
264}
265
Chris Parsonsad876012022-08-20 14:48:32 -0400266func (m MockBazelContext) BazelAllowlisted(moduleName string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400267 return true
268}
269
Liz Kammera92e8442021-04-07 20:25:21 -0400270func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500271
272func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
273 return []bazel.BuildStatement{}
274}
275
Chris Parsons1a7aca02022-04-25 22:35:15 -0400276func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
277 return []bazel.AqueryDepset{}
278}
279
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400280var _ BazelContext = MockBazelContext{}
281
Chris Parsonsf874e462022-05-10 13:50:12 -0400282func (bazelCtx *bazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400283 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400284 bazelCtx.requestMutex.Lock()
285 defer bazelCtx.requestMutex.Unlock()
286 bazelCtx.requests[key] = true
287}
288
289func (bazelCtx *bazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400290 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400291 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500292 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400293
Chris Parsonsf874e462022-05-10 13:50:12 -0400294 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400295 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400296 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400297}
298
Chris Parsonsf874e462022-05-10 13:50:12 -0400299func (bazelCtx *bazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400300 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400301 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000302 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400303 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000304 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400305 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 +0000306}
307
Chris Parsonsf874e462022-05-10 13:50:12 -0400308func (bazelCtx *bazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400309 key := makeCqueryKey(label, cquery.GetPythonBinary, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400310 if rawString, ok := bazelCtx.results[key]; ok {
311 bazelOutput := strings.TrimSpace(rawString)
312 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
313 }
314 return "", fmt.Errorf("no bazel response found for %v", key)
315}
316
Liz Kammerbe6a7122022-11-04 16:05:11 -0400317func (bazelCtx *bazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400318 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700319 if rawString, ok := bazelCtx.results[key]; ok {
320 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString)), nil
321 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400322 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700323}
324
Sasha Smundakedd16662022-10-07 14:44:50 -0700325func (bazelCtx *bazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
326 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
327 if rawString, ok := bazelCtx.results[key]; ok {
328 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString)), nil
329 }
330 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
331}
332
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700333func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500334 panic("unimplemented")
335}
336
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700337func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500338 panic("unimplemented")
339}
340
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700341func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400342 panic("unimplemented")
343}
344
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700345func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000346 panic("unimplemented")
347}
348
Liz Kammerbe6a7122022-11-04 16:05:11 -0400349func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700350 panic("unimplemented")
351}
352
Sasha Smundakedd16662022-10-07 14:44:50 -0700353func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
354 //TODO implement me
355 panic("implement me")
356}
357
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700358func (n noopBazelContext) InvokeBazel(_ Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400359 panic("unimplemented")
360}
361
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500362func (m noopBazelContext) OutputBase() string {
363 return ""
364}
365
Chris Parsonsad876012022-08-20 14:48:32 -0400366func (n noopBazelContext) BazelAllowlisted(moduleName string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400367 return false
368}
369
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500370func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
371 return []bazel.BuildStatement{}
372}
373
Chris Parsons1a7aca02022-04-25 22:35:15 -0400374func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
375 return []bazel.AqueryDepset{}
376}
377
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400378func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400379 var modulesDefaultToBazel bool
380 disabledModules := map[string]bool{}
381 enabledModules := map[string]bool{}
382
383 switch c.BuildMode {
384 case BazelProdMode:
385 modulesDefaultToBazel = false
386
387 for _, enabledProdModule := range allowlists.ProdMixedBuildsEnabledList {
388 enabledModules[enabledProdModule] = true
389 }
MarkDacekb78465d2022-10-18 20:10:16 +0000390 case BazelStagingMode:
391 modulesDefaultToBazel = false
392 for _, enabledStagingMode := range allowlists.StagingMixedBuildsEnabledList {
393 enabledModules[enabledStagingMode] = true
394
395 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400396 case BazelDevMode:
397 modulesDefaultToBazel = true
398
399 // Don't use partially-converted cc_library targets in mixed builds,
400 // since mixed builds would generally rely on both static and shared
401 // variants of a cc_library.
402 for staticOnlyModule, _ := range GetBp2BuildAllowList().ccLibraryStaticOnly {
403 disabledModules[staticOnlyModule] = true
404 }
405 for _, disabledDevModule := range allowlists.MixedBuildsDisabledList {
406 disabledModules[disabledDevModule] = true
407 }
408 default:
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400409 return noopBazelContext{}, nil
410 }
411
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400412 p, err := bazelPathsFromConfig(c)
413 if err != nil {
414 return nil, err
415 }
Chris Parsonsad876012022-08-20 14:48:32 -0400416
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400417 return &bazelContext{
Chris Parsonsad876012022-08-20 14:48:32 -0400418 bazelRunner: &builtinBazelRunner{},
419 paths: p,
420 requests: make(map[cqueryKey]bool),
Chris Parsonsef615e52022-08-18 22:04:11 -0400421 modulesDefaultToBazel: modulesDefaultToBazel,
422 bazelEnabledModules: enabledModules,
Chris Parsonsad876012022-08-20 14:48:32 -0400423 bazelDisabledModules: disabledModules,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400424 }, nil
425}
426
427func bazelPathsFromConfig(c *config) (*bazelPaths, error) {
428 p := bazelPaths{
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200429 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400430 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700431 var missingEnvVars []string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400432 if len(c.Getenv("BAZEL_HOME")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400433 p.homeDir = c.Getenv("BAZEL_HOME")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400434 } else {
435 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
436 }
437 if len(c.Getenv("BAZEL_PATH")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400438 p.bazelPath = c.Getenv("BAZEL_PATH")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400439 } else {
440 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
441 }
442 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400443 p.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400444 } else {
445 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
446 }
447 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400448 p.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400449 } else {
450 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
451 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000452 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400453 p.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000454 } else {
455 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
456 }
MarkDacek0d5bca52022-10-10 20:07:48 +0000457 if len(c.Getenv("BAZEL_DEPS_FILE")) > 1 {
458 p.bazelDepsFile = c.Getenv("BAZEL_DEPS_FILE")
459 } else {
460 missingEnvVars = append(missingEnvVars, "BAZEL_DEPS_FILE")
461 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400462 if len(missingEnvVars) > 0 {
463 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
464 } else {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400465 return &p, nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400466 }
467}
468
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400469func (p *bazelPaths) BazelMetricsDir() string {
470 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000471}
472
Chris Parsonsad876012022-08-20 14:48:32 -0400473func (context *bazelContext) BazelAllowlisted(moduleName string) bool {
474 if context.bazelDisabledModules[moduleName] {
475 return false
476 }
477 if context.bazelEnabledModules[moduleName] {
478 return true
479 }
480 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400481}
482
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400483func pwdPrefix() string {
484 // Darwin doesn't have /proc
485 if runtime.GOOS != "darwin" {
486 return "PWD=/proc/self/cwd"
487 }
488 return ""
489}
490
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400491type bazelCommand struct {
492 command string
493 // query or label
494 expression string
495}
496
497type mockBazelRunner struct {
498 bazelCommandResults map[bazelCommand]string
Jason Wu52cd1942022-09-08 15:37:57 +0000499 // use *exec.Cmd as a key to get the bazelCommand, the map will be used in issueBazelCommand()
500 // Register createBazelCommand() invocations. Later, an
501 // issueBazelCommand() invocation can be mapped to the *exec.Cmd instance
502 // and then to the expected result via bazelCommandResults
503 tokens map[*exec.Cmd]bazelCommand
504 commands []bazelCommand
505 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400506}
507
Jason Wu52cd1942022-09-08 15:37:57 +0000508func (r *mockBazelRunner) createBazelCommand(paths *bazelPaths, runName bazel.RunName,
509 command bazelCommand, extraFlags ...string) *exec.Cmd {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400510 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700511 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Jason Wu52cd1942022-09-08 15:37:57 +0000512 cmd := &exec.Cmd{}
513 if r.tokens == nil {
514 r.tokens = make(map[*exec.Cmd]bazelCommand)
515 }
516 r.tokens[cmd] = command
517 return cmd
518}
519
520func (r *mockBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
521 if command, ok := r.tokens[bazelCmd]; ok {
522 return r.bazelCommandResults[command], "", nil
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400523 }
524 return "", "", nil
525}
526
527type builtinBazelRunner struct{}
528
Chris Parsons808d84c2021-03-09 20:43:32 -0500529// Issues the given bazel command with given build label and additional flags.
530// Returns (stdout, stderr, error). The first and second return values are strings
531// containing the stdout and stderr of the run command, and an error is returned if
532// the invocation returned an error code.
Jason Wu52cd1942022-09-08 15:37:57 +0000533
534func (r *builtinBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
535 stderr := &bytes.Buffer{}
536 bazelCmd.Stderr = stderr
537 if output, err := bazelCmd.Output(); err != nil {
538 return "", string(stderr.Bytes()),
539 fmt.Errorf("bazel command failed. command: [%s], env: [%s], error [%s]", bazelCmd, bazelCmd.Env, stderr)
540 } else {
541 return string(output), string(stderr.Bytes()), nil
542 }
543}
544
545func (r *builtinBazelRunner) createBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
546 extraFlags ...string) *exec.Cmd {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000547 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000548 "--output_base=" + absolutePath(paths.outputBase),
549 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700550 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700551 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700552 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400553
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700554 // Set default platforms to canonicalized values for mixed builds requests.
555 // If these are set in the bazelrc, they will have values that are
556 // non-canonicalized to @sourceroot labels, and thus be invalid when
557 // referenced from the buildroot.
558 //
559 // The actual platform values here may be overridden by configuration
560 // transitions from the buildroot.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700561 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700562 // This should be parameterized on the host OS, but let's restrict to linux
563 // to keep things simple for now.
564 fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"),
565
566 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
567 "--experimental_repository_disable_download",
568
569 // Suppress noise
570 "--ui_event_filters=-INFO",
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700571 "--noshow_progress"}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400572 cmdFlags = append(cmdFlags, extraFlags...)
573
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400574 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200575 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700576 extraEnv := []string{
577 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200578 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700579 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700580 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000581 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700582 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500583 // Disables local host detection of gcc; toolchain information is defined
584 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700585 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
586 }
587 bazelCmd.Env = append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400588
Jason Wu52cd1942022-09-08 15:37:57 +0000589 return bazelCmd
590}
591
592func printableCqueryCommand(bazelCmd *exec.Cmd) string {
593 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(bazelCmd.Args, "\" \"") + "\""
594 return outputString
595
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400596}
597
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400598func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500599 // TODO(cparsons): Define configuration transitions programmatically based
600 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400601 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500602#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400603# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500604#####################################################
605
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400606def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500607 return {
Chris Parsons787fb362021-10-14 18:43:51 -0400608 "//command_line_option:platforms": "@//build/bazel/platforms:%s_%s" % (attr.os, attr.arch),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500609 }
610
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400611_config_node_transition = transition(
612 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500613 inputs = [],
614 outputs = [
615 "//command_line_option:platforms",
616 ],
617)
618
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400619def _passthrough_rule_impl(ctx):
620 return [DefaultInfo(files = depset(ctx.files.deps))]
621
622config_node = rule(
623 implementation = _passthrough_rule_impl,
624 attrs = {
625 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400626 "os" : attr.string(mandatory = True),
627 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400628 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
629 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500630)
631
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400632
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500633# Rule representing the root of the build, to depend on all Bazel targets that
634# are required for the build. Building this target will build the entire Bazel
635# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400636mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400637 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500638 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400639 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500640 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400641)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500642
643def _phony_root_impl(ctx):
644 return []
645
646# Rule to depend on other targets but build nothing.
647# This is useful as follows: building a target of this rule will generate
648# symlink forests for all dependencies of the target, without executing any
649# actions of the build.
650phony_root = rule(
651 implementation = _phony_root_impl,
652 attrs = {"deps" : attr.label_list()},
653)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400654`
655 return []byte(contents)
656}
657
658func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500659 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
660 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400661 formatString := `
662# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400663load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
664
665%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400666
667mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400668 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400669)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500670
671phony_root(name = "phonyroot",
672 deps = [":buildroot"],
673)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400674`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400675 configNodeFormatString := `
676config_node(name = "%s",
677 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400678 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400679 deps = [%s],
680)
681`
682
683 configNodesSection := ""
684
Chris Parsons787fb362021-10-14 18:43:51 -0400685 labelsByConfig := map[string][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400686 for val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200687 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400688 configString := getConfigString(val)
689 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400690 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400691
Jingwen Chen1e347862021-09-02 12:11:49 +0000692 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400693 for configString, labels := range labelsByConfig {
694 configTokens := strings.Split(configString, "|")
695 if len(configTokens) != 2 {
696 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000697 }
Chris Parsons787fb362021-10-14 18:43:51 -0400698 archString := configTokens[0]
699 osString := configTokens[1]
700 targetString := fmt.Sprintf("%s_%s", osString, archString)
701 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
702 labelsString := strings.Join(labels, ",\n ")
703 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400704 }
705
Jingwen Chen1e347862021-09-02 12:11:49 +0000706 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400707}
708
Chris Parsons944e7d02021-03-11 11:08:46 -0500709func indent(original string) string {
710 result := ""
711 for _, line := range strings.Split(original, "\n") {
712 result += " " + line + "\n"
713 }
714 return result
715}
716
Chris Parsons808d84c2021-03-09 20:43:32 -0500717// Returns the file contents of the buildroot.cquery file that should be used for the cquery
718// expression in order to obtain information about buildroot and its dependencies.
719// The contents of this file depend on the bazelContext's requests; requests are enumerated
720// and grouped by their request type. The data retrieved for each label depends on its
721// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400722func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400723 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400724 for val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500725 cqueryId := getCqueryId(val)
726 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
727 requestTypeToCqueryIdEntries[val.requestType] =
728 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
729 }
730 labelRegistrationMapSection := ""
731 functionDefSection := ""
732 mainSwitchSection := ""
733
734 mapDeclarationFormatString := `
735%s = {
736 %s
737}
738`
739 functionDefFormatString := `
740def %s(target):
741%s
742`
743 mainSwitchSectionFormatString := `
744 if id_string in %s:
745 return id_string + ">>" + %s(target)
746`
747
Usta Shrestha0b52d832022-02-04 21:37:39 -0500748 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500749 labelMapName := requestType.Name() + "_Labels"
750 functionName := requestType.Name() + "_Fn"
751 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
752 labelMapName,
753 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
754 functionDefSection += fmt.Sprintf(functionDefFormatString,
755 functionName,
756 indent(requestType.StarlarkFunctionBody()))
757 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
758 labelMapName, functionName)
759 }
760
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400761 formatString := `
762# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400763
Usta Shrestha79fccef2022-09-02 18:37:40 -0400764# a drop-in replacement for json.encode(), not available in cquery environment
765# TODO(cparsons): bring json module in and remove this function
766def json_encode(input):
767 # Avoiding recursion by limiting
768 # - a dict to contain anything except a dict
769 # - a list to contain only primitives
770 def encode_primitive(p):
771 t = type(p)
772 if t == "string" or t == "int":
773 return repr(p)
774 fail("unsupported value '%%s' of type '%%s'" %% (p, type(p)))
775
776 def encode_list(list):
777 return "[%%s]" %% ", ".join([encode_primitive(item) for item in list])
778
779 def encode_list_or_primitive(v):
780 return encode_list(v) if type(v) == "list" else encode_primitive(v)
781
782 if type(input) == "dict":
783 # TODO(juu): the result is read line by line so can't use '\n' yet
784 kv_pairs = [("%%s: %%s" %% (encode_primitive(k), encode_list_or_primitive(v))) for (k, v) in input.items()]
785 return "{ %%s }" %% ", ".join(kv_pairs)
786 else:
787 return encode_list_or_primitive(input)
788
Chris Parsons944e7d02021-03-11 11:08:46 -0500789# Label Map Section
790%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500791
Chris Parsons944e7d02021-03-11 11:08:46 -0500792# Function Def Section
793%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500794
795def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400796 # TODO(b/199363072): filegroups and file targets aren't associated with any
797 # specific platform architecture in mixed builds. This is consistent with how
798 # Soong treats filegroups, but it may not be the case with manually-written
799 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500800 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000801 if buildoptions == None:
802 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400803 # any specific platform architecture in mixed builds, so use the host.
804 return "x86_64|linux"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500805 platforms = build_options(target)["//command_line_option:platforms"]
806 if len(platforms) != 1:
807 # An individual configured target should have only one platform architecture.
808 # Note that it's fine for there to be multiple architectures for the same label,
809 # but each is its own configured target.
810 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
811 platform_name = build_options(target)["//command_line_option:platforms"][0].name
812 if platform_name == "host":
813 return "HOST"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400814 elif platform_name.startswith("android_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400815 return platform_name[len("android_"):] + "|" + platform_name[:len("android_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400816 elif platform_name.startswith("linux_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400817 return platform_name[len("linux_"):] + "|" + platform_name[:len("linux_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400818 else:
819 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500820 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500821
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400822def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500823 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500824
Chris Parsons86dc2c22022-09-28 14:58:41 -0400825 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
826 if id_string.startswith("//"):
827 id_string = "@" + id_string
828
Chris Parsons944e7d02021-03-11 11:08:46 -0500829 # Main switch section
830 %s
831 # This target was not requested via cquery, and thus must be a dependency
832 # of a requested target.
833 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400834`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400835
Chris Parsons944e7d02021-03-11 11:08:46 -0500836 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
837 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400838}
839
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200840// Returns a path containing build-related metadata required for interfacing
841// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400842func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200843 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500844}
845
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200846// Returns the path where the contents of the @soong_injection repository live.
847// It is used by Soong to tell Bazel things it cannot over the command line.
848func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200849 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200850}
851
852// Returns the path of the synthetic Bazel workspace that contains a symlink
853// forest composed the whole source tree and BUILD files generated by bp2build.
854func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200855 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200856}
857
Jingwen Chen8c523582021-06-01 11:19:53 +0000858// Returns the path to the top level out dir ($OUT_DIR).
859func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200860 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000861}
862
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400863// Issues commands to Bazel to receive results for all cquery requests
864// queued in the BazelContext.
Yu Liu8d82ac52022-05-17 15:13:28 -0700865func (context *bazelContext) InvokeBazel(config Config) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400866 context.results = make(map[cqueryKey]string)
867
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400868 var err error
Chris Parsons8ccdb632020-11-17 15:41:01 -0500869
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200870 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200871 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
872 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
873 err = os.MkdirAll(mixedBuildsPath, 0777)
Chris Parsons07c1e4a2021-01-19 17:19:16 -0500874 }
Chris Parsons8ccdb632020-11-17 15:41:01 -0500875 if err != nil {
876 return err
877 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500878 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
879 err = os.MkdirAll(metricsDir, 0777)
880 if err != nil {
881 return err
882 }
883 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700884 if err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200885 return err
886 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700887 if err = ioutil.WriteFile(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400888 return err
889 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700890 if err = ioutil.WriteFile(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400891 return err
892 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200893 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700894 if err = ioutil.WriteFile(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400895 return err
896 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000897
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700898 const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
899 cqueryCmd := bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
Jason Wu52cd1942022-09-08 15:37:57 +0000900 cqueryCommandWithFlag := context.createBazelCommand(context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700901 "--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
Jason Wu52cd1942022-09-08 15:37:57 +0000902 cqueryOutput, cqueryErr, err := context.issueBazelCommand(cqueryCommandWithFlag)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500903 if err != nil {
Chris Parsons429f5402022-08-11 17:02:41 -0400904 return err
Chris Parsons8d6e4332021-02-22 16:13:50 -0500905 }
Jason Wu52cd1942022-09-08 15:37:57 +0000906 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", printableCqueryCommand(cqueryCommandWithFlag))
907 if err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400908 return err
909 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400910 cqueryResults := map[string]string{}
911 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
912 if strings.Contains(outputLine, ">>") {
913 splitLine := strings.SplitN(outputLine, ">>", 2)
914 cqueryResults[splitLine[0]] = splitLine[1]
915 }
916 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500917 for val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500918 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -0500919 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400920 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500921 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
922 getCqueryId(val), cqueryOutput, cqueryErr)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400923 }
924 }
925
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500926 // Issue an aquery command to retrieve action information about the bazel build tree.
927 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700928 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
929 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +0000930 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -0700931 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700932 extraFlags = append(extraFlags, "--collect_code_coverage")
933 paths := make([]string, 0, 2)
934 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
935 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
936 }
937 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
938 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
939 }
940 if len(paths) > 0 {
941 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -0700942 }
943 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700944 aqueryCmd := bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
Jason Wu52cd1942022-09-08 15:37:57 +0000945 if aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
946 extraFlags...)); err == nil {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700947 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400948 }
Chris Parsons4f069892021-01-15 12:22:41 -0500949 if err != nil {
950 return err
951 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500952
953 // Issue a build command of the phony root to generate symlink forests for dependencies of the
954 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
955 // but some of symlinks may be required to resolve source dependencies of the build.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700956 buildCmd := bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
Jason Wu52cd1942022-09-08 15:37:57 +0000957 if _, _, err = context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd)); err != nil {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500958 return err
959 }
960
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400961 // Clear requests.
962 context.requests = map[cqueryKey]bool{}
963 return nil
964}
Chris Parsonsa798d962020-10-12 23:44:08 -0400965
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500966func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
967 return context.buildStatements
968}
969
Chris Parsons1a7aca02022-04-25 22:35:15 -0400970func (context *bazelContext) AqueryDepsets() []bazel.AqueryDepset {
971 return context.depsets
972}
973
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500974func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400975 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500976}
977
Chris Parsonsa798d962020-10-12 23:44:08 -0400978// Singleton used for registering BUILD file ninja dependencies (needed
979// for correctness of builds which use Bazel.
980func BazelSingleton() Singleton {
981 return &bazelSingleton{}
982}
983
984type bazelSingleton struct{}
985
986func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500987 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -0400988 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500989 return
990 }
Chris Parsonsa798d962020-10-12 23:44:08 -0400991
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500992 // Add ninja file dependencies for files which all bazel invocations require.
993 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200994 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500995 ctx.AddNinjaFileDeps(bazelBuildList)
996
997 data, err := ioutil.ReadFile(bazelBuildList)
998 if err != nil {
999 ctx.Errorf(err.Error())
1000 }
1001 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1002 for _, file := range files {
1003 ctx.AddNinjaFileDeps(file)
1004 }
1005
Chris Parsons1a7aca02022-04-25 22:35:15 -04001006 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1007 var outputs []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001008 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1009 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001010 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1011 }
1012 for _, artifactPath := range depset.DirectArtifacts {
1013 outputs = append(outputs, PathForBazelOut(ctx, artifactPath))
1014 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001015 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001016 ctx.Build(pctx, BuildParams{
1017 Rule: blueprint.Phony,
1018 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1019 Implicits: outputs,
1020 })
1021 }
1022
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001023 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1024 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001025 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -07001026 if len(buildStatement.Command) > 0 {
1027 rule := NewRuleBuilder(pctx, ctx)
1028 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1029 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1030 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1031 continue
1032 }
1033 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1034 // and thus require special treatment. If BuildStatement were an interface implementing
1035 // buildRule(ctx) function, the code here would just call it.
1036 // Unfortunately, the BuildStatement is defined in
1037 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1038 // because this would cause circular dependency. So, until we move aquery processing
1039 // to the 'android' package, we need to handle special cases here.
1040 if buildStatement.Mnemonic == "FileWrite" || buildStatement.Mnemonic == "SourceSymlinkManifest" {
1041 // Pass file contents as the value of the rule's "content" argument.
1042 // Escape newlines and $ in the contents (the action "writeBazelFile" restores "\\n"
1043 // back to the newline, and Ninja reads $$ as $.
1044 escaped := strings.ReplaceAll(strings.ReplaceAll(buildStatement.FileContents, "\n", "\\n"),
1045 "$", "$$")
1046 ctx.Build(pctx, BuildParams{
1047 Rule: writeBazelFile,
1048 Output: PathForBazelOut(ctx, buildStatement.OutputPaths[0]),
1049 Description: fmt.Sprintf("%s %s", buildStatement.Mnemonic, buildStatement.OutputPaths[0]),
1050 Args: map[string]string{
1051 "content": escaped,
1052 },
1053 })
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001054 } else if buildStatement.Mnemonic == "SymlinkTree" {
1055 // build-runfiles arguments are the manifest file and the target directory
1056 // where it creates the symlink tree according to this manifest (and then
1057 // writes the MANIFEST file to it).
1058 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1059 outManifestPath := outManifest.String()
1060 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1061 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1062 }
1063 outDir := filepath.Dir(outManifestPath)
1064 ctx.Build(pctx, BuildParams{
1065 Rule: buildRunfilesRule,
1066 Output: outManifest,
1067 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1068 Description: "symlink tree for " + outDir,
1069 Args: map[string]string{
1070 "outDir": outDir,
1071 },
1072 })
Sasha Smundak1da064c2022-06-08 16:36:16 -07001073 } else {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001074 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001075 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001076 }
1077}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001078
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001079// Register bazel-owned build statements (obtained from the aquery invocation).
1080func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx PathContext) {
1081 // executionRoot is the action cwd.
1082 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1083
1084 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1085 if len(buildStatement.OutputPaths) > 0 {
1086 cmd.Text("rm -f")
1087 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001088 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001089 }
1090 cmd.Text("&&")
1091 }
1092
1093 for _, pair := range buildStatement.Env {
1094 // Set per-action env variables, if any.
1095 cmd.Flag(pair.Key + "=" + pair.Value)
1096 }
1097
1098 // The actual Bazel action.
1099 cmd.Text(buildStatement.Command)
1100
1101 for _, outputPath := range buildStatement.OutputPaths {
1102 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1103 }
1104 for _, inputPath := range buildStatement.InputPaths {
1105 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1106 }
1107 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1108 otherDepsetName := bazelDepsetName(inputDepsetHash)
1109 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1110 }
1111
1112 if depfile := buildStatement.Depfile; depfile != nil {
1113 // The paths in depfile are relative to `executionRoot`.
1114 // Hence, they need to be corrected by replacing "bazel-out"
1115 // with the full `bazelOutDir`.
1116 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1117 // would be deemed missing.
1118 // (Note: The regexp uses a capture group because the version of sed
1119 // does not support a look-behind pattern.)
1120 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1121 bazelOutDir, *depfile)
1122 cmd.Text(replacement)
1123 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1124 }
1125
1126 for _, symlinkPath := range buildStatement.SymlinkPaths {
1127 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1128 }
1129}
1130
Chris Parsons8d6e4332021-02-22 16:13:50 -05001131func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001132 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001133}
1134
Chris Parsons787fb362021-10-14 18:43:51 -04001135func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001136 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001137 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001138 if key.configKey.osType.Class == Device {
1139 // For the generic Android, the expected result is "target|android", which
1140 // corresponds to the product_variable_config named "android_target" in
1141 // build/bazel/platforms/BUILD.bazel.
1142 arch = "target"
1143 } else {
1144 // Use host platform, which is currently hardcoded to be x86_64.
1145 arch = "x86_64"
1146 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001147 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001148 osName := key.configKey.osType.Name
1149 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" {
Chris Parsons787fb362021-10-14 18:43:51 -04001150 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001151 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001152 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001153 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -04001154}
1155
Chris Parsonsf874e462022-05-10 13:50:12 -04001156func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001157 return configKey{
1158 // use string because Arch is not a valid key in go
1159 arch: ctx.Arch().String(),
1160 osType: ctx.Os(),
1161 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001162}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001163
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001164func bazelDepsetName(contentHash string) string {
1165 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001166}