blob: 8d4504175cd8c1bbdf8b6e533f779a20f868272d [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"
Liz Kammer337e9032022-08-03 15:49:43 -040032
Chris Parsons1a7aca02022-04-25 22:35:15 -040033 "github.com/google/blueprint"
Liz Kammer8206d4f2021-03-03 16:40:52 -050034
Patrice Arruda05ab2d02020-12-12 06:24:26 +000035 "android/soong/bazel"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040036)
37
Sasha Smundak1da064c2022-06-08 16:36:16 -070038var (
Sasha Smundakc180dbd2022-07-03 14:55:58 -070039 _ = pctx.HostBinToolVariable("bazelBuildRunfilesTool", "build-runfiles")
40 buildRunfilesRule = pctx.AndroidStaticRule("bazelBuildRunfiles", blueprint.RuleParams{
41 Command: "${bazelBuildRunfilesTool} ${in} ${outDir}",
42 Depfile: "",
43 Description: "",
44 CommandDeps: []string{"${bazelBuildRunfilesTool}"},
45 }, "outDir")
Sasha Smundak1da064c2022-06-08 16:36:16 -070046)
47
Chris Parsonsf874e462022-05-10 13:50:12 -040048func init() {
49 RegisterMixedBuildsMutator(InitRegistrationContext)
50}
51
52func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammer337e9032022-08-03 15:49:43 -040053 ctx.FinalDepsMutators(func(ctx RegisterMutatorsContext) {
Chris Parsonsf874e462022-05-10 13:50:12 -040054 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
55 })
56}
57
58func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
59 if m := ctx.Module(); m.Enabled() {
60 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
61 if mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx) {
62 mixedBuildMod.QueueBazelCall(ctx)
63 }
64 }
65 }
66}
67
Liz Kammerf29df7c2021-04-02 13:37:39 -040068type cqueryRequest interface {
69 // Name returns a string name for this request type. Such request type names must be unique,
70 // and must only consist of alphanumeric characters.
71 Name() string
72
73 // StarlarkFunctionBody returns a starlark function body to process this request type.
74 // The returned string is the body of a Starlark function which obtains
75 // all request-relevant information about a target and returns a string containing
76 // this information.
77 // The function should have the following properties:
Cole Faust97d15272022-11-22 14:08:59 -080078 // - The arguments are `target` (a configured target) and `id_string` (the label + configuration).
Liz Kammerf29df7c2021-04-02 13:37:39 -040079 // - The return value must be a string.
80 // - The function body should not be indented outside of its own scope.
81 StarlarkFunctionBody() string
82}
83
Chris Parsons787fb362021-10-14 18:43:51 -040084// Portion of cquery map key to describe target configuration.
85type configKey struct {
Liz Kammer0940b892022-03-18 15:55:04 -040086 arch string
87 osType OsType
Chris Parsons787fb362021-10-14 18:43:51 -040088}
89
Sasha Smundakfe9a5b82022-07-27 14:51:45 -070090func (c configKey) String() string {
91 return fmt.Sprintf("%s::%s", c.arch, c.osType)
92}
93
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040094// Map key to describe bazel cquery requests.
95type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -040096 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -040097 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -040098 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040099}
100
Chris Parsons86dc2c22022-09-28 14:58:41 -0400101func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
102 if strings.HasPrefix(label, "//") {
103 // Normalize Bazel labels to specify main repository explicitly.
104 label = "@" + label
105 }
106 return cqueryKey{label, cqueryRequest, cfgKey}
107}
108
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700109func (c cqueryKey) String() string {
110 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700111}
112
Chris Parsonsf874e462022-05-10 13:50:12 -0400113// BazelContext is a context object useful for interacting with Bazel during
114// the course of a build. Use of Bazel to evaluate part of the build graph
115// is referred to as a "mixed build". (Some modules are managed by Soong,
116// some are managed by Bazel). To facilitate interop between these build
117// subgraphs, Soong may make requests to Bazel and evaluate their responses
118// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400119type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400120 // Add a cquery request to the bazel request queue. All queued requests
121 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
122 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
123
124 // ** Cquery Results Retrieval Functions
125 // The below functions pertain to retrieving cquery results from a prior
126 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400127
128 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400129 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500130
Chris Parsons944e7d02021-03-11 11:08:46 -0500131 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400132 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400133
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000134 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400135 // TODO(b/232976601): Remove.
136 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000137
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700138 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400139 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700140
Sasha Smundakedd16662022-10-07 14:44:50 -0700141 // Returns the results of the GetCcUnstrippedInfo query
142 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
143
Chris Parsonsf874e462022-05-10 13:50:12 -0400144 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400145
146 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800147 // queued in the BazelContext. The ctx argument is optional and is only
148 // used for performance data collection
149 InvokeBazel(config Config, ctx *Context) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400150
Chris Parsonsad876012022-08-20 14:48:32 -0400151 // Returns true if Bazel handling is enabled for the module with the given name.
152 // Note that this only implies "bazel mixed build" allowlisting. The caller
153 // should independently verify the module is eligible for Bazel handling
154 // (for example, that it is MixedBuildBuildable).
Sasha Smundak39a301c2022-12-29 17:11:49 -0800155 IsModuleNameAllowed(moduleName string) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500156
157 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
158 OutputBase() string
159
160 // Returns build statements which should get registered to reflect Bazel's outputs.
161 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400162
163 // Returns the depsets defined in Bazel's aquery response.
164 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400165}
166
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400167type bazelRunner interface {
Jason Wu52cd1942022-09-08 15:37:57 +0000168 createBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) *exec.Cmd
169 issueBazelCommand(bazelCmd *exec.Cmd) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400170}
171
172type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000173 homeDir string
174 bazelPath string
175 outputBase string
176 workspaceDir string
177 soongOutDir string
178 metricsDir string
179 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400180}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400181
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400182// A context object which tracks queued requests that need to be made to Bazel,
183// and their results after the requests have been made.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800184type mixedBuildBazelContext struct {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400185 bazelRunner
186 paths *bazelPaths
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400187 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
188 requestMutex sync.Mutex // requests can be written in parallel
189
190 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500191
192 // Build statements which should get registered to reflect Bazel's outputs.
193 buildStatements []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400194
195 // Depsets which should be used for Bazel's build statements.
196 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400197
198 // Per-module allowlist/denylist functionality to control whether analysis of
199 // modules are handled by Bazel. For modules which do not have a Bazel definition
200 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
201 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
202 // Per-module denylist to opt modules out of bazel handling.
203 bazelDisabledModules map[string]bool
204 // Per-module allowlist to opt modules in to bazel handling.
205 bazelEnabledModules map[string]bool
206 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
207 modulesDefaultToBazel bool
Cole Faustb85d1a12022-11-08 18:14:01 -0800208
209 targetProduct string
210 targetBuildVariant string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400211}
212
Sasha Smundak39a301c2022-12-29 17:11:49 -0800213var _ BazelContext = &mixedBuildBazelContext{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400214
215// A bazel context to use when Bazel is disabled.
216type noopBazelContext struct{}
217
218var _ BazelContext = noopBazelContext{}
219
220// A bazel context to use for tests.
221type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400222 OutputBaseDir string
223
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000224 LabelToOutputFiles map[string][]string
225 LabelToCcInfo map[string]cquery.CcInfo
226 LabelToPythonBinary map[string]string
Liz Kammerbe6a7122022-11-04 16:05:11 -0400227 LabelToApexInfo map[string]cquery.ApexInfo
Sasha Smundakedd16662022-10-07 14:44:50 -0700228 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400229}
230
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700231func (m MockBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400232 panic("unimplemented")
Chris Parsons8d6e4332021-02-22 16:13:50 -0500233}
234
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700235func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400236 result, _ := m.LabelToOutputFiles[label]
237 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400238}
239
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700240func (m MockBazelContext) GetCcInfo(label string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400241 result, _ := m.LabelToCcInfo[label]
242 return result, nil
243}
244
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700245func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400246 result, _ := m.LabelToPythonBinary[label]
247 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000248}
249
Liz Kammerbe6a7122022-11-04 16:05:11 -0400250func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Liz Kammer0e255ef2022-11-04 16:07:04 -0400251 result, _ := m.LabelToApexInfo[label]
252 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700253}
254
Sasha Smundakedd16662022-10-07 14:44:50 -0700255func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
256 result, _ := m.LabelToCcBinary[label]
257 return result, nil
258}
259
Sasha Smundak0e87b182022-12-01 11:46:11 -0800260func (m MockBazelContext) InvokeBazel(_ Config, _ *Context) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400261 panic("unimplemented")
262}
263
Sasha Smundak39a301c2022-12-29 17:11:49 -0800264func (m MockBazelContext) IsModuleNameAllowed(_ string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400265 return true
266}
267
Liz Kammera92e8442021-04-07 20:25:21 -0400268func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500269
270func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
271 return []bazel.BuildStatement{}
272}
273
Chris Parsons1a7aca02022-04-25 22:35:15 -0400274func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
275 return []bazel.AqueryDepset{}
276}
277
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400278var _ BazelContext = MockBazelContext{}
279
Sasha Smundak39a301c2022-12-29 17:11:49 -0800280func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400281 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400282 bazelCtx.requestMutex.Lock()
283 defer bazelCtx.requestMutex.Unlock()
284 bazelCtx.requests[key] = true
285}
286
Sasha Smundak39a301c2022-12-29 17:11:49 -0800287func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400288 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400289 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500290 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400291
Chris Parsonsf874e462022-05-10 13:50:12 -0400292 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400293 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400294 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400295}
296
Sasha Smundak39a301c2022-12-29 17:11:49 -0800297func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400298 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400299 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000300 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400301 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000302 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400303 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 +0000304}
305
Sasha Smundak39a301c2022-12-29 17:11:49 -0800306func (bazelCtx *mixedBuildBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400307 key := makeCqueryKey(label, cquery.GetPythonBinary, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400308 if rawString, ok := bazelCtx.results[key]; ok {
309 bazelOutput := strings.TrimSpace(rawString)
310 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
311 }
312 return "", fmt.Errorf("no bazel response found for %v", key)
313}
314
Sasha Smundak39a301c2022-12-29 17:11:49 -0800315func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400316 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700317 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500318 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700319 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400320 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700321}
322
Sasha Smundak39a301c2022-12-29 17:11:49 -0800323func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700324 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
325 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500326 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700327 }
328 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
329}
330
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700331func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500332 panic("unimplemented")
333}
334
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700335func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500336 panic("unimplemented")
337}
338
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700339func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400340 panic("unimplemented")
341}
342
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700343func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000344 panic("unimplemented")
345}
346
Liz Kammerbe6a7122022-11-04 16:05:11 -0400347func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700348 panic("unimplemented")
349}
350
Sasha Smundakedd16662022-10-07 14:44:50 -0700351func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
352 //TODO implement me
353 panic("implement me")
354}
355
Sasha Smundak0e87b182022-12-01 11:46:11 -0800356func (n noopBazelContext) InvokeBazel(_ Config, _ *Context) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400357 panic("unimplemented")
358}
359
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500360func (m noopBazelContext) OutputBase() string {
361 return ""
362}
363
Sasha Smundak39a301c2022-12-29 17:11:49 -0800364func (n noopBazelContext) IsModuleNameAllowed(_ string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400365 return false
366}
367
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500368func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
369 return []bazel.BuildStatement{}
370}
371
Chris Parsons1a7aca02022-04-25 22:35:15 -0400372func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
373 return []bazel.AqueryDepset{}
374}
375
Cole Faust705968d2022-12-14 11:32:05 -0800376func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400377 disabledModules := map[string]bool{}
378 enabledModules := map[string]bool{}
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800379 addToStringSet := func(set map[string]bool, items []string) {
380 for _, item := range items {
381 set[item] = true
382 }
383 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400384
Cole Faust705968d2022-12-14 11:32:05 -0800385 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400386 case BazelProdMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800387 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800388 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000389 enabledModules[enabledAdHocModule] = true
390 }
MarkDacekb78465d2022-10-18 20:10:16 +0000391 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400392 // Staging mode includes all prod modules plus all staging modules.
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800393 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
394 addToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800395 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000396 enabledModules[enabledAdHocModule] = true
397 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400398 case BazelDevMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800399 addToStringSet(disabledModules, allowlists.MixedBuildsDisabledList)
Chris Parsonsef615e52022-08-18 22:04:11 -0400400 default:
Cole Faust705968d2022-12-14 11:32:05 -0800401 panic("Expected BazelProdMode, BazelStagingMode, or BazelDevMode")
402 }
403 return enabledModules, disabledModules
404}
405
406func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
407 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
408 enabledList := make([]string, 0, len(enabledModules))
409 for module := range enabledModules {
410 if !disabledModules[module] {
411 enabledList = append(enabledList, module)
412 }
413 }
414 sort.Strings(enabledList)
415 return enabledList
416}
417
418func NewBazelContext(c *config) (BazelContext, error) {
419 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode && c.BuildMode != BazelDevMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400420 return noopBazelContext{}, nil
421 }
422
Cole Faust705968d2022-12-14 11:32:05 -0800423 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
424
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800425 paths := bazelPaths{
426 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400427 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800428 var missing []string
429 vars := []struct {
430 name string
431 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000432
433 // True if the environment variable needs to be tracked so that changes to the variable
434 // cause the ninja file to be regenerated, false otherwise. False should only be set for
435 // environment variables that have no effect on the generated ninja file.
436 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800437 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000438 {"BAZEL_HOME", &paths.homeDir, true},
439 {"BAZEL_PATH", &paths.bazelPath, true},
440 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
441 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
442 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
443 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800444 }
445 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000446 if v.track {
447 if s := c.Getenv(v.name); len(s) > 1 {
448 *v.ptr = s
449 continue
450 }
451 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800452 *v.ptr = s
453 } else {
454 missing = append(missing, v.name)
455 }
456 }
457 if len(missing) > 0 {
458 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
459 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800460
461 targetBuildVariant := "user"
462 if c.Eng() {
463 targetBuildVariant = "eng"
464 } else if c.Debuggable() {
465 targetBuildVariant = "userdebug"
466 }
467 targetProduct := "unknown"
468 if c.HasDeviceProduct() {
469 targetProduct = c.DeviceProduct()
470 }
471
Sasha Smundak39a301c2022-12-29 17:11:49 -0800472 return &mixedBuildBazelContext{
Chris Parsonsad876012022-08-20 14:48:32 -0400473 bazelRunner: &builtinBazelRunner{},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800474 paths: &paths,
Chris Parsonsad876012022-08-20 14:48:32 -0400475 requests: make(map[cqueryKey]bool),
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800476 modulesDefaultToBazel: c.BuildMode == BazelDevMode,
Chris Parsonsef615e52022-08-18 22:04:11 -0400477 bazelEnabledModules: enabledModules,
Chris Parsonsad876012022-08-20 14:48:32 -0400478 bazelDisabledModules: disabledModules,
Cole Faustb85d1a12022-11-08 18:14:01 -0800479 targetProduct: targetProduct,
480 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400481 }, nil
482}
483
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400484func (p *bazelPaths) BazelMetricsDir() string {
485 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000486}
487
Sasha Smundak39a301c2022-12-29 17:11:49 -0800488func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400489 if context.bazelDisabledModules[moduleName] {
490 return false
491 }
492 if context.bazelEnabledModules[moduleName] {
493 return true
494 }
495 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400496}
497
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400498func pwdPrefix() string {
499 // Darwin doesn't have /proc
500 if runtime.GOOS != "darwin" {
501 return "PWD=/proc/self/cwd"
502 }
503 return ""
504}
505
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400506type bazelCommand struct {
507 command string
508 // query or label
509 expression string
510}
511
512type mockBazelRunner struct {
513 bazelCommandResults map[bazelCommand]string
Jason Wu52cd1942022-09-08 15:37:57 +0000514 // use *exec.Cmd as a key to get the bazelCommand, the map will be used in issueBazelCommand()
515 // Register createBazelCommand() invocations. Later, an
516 // issueBazelCommand() invocation can be mapped to the *exec.Cmd instance
517 // and then to the expected result via bazelCommandResults
518 tokens map[*exec.Cmd]bazelCommand
519 commands []bazelCommand
520 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400521}
522
Sasha Smundak0e87b182022-12-01 11:46:11 -0800523func (r *mockBazelRunner) createBazelCommand(_ *bazelPaths, _ bazel.RunName,
Jason Wu52cd1942022-09-08 15:37:57 +0000524 command bazelCommand, extraFlags ...string) *exec.Cmd {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400525 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700526 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Jason Wu52cd1942022-09-08 15:37:57 +0000527 cmd := &exec.Cmd{}
528 if r.tokens == nil {
529 r.tokens = make(map[*exec.Cmd]bazelCommand)
530 }
531 r.tokens[cmd] = command
532 return cmd
533}
534
535func (r *mockBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
536 if command, ok := r.tokens[bazelCmd]; ok {
537 return r.bazelCommandResults[command], "", nil
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400538 }
539 return "", "", nil
540}
541
542type builtinBazelRunner struct{}
543
Chris Parsons808d84c2021-03-09 20:43:32 -0500544// Issues the given bazel command with given build label and additional flags.
545// Returns (stdout, stderr, error). The first and second return values are strings
546// containing the stdout and stderr of the run command, and an error is returned if
547// the invocation returned an error code.
Jason Wu52cd1942022-09-08 15:37:57 +0000548func (r *builtinBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
549 stderr := &bytes.Buffer{}
550 bazelCmd.Stderr = stderr
551 if output, err := bazelCmd.Output(); err != nil {
552 return "", string(stderr.Bytes()),
Sasha Smundak0e87b182022-12-01 11:46:11 -0800553 fmt.Errorf("bazel command failed: %s\n---command---\n%s\n---env---\n%s\n---stderr---\n%s---",
554 err, bazelCmd, strings.Join(bazelCmd.Env, "\n"), stderr)
Jason Wu52cd1942022-09-08 15:37:57 +0000555 } else {
556 return string(output), string(stderr.Bytes()), nil
557 }
558}
559
560func (r *builtinBazelRunner) createBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
561 extraFlags ...string) *exec.Cmd {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000562 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000563 "--output_base=" + absolutePath(paths.outputBase),
564 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700565 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700566 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700567 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400568
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700569 // Set default platforms to canonicalized values for mixed builds requests.
570 // If these are set in the bazelrc, they will have values that are
571 // non-canonicalized to @sourceroot labels, and thus be invalid when
572 // referenced from the buildroot.
573 //
574 // The actual platform values here may be overridden by configuration
575 // transitions from the buildroot.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700576 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Cole Faustb85d1a12022-11-08 18:14:01 -0800577
578 // We don't need to set --host_platforms because it's set in bazelrc files
579 // that the bazel shell script wrapper passes
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700580
581 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
582 "--experimental_repository_disable_download",
583
584 // Suppress noise
585 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500586 "--noshow_progress",
587 "--norun_validations",
588 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400589 cmdFlags = append(cmdFlags, extraFlags...)
590
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400591 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200592 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700593 extraEnv := []string{
594 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200595 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700596 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700597 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000598 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700599 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500600 // Disables local host detection of gcc; toolchain information is defined
601 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700602 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
603 }
604 bazelCmd.Env = append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400605
Jason Wu52cd1942022-09-08 15:37:57 +0000606 return bazelCmd
607}
608
609func printableCqueryCommand(bazelCmd *exec.Cmd) string {
610 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(bazelCmd.Args, "\" \"") + "\""
611 return outputString
612
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400613}
614
Sasha Smundak39a301c2022-12-29 17:11:49 -0800615func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500616 // TODO(cparsons): Define configuration transitions programmatically based
617 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400618 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500619#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400620# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500621#####################################################
622
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400623def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800624 if attr.os == "android" and attr.arch == "target":
625 target = "{PRODUCT}-{VARIANT}"
626 else:
627 target = "{PRODUCT}-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500628 return {
Cole Faustb85d1a12022-11-08 18:14:01 -0800629 "//command_line_option:platforms": "@soong_injection//product_config_platforms/products/{PRODUCT}-{VARIANT}:%s" % target,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500630 }
631
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400632_config_node_transition = transition(
633 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500634 inputs = [],
635 outputs = [
636 "//command_line_option:platforms",
637 ],
638)
639
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400640def _passthrough_rule_impl(ctx):
641 return [DefaultInfo(files = depset(ctx.files.deps))]
642
643config_node = rule(
644 implementation = _passthrough_rule_impl,
645 attrs = {
646 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400647 "os" : attr.string(mandatory = True),
648 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400649 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
650 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500651)
652
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400653
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500654# Rule representing the root of the build, to depend on all Bazel targets that
655# are required for the build. Building this target will build the entire Bazel
656# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400657mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400658 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500659 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400660 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500661 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400662)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500663
664def _phony_root_impl(ctx):
665 return []
666
667# Rule to depend on other targets but build nothing.
668# This is useful as follows: building a target of this rule will generate
669# symlink forests for all dependencies of the target, without executing any
670# actions of the build.
671phony_root = rule(
672 implementation = _phony_root_impl,
673 attrs = {"deps" : attr.label_list()},
674)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400675`
Cole Faustb85d1a12022-11-08 18:14:01 -0800676
677 productReplacer := strings.NewReplacer(
678 "{PRODUCT}", context.targetProduct,
679 "{VARIANT}", context.targetBuildVariant)
680
681 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400682}
683
Sasha Smundak39a301c2022-12-29 17:11:49 -0800684func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500685 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
686 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400687 formatString := `
688# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400689load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
690
691%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400692
693mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400694 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000695 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400696)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500697
698phony_root(name = "phonyroot",
699 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000700 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500701)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400702`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400703 configNodeFormatString := `
704config_node(name = "%s",
705 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400706 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400707 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000708 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400709)
710`
711
712 configNodesSection := ""
713
Chris Parsons787fb362021-10-14 18:43:51 -0400714 labelsByConfig := map[string][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400715 for val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200716 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400717 configString := getConfigString(val)
718 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400719 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400720
Jingwen Chen1e347862021-09-02 12:11:49 +0000721 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400722 for configString, labels := range labelsByConfig {
723 configTokens := strings.Split(configString, "|")
724 if len(configTokens) != 2 {
725 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000726 }
Chris Parsons787fb362021-10-14 18:43:51 -0400727 archString := configTokens[0]
728 osString := configTokens[1]
729 targetString := fmt.Sprintf("%s_%s", osString, archString)
730 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
731 labelsString := strings.Join(labels, ",\n ")
732 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400733 }
734
Jingwen Chen1e347862021-09-02 12:11:49 +0000735 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400736}
737
Chris Parsons944e7d02021-03-11 11:08:46 -0500738func indent(original string) string {
739 result := ""
740 for _, line := range strings.Split(original, "\n") {
741 result += " " + line + "\n"
742 }
743 return result
744}
745
Chris Parsons808d84c2021-03-09 20:43:32 -0500746// Returns the file contents of the buildroot.cquery file that should be used for the cquery
747// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800748// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500749// and grouped by their request type. The data retrieved for each label depends on its
750// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800751func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400752 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400753 for val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500754 cqueryId := getCqueryId(val)
755 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
756 requestTypeToCqueryIdEntries[val.requestType] =
757 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
758 }
759 labelRegistrationMapSection := ""
760 functionDefSection := ""
761 mainSwitchSection := ""
762
763 mapDeclarationFormatString := `
764%s = {
765 %s
766}
767`
768 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800769def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500770%s
771`
772 mainSwitchSectionFormatString := `
773 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800774 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500775`
776
Usta Shrestha0b52d832022-02-04 21:37:39 -0500777 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500778 labelMapName := requestType.Name() + "_Labels"
779 functionName := requestType.Name() + "_Fn"
780 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
781 labelMapName,
782 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
783 functionDefSection += fmt.Sprintf(functionDefFormatString,
784 functionName,
785 indent(requestType.StarlarkFunctionBody()))
786 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
787 labelMapName, functionName)
788 }
789
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400790 formatString := `
791# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400792
Usta Shrestha79fccef2022-09-02 18:37:40 -0400793# a drop-in replacement for json.encode(), not available in cquery environment
794# TODO(cparsons): bring json module in and remove this function
795def json_encode(input):
796 # Avoiding recursion by limiting
797 # - a dict to contain anything except a dict
798 # - a list to contain only primitives
799 def encode_primitive(p):
800 t = type(p)
801 if t == "string" or t == "int":
802 return repr(p)
Cole Faustb85d1a12022-11-08 18:14:01 -0800803 fail("unsupported value '%s' of type '%s'" % (p, type(p)))
Usta Shrestha79fccef2022-09-02 18:37:40 -0400804
805 def encode_list(list):
Cole Faustb85d1a12022-11-08 18:14:01 -0800806 return "[%s]" % ", ".join([encode_primitive(item) for item in list])
Usta Shrestha79fccef2022-09-02 18:37:40 -0400807
808 def encode_list_or_primitive(v):
809 return encode_list(v) if type(v) == "list" else encode_primitive(v)
810
811 if type(input) == "dict":
812 # TODO(juu): the result is read line by line so can't use '\n' yet
Cole Faustb85d1a12022-11-08 18:14:01 -0800813 kv_pairs = [("%s: %s" % (encode_primitive(k), encode_list_or_primitive(v))) for (k, v) in input.items()]
814 return "{ %s }" % ", ".join(kv_pairs)
Usta Shrestha79fccef2022-09-02 18:37:40 -0400815 else:
816 return encode_list_or_primitive(input)
817
Cole Faustb85d1a12022-11-08 18:14:01 -0800818{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500819
Cole Faustb85d1a12022-11-08 18:14:01 -0800820{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500821
822def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400823 # TODO(b/199363072): filegroups and file targets aren't associated with any
824 # specific platform architecture in mixed builds. This is consistent with how
825 # Soong treats filegroups, but it may not be the case with manually-written
826 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500827 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000828 if buildoptions == None:
829 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400830 # any specific platform architecture in mixed builds, so use the host.
831 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -0800832 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500833 if len(platforms) != 1:
834 # An individual configured target should have only one platform architecture.
835 # Note that it's fine for there to be multiple architectures for the same label,
836 # but each is its own configured target.
837 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -0800838 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -0500839 if platform_name == "host":
840 return "HOST"
Cole Faustb85d1a12022-11-08 18:14:01 -0800841 if not platform_name.startswith("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}"):
842 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))
843 platform_name = platform_name.removeprefix("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}").removeprefix("_")
844 if not platform_name:
845 return "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400846 elif platform_name.startswith("android_"):
Cole Faustb85d1a12022-11-08 18:14:01 -0800847 return platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400848 elif platform_name.startswith("linux_"):
Cole Faustb85d1a12022-11-08 18:14:01 -0800849 return platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400850 else:
Cole Faustb85d1a12022-11-08 18:14:01 -0800851 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 -0500852
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400853def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500854 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500855
Chris Parsons86dc2c22022-09-28 14:58:41 -0400856 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
857 if id_string.startswith("//"):
858 id_string = "@" + id_string
859
Cole Faustb85d1a12022-11-08 18:14:01 -0800860 {MAIN_SWITCH_SECTION}
861
Chris Parsons944e7d02021-03-11 11:08:46 -0500862 # This target was not requested via cquery, and thus must be a dependency
863 # of a requested target.
864 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400865`
Cole Faustb85d1a12022-11-08 18:14:01 -0800866 replacer := strings.NewReplacer(
867 "{TARGET_PRODUCT}", context.targetProduct,
868 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
869 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
870 "{FUNCTION_DEF_SECTION}", functionDefSection,
871 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400872
Cole Faustb85d1a12022-11-08 18:14:01 -0800873 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400874}
875
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200876// Returns a path containing build-related metadata required for interfacing
877// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400878func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200879 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500880}
881
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200882// Returns the path where the contents of the @soong_injection repository live.
883// It is used by Soong to tell Bazel things it cannot over the command line.
884func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200885 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200886}
887
888// Returns the path of the synthetic Bazel workspace that contains a symlink
889// forest composed the whole source tree and BUILD files generated by bp2build.
890func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200891 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200892}
893
Jingwen Chen8c523582021-06-01 11:19:53 +0000894// Returns the path to the top level out dir ($OUT_DIR).
895func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200896 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000897}
898
Sasha Smundak4975c822022-11-16 15:28:18 -0800899const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
900
901var (
902 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
903 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
904 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
905)
906
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400907// Issues commands to Bazel to receive results for all cquery requests
908// queued in the BazelContext.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800909func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -0800910 if ctx != nil {
911 ctx.EventHandler.Begin("bazel")
912 defer ctx.EventHandler.End("bazel")
913 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400914
Sasha Smundak4975c822022-11-16 15:28:18 -0800915 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
916 if err := os.MkdirAll(metricsDir, 0777); err != nil {
917 return err
918 }
919 }
920 context.results = make(map[cqueryKey]string)
921 if err := context.runCquery(ctx); err != nil {
922 return err
923 }
924 if err := context.runAquery(config, ctx); err != nil {
925 return err
926 }
927 if err := context.generateBazelSymlinks(ctx); err != nil {
928 return err
929 }
930
931 // Clear requests.
932 context.requests = map[cqueryKey]bool{}
933 return nil
934}
935
Sasha Smundak39a301c2022-12-29 17:11:49 -0800936func (context *mixedBuildBazelContext) runCquery(ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -0800937 if ctx != nil {
938 ctx.EventHandler.Begin("cquery")
939 defer ctx.EventHandler.End("cquery")
940 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200941 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200942 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
943 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
944 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -0500945 if err != nil {
946 return err
947 }
948 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800949 if err := os.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200950 return err
951 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800952 if err := os.WriteFile(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400953 return err
954 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800955 if err := os.WriteFile(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400956 return err
957 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200958 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Sasha Smundak0e87b182022-12-01 11:46:11 -0800959 if err := os.WriteFile(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400960 return err
961 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000962
Jason Wu52cd1942022-09-08 15:37:57 +0000963 cqueryCommandWithFlag := context.createBazelCommand(context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700964 "--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
Wei Licbd181c2022-11-16 08:59:23 -0800965 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCommandWithFlag)
966 if cqueryErr != nil {
967 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -0500968 }
Jason Wu52cd1942022-09-08 15:37:57 +0000969 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", printableCqueryCommand(cqueryCommandWithFlag))
Sasha Smundak0e87b182022-12-01 11:46:11 -0800970 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400971 return err
972 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400973 cqueryResults := map[string]string{}
974 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
975 if strings.Contains(outputLine, ">>") {
976 splitLine := strings.SplitN(outputLine, ">>", 2)
977 cqueryResults[splitLine[0]] = splitLine[1]
978 }
979 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500980 for val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500981 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -0500982 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400983 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500984 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -0800985 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400986 }
987 }
Sasha Smundak4975c822022-11-16 15:28:18 -0800988 return nil
989}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400990
Sasha Smundak39a301c2022-12-29 17:11:49 -0800991func (context *mixedBuildBazelContext) runAquery(config Config, ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -0800992 if ctx != nil {
993 ctx.EventHandler.Begin("aquery")
994 defer ctx.EventHandler.End("aquery")
995 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500996 // Issue an aquery command to retrieve action information about the bazel build tree.
997 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700998 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
999 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001000 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001001 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001002 extraFlags = append(extraFlags, "--collect_code_coverage")
1003 paths := make([]string, 0, 2)
1004 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001005 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001006 // TODO(b/259404593) convert path wildcard to regex values
1007 if p[i] == "*" {
1008 p[i] = ".*"
1009 }
1010 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001011 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1012 }
1013 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1014 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1015 }
1016 if len(paths) > 0 {
1017 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001018 }
1019 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001020 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
1021 extraFlags...))
1022 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001023 return err
1024 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001025 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
1026 return err
1027}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001028
Sasha Smundak39a301c2022-12-29 17:11:49 -08001029func (context *mixedBuildBazelContext) generateBazelSymlinks(ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -08001030 if ctx != nil {
1031 ctx.EventHandler.Begin("symlinks")
1032 defer ctx.EventHandler.End("symlinks")
1033 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001034 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1035 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1036 // but some of symlinks may be required to resolve source dependencies of the build.
Sasha Smundak4975c822022-11-16 15:28:18 -08001037 _, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd))
1038 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001039}
Chris Parsonsa798d962020-10-12 23:44:08 -04001040
Sasha Smundak39a301c2022-12-29 17:11:49 -08001041func (context *mixedBuildBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001042 return context.buildStatements
1043}
1044
Sasha Smundak39a301c2022-12-29 17:11:49 -08001045func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001046 return context.depsets
1047}
1048
Sasha Smundak39a301c2022-12-29 17:11:49 -08001049func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001050 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001051}
1052
Chris Parsonsa798d962020-10-12 23:44:08 -04001053// Singleton used for registering BUILD file ninja dependencies (needed
1054// for correctness of builds which use Bazel.
1055func BazelSingleton() Singleton {
1056 return &bazelSingleton{}
1057}
1058
1059type bazelSingleton struct{}
1060
1061func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001062 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001063 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001064 return
1065 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001066
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001067 // Add ninja file dependencies for files which all bazel invocations require.
1068 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001069 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001070 ctx.AddNinjaFileDeps(bazelBuildList)
1071
Sasha Smundak0e87b182022-12-01 11:46:11 -08001072 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001073 if err != nil {
1074 ctx.Errorf(err.Error())
1075 }
1076 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1077 for _, file := range files {
1078 ctx.AddNinjaFileDeps(file)
1079 }
1080
Chris Parsons1a7aca02022-04-25 22:35:15 -04001081 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1082 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001083 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001084 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1085 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001086 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1087 }
1088 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001089 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1090 if artifactPath == "bazel-out/volatile-status.txt" {
1091 // See https://bazel.build/docs/user-manual#workspace-status
1092 orderOnlies = append(orderOnlies, pathInBazelOut)
1093 } else {
1094 outputs = append(outputs, pathInBazelOut)
1095 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001096 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001097 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001098 ctx.Build(pctx, BuildParams{
1099 Rule: blueprint.Phony,
1100 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1101 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001102 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001103 })
1104 }
1105
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001106 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1107 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001108 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -07001109 if len(buildStatement.Command) > 0 {
1110 rule := NewRuleBuilder(pctx, ctx)
1111 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1112 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1113 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1114 continue
1115 }
1116 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1117 // and thus require special treatment. If BuildStatement were an interface implementing
1118 // buildRule(ctx) function, the code here would just call it.
1119 // Unfortunately, the BuildStatement is defined in
1120 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1121 // because this would cause circular dependency. So, until we move aquery processing
1122 // to the 'android' package, we need to handle special cases here.
1123 if buildStatement.Mnemonic == "FileWrite" || buildStatement.Mnemonic == "SourceSymlinkManifest" {
Cole Fausta7347492022-12-16 10:56:24 -08001124 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1125 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001126 } else if buildStatement.Mnemonic == "SymlinkTree" {
1127 // build-runfiles arguments are the manifest file and the target directory
1128 // where it creates the symlink tree according to this manifest (and then
1129 // writes the MANIFEST file to it).
1130 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1131 outManifestPath := outManifest.String()
1132 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1133 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1134 }
1135 outDir := filepath.Dir(outManifestPath)
1136 ctx.Build(pctx, BuildParams{
1137 Rule: buildRunfilesRule,
1138 Output: outManifest,
1139 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1140 Description: "symlink tree for " + outDir,
1141 Args: map[string]string{
1142 "outDir": outDir,
1143 },
1144 })
Sasha Smundak1da064c2022-06-08 16:36:16 -07001145 } else {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001146 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001147 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001148 }
1149}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001150
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001151// Register bazel-owned build statements (obtained from the aquery invocation).
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001152func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001153 // executionRoot is the action cwd.
1154 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1155
1156 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1157 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001158 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001159 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001160 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001161 }
1162 cmd.Text("&&")
1163 }
1164
1165 for _, pair := range buildStatement.Env {
1166 // Set per-action env variables, if any.
1167 cmd.Flag(pair.Key + "=" + pair.Value)
1168 }
1169
1170 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001171 if len(buildStatement.Command) > 16*1024 {
1172 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1173 WriteFileRule(ctx, commandFile, buildStatement.Command)
1174
1175 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1176 } else {
1177 cmd.Text(buildStatement.Command)
1178 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001179
1180 for _, outputPath := range buildStatement.OutputPaths {
1181 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1182 }
1183 for _, inputPath := range buildStatement.InputPaths {
1184 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1185 }
1186 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1187 otherDepsetName := bazelDepsetName(inputDepsetHash)
1188 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1189 }
1190
1191 if depfile := buildStatement.Depfile; depfile != nil {
1192 // The paths in depfile are relative to `executionRoot`.
1193 // Hence, they need to be corrected by replacing "bazel-out"
1194 // with the full `bazelOutDir`.
1195 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1196 // would be deemed missing.
1197 // (Note: The regexp uses a capture group because the version of sed
1198 // does not support a look-behind pattern.)
1199 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1200 bazelOutDir, *depfile)
1201 cmd.Text(replacement)
1202 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1203 }
1204
1205 for _, symlinkPath := range buildStatement.SymlinkPaths {
1206 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1207 }
1208}
1209
Chris Parsons8d6e4332021-02-22 16:13:50 -05001210func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001211 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001212}
1213
Chris Parsons787fb362021-10-14 18:43:51 -04001214func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001215 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001216 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001217 if key.configKey.osType.Class == Device {
1218 // For the generic Android, the expected result is "target|android", which
1219 // corresponds to the product_variable_config named "android_target" in
1220 // build/bazel/platforms/BUILD.bazel.
1221 arch = "target"
1222 } else {
1223 // Use host platform, which is currently hardcoded to be x86_64.
1224 arch = "x86_64"
1225 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001226 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001227 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001228 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001229 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001230 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001231 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001232 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -04001233}
1234
Chris Parsonsf874e462022-05-10 13:50:12 -04001235func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001236 return configKey{
1237 // use string because Arch is not a valid key in go
1238 arch: ctx.Arch().String(),
1239 osType: ctx.Os(),
1240 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001241}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001242
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001243func bazelDepsetName(contentHash string) string {
1244 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001245}