blob: 7ba0023a51aaec5bb860dbbb477fc27dcebdb333 [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
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500186 paths *bazelPaths
187 // cquery requests that have not yet been issued to Bazel. This list is maintained
188 // in a sorted state, and is guaranteed to have no duplicates.
189 requests []cqueryKey
190 requestMutex sync.Mutex // requests can be written in parallel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400191
192 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500193
194 // Build statements which should get registered to reflect Bazel's outputs.
195 buildStatements []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400196
197 // Depsets which should be used for Bazel's build statements.
198 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400199
200 // Per-module allowlist/denylist functionality to control whether analysis of
201 // modules are handled by Bazel. For modules which do not have a Bazel definition
202 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
203 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
204 // Per-module denylist to opt modules out of bazel handling.
205 bazelDisabledModules map[string]bool
206 // Per-module allowlist to opt modules in to bazel handling.
207 bazelEnabledModules map[string]bool
208 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
209 modulesDefaultToBazel bool
Cole Faustb85d1a12022-11-08 18:14:01 -0800210
211 targetProduct string
212 targetBuildVariant string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400213}
214
Sasha Smundak39a301c2022-12-29 17:11:49 -0800215var _ BazelContext = &mixedBuildBazelContext{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400216
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 Smundak0e87b182022-12-01 11:46:11 -0800262func (m MockBazelContext) InvokeBazel(_ Config, _ *Context) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400263 panic("unimplemented")
264}
265
Sasha Smundak39a301c2022-12-29 17:11:49 -0800266func (m MockBazelContext) IsModuleNameAllowed(_ 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
Sasha Smundak39a301c2022-12-29 17:11:49 -0800282func (bazelCtx *mixedBuildBazelContext) 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()
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500286
287 // Insert key into requests, maintaining the sort, and only if it's not duplicate.
288 keyString := key.String()
289 foundEqual := false
290 notLessThanKeyString := func(i int) bool {
291 s := bazelCtx.requests[i].String()
292 v := strings.Compare(s, keyString)
293 if v == 0 {
294 foundEqual = true
295 }
296 return v >= 0
297 }
298 targetIndex := sort.Search(len(bazelCtx.requests), notLessThanKeyString)
299 if foundEqual {
300 return
301 }
302
303 if targetIndex == len(bazelCtx.requests) {
304 bazelCtx.requests = append(bazelCtx.requests, key)
305 } else {
306 bazelCtx.requests = append(bazelCtx.requests[:targetIndex+1], bazelCtx.requests[targetIndex:]...)
307 bazelCtx.requests[targetIndex] = key
308 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400309}
310
Sasha Smundak39a301c2022-12-29 17:11:49 -0800311func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400312 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400313 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500314 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400315
Chris Parsonsf874e462022-05-10 13:50:12 -0400316 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400317 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400318 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400319}
320
Sasha Smundak39a301c2022-12-29 17:11:49 -0800321func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400322 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400323 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000324 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400325 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000326 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400327 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 +0000328}
329
Sasha Smundak39a301c2022-12-29 17:11:49 -0800330func (bazelCtx *mixedBuildBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400331 key := makeCqueryKey(label, cquery.GetPythonBinary, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400332 if rawString, ok := bazelCtx.results[key]; ok {
333 bazelOutput := strings.TrimSpace(rawString)
334 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
335 }
336 return "", fmt.Errorf("no bazel response found for %v", key)
337}
338
Sasha Smundak39a301c2022-12-29 17:11:49 -0800339func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400340 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700341 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500342 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700343 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400344 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700345}
346
Sasha Smundak39a301c2022-12-29 17:11:49 -0800347func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700348 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
349 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500350 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700351 }
352 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
353}
354
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700355func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500356 panic("unimplemented")
357}
358
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700359func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500360 panic("unimplemented")
361}
362
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700363func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400364 panic("unimplemented")
365}
366
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700367func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000368 panic("unimplemented")
369}
370
Liz Kammerbe6a7122022-11-04 16:05:11 -0400371func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700372 panic("unimplemented")
373}
374
Sasha Smundakedd16662022-10-07 14:44:50 -0700375func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
376 //TODO implement me
377 panic("implement me")
378}
379
Sasha Smundak0e87b182022-12-01 11:46:11 -0800380func (n noopBazelContext) InvokeBazel(_ Config, _ *Context) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400381 panic("unimplemented")
382}
383
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500384func (m noopBazelContext) OutputBase() string {
385 return ""
386}
387
Sasha Smundak39a301c2022-12-29 17:11:49 -0800388func (n noopBazelContext) IsModuleNameAllowed(_ string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400389 return false
390}
391
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500392func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
393 return []bazel.BuildStatement{}
394}
395
Chris Parsons1a7aca02022-04-25 22:35:15 -0400396func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
397 return []bazel.AqueryDepset{}
398}
399
Cole Faust705968d2022-12-14 11:32:05 -0800400func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400401 disabledModules := map[string]bool{}
402 enabledModules := map[string]bool{}
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800403 addToStringSet := func(set map[string]bool, items []string) {
404 for _, item := range items {
405 set[item] = true
406 }
407 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400408
Cole Faust705968d2022-12-14 11:32:05 -0800409 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400410 case BazelProdMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800411 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800412 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000413 enabledModules[enabledAdHocModule] = true
414 }
MarkDacekb78465d2022-10-18 20:10:16 +0000415 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400416 // Staging mode includes all prod modules plus all staging modules.
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800417 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
418 addToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800419 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000420 enabledModules[enabledAdHocModule] = true
421 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400422 case BazelDevMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800423 addToStringSet(disabledModules, allowlists.MixedBuildsDisabledList)
Chris Parsonsef615e52022-08-18 22:04:11 -0400424 default:
Cole Faust705968d2022-12-14 11:32:05 -0800425 panic("Expected BazelProdMode, BazelStagingMode, or BazelDevMode")
426 }
427 return enabledModules, disabledModules
428}
429
430func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
431 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
432 enabledList := make([]string, 0, len(enabledModules))
433 for module := range enabledModules {
434 if !disabledModules[module] {
435 enabledList = append(enabledList, module)
436 }
437 }
438 sort.Strings(enabledList)
439 return enabledList
440}
441
442func NewBazelContext(c *config) (BazelContext, error) {
443 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode && c.BuildMode != BazelDevMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400444 return noopBazelContext{}, nil
445 }
446
Cole Faust705968d2022-12-14 11:32:05 -0800447 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
448
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800449 paths := bazelPaths{
450 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400451 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800452 var missing []string
453 vars := []struct {
454 name string
455 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000456
457 // True if the environment variable needs to be tracked so that changes to the variable
458 // cause the ninja file to be regenerated, false otherwise. False should only be set for
459 // environment variables that have no effect on the generated ninja file.
460 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800461 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000462 {"BAZEL_HOME", &paths.homeDir, true},
463 {"BAZEL_PATH", &paths.bazelPath, true},
464 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
465 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
466 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
467 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800468 }
469 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000470 if v.track {
471 if s := c.Getenv(v.name); len(s) > 1 {
472 *v.ptr = s
473 continue
474 }
475 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800476 *v.ptr = s
477 } else {
478 missing = append(missing, v.name)
479 }
480 }
481 if len(missing) > 0 {
482 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
483 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800484
485 targetBuildVariant := "user"
486 if c.Eng() {
487 targetBuildVariant = "eng"
488 } else if c.Debuggable() {
489 targetBuildVariant = "userdebug"
490 }
491 targetProduct := "unknown"
492 if c.HasDeviceProduct() {
493 targetProduct = c.DeviceProduct()
494 }
495
Sasha Smundak39a301c2022-12-29 17:11:49 -0800496 return &mixedBuildBazelContext{
Chris Parsonsad876012022-08-20 14:48:32 -0400497 bazelRunner: &builtinBazelRunner{},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800498 paths: &paths,
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800499 modulesDefaultToBazel: c.BuildMode == BazelDevMode,
Chris Parsonsef615e52022-08-18 22:04:11 -0400500 bazelEnabledModules: enabledModules,
Chris Parsonsad876012022-08-20 14:48:32 -0400501 bazelDisabledModules: disabledModules,
Cole Faustb85d1a12022-11-08 18:14:01 -0800502 targetProduct: targetProduct,
503 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400504 }, nil
505}
506
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400507func (p *bazelPaths) BazelMetricsDir() string {
508 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000509}
510
Sasha Smundak39a301c2022-12-29 17:11:49 -0800511func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400512 if context.bazelDisabledModules[moduleName] {
513 return false
514 }
515 if context.bazelEnabledModules[moduleName] {
516 return true
517 }
518 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400519}
520
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400521func pwdPrefix() string {
522 // Darwin doesn't have /proc
523 if runtime.GOOS != "darwin" {
524 return "PWD=/proc/self/cwd"
525 }
526 return ""
527}
528
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400529type bazelCommand struct {
530 command string
531 // query or label
532 expression string
533}
534
535type mockBazelRunner struct {
536 bazelCommandResults map[bazelCommand]string
Jason Wu52cd1942022-09-08 15:37:57 +0000537 // use *exec.Cmd as a key to get the bazelCommand, the map will be used in issueBazelCommand()
538 // Register createBazelCommand() invocations. Later, an
539 // issueBazelCommand() invocation can be mapped to the *exec.Cmd instance
540 // and then to the expected result via bazelCommandResults
541 tokens map[*exec.Cmd]bazelCommand
542 commands []bazelCommand
543 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400544}
545
Sasha Smundak0e87b182022-12-01 11:46:11 -0800546func (r *mockBazelRunner) createBazelCommand(_ *bazelPaths, _ bazel.RunName,
Jason Wu52cd1942022-09-08 15:37:57 +0000547 command bazelCommand, extraFlags ...string) *exec.Cmd {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400548 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700549 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Jason Wu52cd1942022-09-08 15:37:57 +0000550 cmd := &exec.Cmd{}
551 if r.tokens == nil {
552 r.tokens = make(map[*exec.Cmd]bazelCommand)
553 }
554 r.tokens[cmd] = command
555 return cmd
556}
557
558func (r *mockBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
559 if command, ok := r.tokens[bazelCmd]; ok {
560 return r.bazelCommandResults[command], "", nil
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400561 }
562 return "", "", nil
563}
564
565type builtinBazelRunner struct{}
566
Chris Parsons808d84c2021-03-09 20:43:32 -0500567// Issues the given bazel command with given build label and additional flags.
568// Returns (stdout, stderr, error). The first and second return values are strings
569// containing the stdout and stderr of the run command, and an error is returned if
570// the invocation returned an error code.
Jason Wu52cd1942022-09-08 15:37:57 +0000571func (r *builtinBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
572 stderr := &bytes.Buffer{}
573 bazelCmd.Stderr = stderr
574 if output, err := bazelCmd.Output(); err != nil {
575 return "", string(stderr.Bytes()),
Sasha Smundak0e87b182022-12-01 11:46:11 -0800576 fmt.Errorf("bazel command failed: %s\n---command---\n%s\n---env---\n%s\n---stderr---\n%s---",
577 err, bazelCmd, strings.Join(bazelCmd.Env, "\n"), stderr)
Jason Wu52cd1942022-09-08 15:37:57 +0000578 } else {
579 return string(output), string(stderr.Bytes()), nil
580 }
581}
582
583func (r *builtinBazelRunner) createBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
584 extraFlags ...string) *exec.Cmd {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000585 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000586 "--output_base=" + absolutePath(paths.outputBase),
587 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700588 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700589 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700590 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400591
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700592 // Set default platforms to canonicalized values for mixed builds requests.
593 // If these are set in the bazelrc, they will have values that are
594 // non-canonicalized to @sourceroot labels, and thus be invalid when
595 // referenced from the buildroot.
596 //
597 // The actual platform values here may be overridden by configuration
598 // transitions from the buildroot.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700599 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Cole Faustb85d1a12022-11-08 18:14:01 -0800600
601 // We don't need to set --host_platforms because it's set in bazelrc files
602 // that the bazel shell script wrapper passes
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700603
604 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
605 "--experimental_repository_disable_download",
606
607 // Suppress noise
608 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500609 "--noshow_progress",
610 "--norun_validations",
611 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400612 cmdFlags = append(cmdFlags, extraFlags...)
613
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400614 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200615 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700616 extraEnv := []string{
617 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200618 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700619 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700620 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000621 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700622 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500623 // Disables local host detection of gcc; toolchain information is defined
624 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700625 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
626 }
627 bazelCmd.Env = append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400628
Jason Wu52cd1942022-09-08 15:37:57 +0000629 return bazelCmd
630}
631
632func printableCqueryCommand(bazelCmd *exec.Cmd) string {
633 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(bazelCmd.Args, "\" \"") + "\""
634 return outputString
635
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400636}
637
Sasha Smundak39a301c2022-12-29 17:11:49 -0800638func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500639 // TODO(cparsons): Define configuration transitions programmatically based
640 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400641 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500642#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400643# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500644#####################################################
645
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400646def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800647 if attr.os == "android" and attr.arch == "target":
648 target = "{PRODUCT}-{VARIANT}"
649 else:
650 target = "{PRODUCT}-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500651 return {
Cole Faustb85d1a12022-11-08 18:14:01 -0800652 "//command_line_option:platforms": "@soong_injection//product_config_platforms/products/{PRODUCT}-{VARIANT}:%s" % target,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500653 }
654
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400655_config_node_transition = transition(
656 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500657 inputs = [],
658 outputs = [
659 "//command_line_option:platforms",
660 ],
661)
662
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400663def _passthrough_rule_impl(ctx):
664 return [DefaultInfo(files = depset(ctx.files.deps))]
665
666config_node = rule(
667 implementation = _passthrough_rule_impl,
668 attrs = {
669 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400670 "os" : attr.string(mandatory = True),
671 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400672 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
673 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500674)
675
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400676
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500677# Rule representing the root of the build, to depend on all Bazel targets that
678# are required for the build. Building this target will build the entire Bazel
679# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400680mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400681 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500682 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400683 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500684 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400685)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500686
687def _phony_root_impl(ctx):
688 return []
689
690# Rule to depend on other targets but build nothing.
691# This is useful as follows: building a target of this rule will generate
692# symlink forests for all dependencies of the target, without executing any
693# actions of the build.
694phony_root = rule(
695 implementation = _phony_root_impl,
696 attrs = {"deps" : attr.label_list()},
697)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400698`
Cole Faustb85d1a12022-11-08 18:14:01 -0800699
700 productReplacer := strings.NewReplacer(
701 "{PRODUCT}", context.targetProduct,
702 "{VARIANT}", context.targetBuildVariant)
703
704 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400705}
706
Sasha Smundak39a301c2022-12-29 17:11:49 -0800707func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500708 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
709 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400710 formatString := `
711# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400712load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
713
714%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400715
716mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400717 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000718 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400719)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500720
721phony_root(name = "phonyroot",
722 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000723 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500724)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400725`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400726 configNodeFormatString := `
727config_node(name = "%s",
728 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400729 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400730 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000731 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400732)
733`
734
735 configNodesSection := ""
736
Chris Parsons787fb362021-10-14 18:43:51 -0400737 labelsByConfig := map[string][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500738
739 for _, val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200740 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400741 configString := getConfigString(val)
742 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400743 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400744
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500745 // Configs need to be sorted to maintain determinism of the BUILD file.
746 sortedConfigs := make([]string, 0, len(labelsByConfig))
747 for val := range labelsByConfig {
748 sortedConfigs = append(sortedConfigs, val)
749 }
750 sort.Slice(sortedConfigs, func(i, j int) bool { return sortedConfigs[i] < sortedConfigs[j] })
751
Jingwen Chen1e347862021-09-02 12:11:49 +0000752 allLabels := []string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500753 for _, configString := range sortedConfigs {
754 labels := labelsByConfig[configString]
Chris Parsons787fb362021-10-14 18:43:51 -0400755 configTokens := strings.Split(configString, "|")
756 if len(configTokens) != 2 {
757 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000758 }
Chris Parsons787fb362021-10-14 18:43:51 -0400759 archString := configTokens[0]
760 osString := configTokens[1]
761 targetString := fmt.Sprintf("%s_%s", osString, archString)
762 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
763 labelsString := strings.Join(labels, ",\n ")
764 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400765 }
766
Jingwen Chen1e347862021-09-02 12:11:49 +0000767 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400768}
769
Chris Parsons944e7d02021-03-11 11:08:46 -0500770func indent(original string) string {
771 result := ""
772 for _, line := range strings.Split(original, "\n") {
773 result += " " + line + "\n"
774 }
775 return result
776}
777
Chris Parsons808d84c2021-03-09 20:43:32 -0500778// Returns the file contents of the buildroot.cquery file that should be used for the cquery
779// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800780// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500781// and grouped by their request type. The data retrieved for each label depends on its
782// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800783func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400784 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500785 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500786 cqueryId := getCqueryId(val)
787 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
788 requestTypeToCqueryIdEntries[val.requestType] =
789 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
790 }
791 labelRegistrationMapSection := ""
792 functionDefSection := ""
793 mainSwitchSection := ""
794
795 mapDeclarationFormatString := `
796%s = {
797 %s
798}
799`
800 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800801def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500802%s
803`
804 mainSwitchSectionFormatString := `
805 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800806 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500807`
808
Usta Shrestha0b52d832022-02-04 21:37:39 -0500809 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500810 labelMapName := requestType.Name() + "_Labels"
811 functionName := requestType.Name() + "_Fn"
812 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
813 labelMapName,
814 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
815 functionDefSection += fmt.Sprintf(functionDefFormatString,
816 functionName,
817 indent(requestType.StarlarkFunctionBody()))
818 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
819 labelMapName, functionName)
820 }
821
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400822 formatString := `
823# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400824
Usta Shrestha79fccef2022-09-02 18:37:40 -0400825# a drop-in replacement for json.encode(), not available in cquery environment
826# TODO(cparsons): bring json module in and remove this function
827def json_encode(input):
828 # Avoiding recursion by limiting
829 # - a dict to contain anything except a dict
830 # - a list to contain only primitives
831 def encode_primitive(p):
832 t = type(p)
833 if t == "string" or t == "int":
834 return repr(p)
Cole Faustb85d1a12022-11-08 18:14:01 -0800835 fail("unsupported value '%s' of type '%s'" % (p, type(p)))
Usta Shrestha79fccef2022-09-02 18:37:40 -0400836
837 def encode_list(list):
Cole Faustb85d1a12022-11-08 18:14:01 -0800838 return "[%s]" % ", ".join([encode_primitive(item) for item in list])
Usta Shrestha79fccef2022-09-02 18:37:40 -0400839
840 def encode_list_or_primitive(v):
841 return encode_list(v) if type(v) == "list" else encode_primitive(v)
842
843 if type(input) == "dict":
844 # TODO(juu): the result is read line by line so can't use '\n' yet
Cole Faustb85d1a12022-11-08 18:14:01 -0800845 kv_pairs = [("%s: %s" % (encode_primitive(k), encode_list_or_primitive(v))) for (k, v) in input.items()]
846 return "{ %s }" % ", ".join(kv_pairs)
Usta Shrestha79fccef2022-09-02 18:37:40 -0400847 else:
848 return encode_list_or_primitive(input)
849
Cole Faustb85d1a12022-11-08 18:14:01 -0800850{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500851
Cole Faustb85d1a12022-11-08 18:14:01 -0800852{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500853
854def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400855 # TODO(b/199363072): filegroups and file targets aren't associated with any
856 # specific platform architecture in mixed builds. This is consistent with how
857 # Soong treats filegroups, but it may not be the case with manually-written
858 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500859 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000860 if buildoptions == None:
861 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400862 # any specific platform architecture in mixed builds, so use the host.
863 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -0800864 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500865 if len(platforms) != 1:
866 # An individual configured target should have only one platform architecture.
867 # Note that it's fine for there to be multiple architectures for the same label,
868 # but each is its own configured target.
869 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -0800870 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -0500871 if platform_name == "host":
872 return "HOST"
Cole Faustb85d1a12022-11-08 18:14:01 -0800873 if not platform_name.startswith("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}"):
874 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))
875 platform_name = platform_name.removeprefix("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}").removeprefix("_")
876 if not platform_name:
877 return "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400878 elif platform_name.startswith("android_"):
Cole Faustb85d1a12022-11-08 18:14:01 -0800879 return platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400880 elif platform_name.startswith("linux_"):
Cole Faustb85d1a12022-11-08 18:14:01 -0800881 return platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400882 else:
Cole Faustb85d1a12022-11-08 18:14:01 -0800883 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 -0500884
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400885def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500886 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500887
Chris Parsons86dc2c22022-09-28 14:58:41 -0400888 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
889 if id_string.startswith("//"):
890 id_string = "@" + id_string
891
Cole Faustb85d1a12022-11-08 18:14:01 -0800892 {MAIN_SWITCH_SECTION}
893
Chris Parsons944e7d02021-03-11 11:08:46 -0500894 # This target was not requested via cquery, and thus must be a dependency
895 # of a requested target.
896 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400897`
Cole Faustb85d1a12022-11-08 18:14:01 -0800898 replacer := strings.NewReplacer(
899 "{TARGET_PRODUCT}", context.targetProduct,
900 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
901 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
902 "{FUNCTION_DEF_SECTION}", functionDefSection,
903 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400904
Cole Faustb85d1a12022-11-08 18:14:01 -0800905 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400906}
907
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200908// Returns a path containing build-related metadata required for interfacing
909// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400910func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200911 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500912}
913
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200914// Returns the path where the contents of the @soong_injection repository live.
915// It is used by Soong to tell Bazel things it cannot over the command line.
916func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200917 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200918}
919
920// Returns the path of the synthetic Bazel workspace that contains a symlink
921// forest composed the whole source tree and BUILD files generated by bp2build.
922func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200923 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200924}
925
Jingwen Chen8c523582021-06-01 11:19:53 +0000926// Returns the path to the top level out dir ($OUT_DIR).
927func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200928 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000929}
930
Sasha Smundak4975c822022-11-16 15:28:18 -0800931const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
932
933var (
934 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
935 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
936 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
937)
938
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400939// Issues commands to Bazel to receive results for all cquery requests
940// queued in the BazelContext.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800941func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -0800942 if ctx != nil {
943 ctx.EventHandler.Begin("bazel")
944 defer ctx.EventHandler.End("bazel")
945 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400946
Sasha Smundak4975c822022-11-16 15:28:18 -0800947 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
948 if err := os.MkdirAll(metricsDir, 0777); err != nil {
949 return err
950 }
951 }
952 context.results = make(map[cqueryKey]string)
953 if err := context.runCquery(ctx); err != nil {
954 return err
955 }
956 if err := context.runAquery(config, ctx); err != nil {
957 return err
958 }
959 if err := context.generateBazelSymlinks(ctx); err != nil {
960 return err
961 }
962
963 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500964 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -0800965 return nil
966}
967
Sasha Smundak39a301c2022-12-29 17:11:49 -0800968func (context *mixedBuildBazelContext) runCquery(ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -0800969 if ctx != nil {
970 ctx.EventHandler.Begin("cquery")
971 defer ctx.EventHandler.End("cquery")
972 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200973 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200974 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
975 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
976 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -0500977 if err != nil {
978 return err
979 }
980 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500981 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200982 return err
983 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500984 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400985 return err
986 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500987 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400988 return err
989 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200990 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500991 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400992 return err
993 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000994
Jason Wu52cd1942022-09-08 15:37:57 +0000995 cqueryCommandWithFlag := context.createBazelCommand(context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700996 "--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
Wei Licbd181c2022-11-16 08:59:23 -0800997 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCommandWithFlag)
998 if cqueryErr != nil {
999 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001000 }
Jason Wu52cd1942022-09-08 15:37:57 +00001001 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", printableCqueryCommand(cqueryCommandWithFlag))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001002 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001003 return err
1004 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001005 cqueryResults := map[string]string{}
1006 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1007 if strings.Contains(outputLine, ">>") {
1008 splitLine := strings.SplitN(outputLine, ">>", 2)
1009 cqueryResults[splitLine[0]] = splitLine[1]
1010 }
1011 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001012 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001013 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001014 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001015 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001016 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001017 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001018 }
1019 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001020 return nil
1021}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001022
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001023func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1024 oldContents, err := os.ReadFile(path)
1025 if err != nil || !bytes.Equal(contents, oldContents) {
1026 err = os.WriteFile(path, contents, perm)
1027 }
1028 return nil
1029}
1030
Sasha Smundak39a301c2022-12-29 17:11:49 -08001031func (context *mixedBuildBazelContext) runAquery(config Config, ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -08001032 if ctx != nil {
1033 ctx.EventHandler.Begin("aquery")
1034 defer ctx.EventHandler.End("aquery")
1035 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001036 // Issue an aquery command to retrieve action information about the bazel build tree.
1037 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001038 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1039 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001040 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001041 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001042 extraFlags = append(extraFlags, "--collect_code_coverage")
1043 paths := make([]string, 0, 2)
1044 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001045 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001046 // TODO(b/259404593) convert path wildcard to regex values
1047 if p[i] == "*" {
1048 p[i] = ".*"
1049 }
1050 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001051 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1052 }
1053 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1054 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1055 }
1056 if len(paths) > 0 {
1057 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001058 }
1059 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001060 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
1061 extraFlags...))
1062 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001063 return err
1064 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001065 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
1066 return err
1067}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001068
Sasha Smundak39a301c2022-12-29 17:11:49 -08001069func (context *mixedBuildBazelContext) generateBazelSymlinks(ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -08001070 if ctx != nil {
1071 ctx.EventHandler.Begin("symlinks")
1072 defer ctx.EventHandler.End("symlinks")
1073 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001074 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1075 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1076 // but some of symlinks may be required to resolve source dependencies of the build.
Sasha Smundak4975c822022-11-16 15:28:18 -08001077 _, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd))
1078 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001079}
Chris Parsonsa798d962020-10-12 23:44:08 -04001080
Sasha Smundak39a301c2022-12-29 17:11:49 -08001081func (context *mixedBuildBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001082 return context.buildStatements
1083}
1084
Sasha Smundak39a301c2022-12-29 17:11:49 -08001085func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001086 return context.depsets
1087}
1088
Sasha Smundak39a301c2022-12-29 17:11:49 -08001089func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001090 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001091}
1092
Chris Parsonsa798d962020-10-12 23:44:08 -04001093// Singleton used for registering BUILD file ninja dependencies (needed
1094// for correctness of builds which use Bazel.
1095func BazelSingleton() Singleton {
1096 return &bazelSingleton{}
1097}
1098
1099type bazelSingleton struct{}
1100
1101func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001102 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001103 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001104 return
1105 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001106
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001107 // Add ninja file dependencies for files which all bazel invocations require.
1108 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001109 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001110 ctx.AddNinjaFileDeps(bazelBuildList)
1111
Sasha Smundak0e87b182022-12-01 11:46:11 -08001112 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001113 if err != nil {
1114 ctx.Errorf(err.Error())
1115 }
1116 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1117 for _, file := range files {
1118 ctx.AddNinjaFileDeps(file)
1119 }
1120
Chris Parsons1a7aca02022-04-25 22:35:15 -04001121 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1122 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001123 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001124 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1125 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001126 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1127 }
1128 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001129 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1130 if artifactPath == "bazel-out/volatile-status.txt" {
1131 // See https://bazel.build/docs/user-manual#workspace-status
1132 orderOnlies = append(orderOnlies, pathInBazelOut)
1133 } else {
1134 outputs = append(outputs, pathInBazelOut)
1135 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001136 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001137 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001138 ctx.Build(pctx, BuildParams{
1139 Rule: blueprint.Phony,
1140 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1141 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001142 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001143 })
1144 }
1145
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001146 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1147 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001148 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -07001149 if len(buildStatement.Command) > 0 {
1150 rule := NewRuleBuilder(pctx, ctx)
1151 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1152 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1153 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1154 continue
1155 }
1156 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1157 // and thus require special treatment. If BuildStatement were an interface implementing
1158 // buildRule(ctx) function, the code here would just call it.
1159 // Unfortunately, the BuildStatement is defined in
1160 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1161 // because this would cause circular dependency. So, until we move aquery processing
1162 // to the 'android' package, we need to handle special cases here.
1163 if buildStatement.Mnemonic == "FileWrite" || buildStatement.Mnemonic == "SourceSymlinkManifest" {
Cole Fausta7347492022-12-16 10:56:24 -08001164 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1165 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001166 } else if buildStatement.Mnemonic == "SymlinkTree" {
1167 // build-runfiles arguments are the manifest file and the target directory
1168 // where it creates the symlink tree according to this manifest (and then
1169 // writes the MANIFEST file to it).
1170 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1171 outManifestPath := outManifest.String()
1172 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1173 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1174 }
1175 outDir := filepath.Dir(outManifestPath)
1176 ctx.Build(pctx, BuildParams{
1177 Rule: buildRunfilesRule,
1178 Output: outManifest,
1179 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1180 Description: "symlink tree for " + outDir,
1181 Args: map[string]string{
1182 "outDir": outDir,
1183 },
1184 })
Sasha Smundak1da064c2022-06-08 16:36:16 -07001185 } else {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001186 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001187 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001188 }
1189}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001190
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001191// Register bazel-owned build statements (obtained from the aquery invocation).
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001192func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001193 // executionRoot is the action cwd.
1194 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1195
1196 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1197 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001198 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001199 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001200 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001201 }
1202 cmd.Text("&&")
1203 }
1204
1205 for _, pair := range buildStatement.Env {
1206 // Set per-action env variables, if any.
1207 cmd.Flag(pair.Key + "=" + pair.Value)
1208 }
1209
1210 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001211 if len(buildStatement.Command) > 16*1024 {
1212 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1213 WriteFileRule(ctx, commandFile, buildStatement.Command)
1214
1215 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1216 } else {
1217 cmd.Text(buildStatement.Command)
1218 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001219
1220 for _, outputPath := range buildStatement.OutputPaths {
1221 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1222 }
1223 for _, inputPath := range buildStatement.InputPaths {
1224 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1225 }
1226 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1227 otherDepsetName := bazelDepsetName(inputDepsetHash)
1228 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1229 }
1230
1231 if depfile := buildStatement.Depfile; depfile != nil {
1232 // The paths in depfile are relative to `executionRoot`.
1233 // Hence, they need to be corrected by replacing "bazel-out"
1234 // with the full `bazelOutDir`.
1235 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1236 // would be deemed missing.
1237 // (Note: The regexp uses a capture group because the version of sed
1238 // does not support a look-behind pattern.)
1239 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1240 bazelOutDir, *depfile)
1241 cmd.Text(replacement)
1242 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1243 }
1244
1245 for _, symlinkPath := range buildStatement.SymlinkPaths {
1246 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1247 }
1248}
1249
Chris Parsons8d6e4332021-02-22 16:13:50 -05001250func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001251 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001252}
1253
Chris Parsons787fb362021-10-14 18:43:51 -04001254func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001255 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001256 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001257 if key.configKey.osType.Class == Device {
1258 // For the generic Android, the expected result is "target|android", which
1259 // corresponds to the product_variable_config named "android_target" in
1260 // build/bazel/platforms/BUILD.bazel.
1261 arch = "target"
1262 } else {
1263 // Use host platform, which is currently hardcoded to be x86_64.
1264 arch = "x86_64"
1265 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001266 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001267 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001268 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001269 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001270 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001271 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001272 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -04001273}
1274
Chris Parsonsf874e462022-05-10 13:50:12 -04001275func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001276 return configKey{
1277 // use string because Arch is not a valid key in go
1278 arch: ctx.Arch().String(),
1279 osType: ctx.Os(),
1280 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001281}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001282
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001283func bazelDepsetName(contentHash string) string {
1284 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001285}