blob: 123cc608e24f86ba27fa2cfe0ac7e65d0a5061f2 [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) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500238 result, ok := m.LabelToOutputFiles[label]
239 if !ok {
240 return []string{}, fmt.Errorf("no target with label %q in LabelToOutputFiles", label)
241 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400242 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400243}
244
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700245func (m MockBazelContext) GetCcInfo(label string, _ configKey) (cquery.CcInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500246 result, ok := m.LabelToCcInfo[label]
247 if !ok {
248 return cquery.CcInfo{}, fmt.Errorf("no target with label %q in LabelToCcInfo", label)
249 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400250 return result, nil
251}
252
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700253func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500254 result, ok := m.LabelToPythonBinary[label]
255 if !ok {
256 return "", fmt.Errorf("no target with label %q in LabelToPythonBinary", label)
257 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400258 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000259}
260
Liz Kammerbe6a7122022-11-04 16:05:11 -0400261func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500262 result, ok := m.LabelToApexInfo[label]
263 if !ok {
264 return cquery.ApexInfo{}, fmt.Errorf("no target with label %q in LabelToApexInfo", label)
265 }
Liz Kammer0e255ef2022-11-04 16:07:04 -0400266 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700267}
268
Sasha Smundakedd16662022-10-07 14:44:50 -0700269func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500270 result, ok := m.LabelToCcBinary[label]
271 if !ok {
272 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no target with label %q in LabelToCcBinary", label)
273 }
Sasha Smundakedd16662022-10-07 14:44:50 -0700274 return result, nil
275}
276
Sasha Smundak0e87b182022-12-01 11:46:11 -0800277func (m MockBazelContext) InvokeBazel(_ Config, _ *Context) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400278 panic("unimplemented")
279}
280
Sasha Smundak39a301c2022-12-29 17:11:49 -0800281func (m MockBazelContext) IsModuleNameAllowed(_ string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400282 return true
283}
284
Liz Kammera92e8442021-04-07 20:25:21 -0400285func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500286
287func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
288 return []bazel.BuildStatement{}
289}
290
Chris Parsons1a7aca02022-04-25 22:35:15 -0400291func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
292 return []bazel.AqueryDepset{}
293}
294
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400295var _ BazelContext = MockBazelContext{}
296
Sasha Smundak39a301c2022-12-29 17:11:49 -0800297func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400298 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400299 bazelCtx.requestMutex.Lock()
300 defer bazelCtx.requestMutex.Unlock()
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500301
302 // Insert key into requests, maintaining the sort, and only if it's not duplicate.
303 keyString := key.String()
304 foundEqual := false
305 notLessThanKeyString := func(i int) bool {
306 s := bazelCtx.requests[i].String()
307 v := strings.Compare(s, keyString)
308 if v == 0 {
309 foundEqual = true
310 }
311 return v >= 0
312 }
313 targetIndex := sort.Search(len(bazelCtx.requests), notLessThanKeyString)
314 if foundEqual {
315 return
316 }
317
318 if targetIndex == len(bazelCtx.requests) {
319 bazelCtx.requests = append(bazelCtx.requests, key)
320 } else {
321 bazelCtx.requests = append(bazelCtx.requests[:targetIndex+1], bazelCtx.requests[targetIndex:]...)
322 bazelCtx.requests[targetIndex] = key
323 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400324}
325
Sasha Smundak39a301c2022-12-29 17:11:49 -0800326func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400327 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400328 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500329 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400330
Chris Parsonsf874e462022-05-10 13:50:12 -0400331 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400332 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400333 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400334}
335
Sasha Smundak39a301c2022-12-29 17:11:49 -0800336func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400337 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400338 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000339 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400340 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000341 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400342 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 +0000343}
344
Sasha Smundak39a301c2022-12-29 17:11:49 -0800345func (bazelCtx *mixedBuildBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400346 key := makeCqueryKey(label, cquery.GetPythonBinary, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400347 if rawString, ok := bazelCtx.results[key]; ok {
348 bazelOutput := strings.TrimSpace(rawString)
349 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
350 }
351 return "", fmt.Errorf("no bazel response found for %v", key)
352}
353
Sasha Smundak39a301c2022-12-29 17:11:49 -0800354func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400355 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700356 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500357 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700358 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400359 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700360}
361
Sasha Smundak39a301c2022-12-29 17:11:49 -0800362func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700363 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
364 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500365 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700366 }
367 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
368}
369
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700370func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500371 panic("unimplemented")
372}
373
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700374func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500375 panic("unimplemented")
376}
377
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700378func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400379 panic("unimplemented")
380}
381
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700382func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000383 panic("unimplemented")
384}
385
Liz Kammerbe6a7122022-11-04 16:05:11 -0400386func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700387 panic("unimplemented")
388}
389
Sasha Smundakedd16662022-10-07 14:44:50 -0700390func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
391 //TODO implement me
392 panic("implement me")
393}
394
Sasha Smundak0e87b182022-12-01 11:46:11 -0800395func (n noopBazelContext) InvokeBazel(_ Config, _ *Context) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400396 panic("unimplemented")
397}
398
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500399func (m noopBazelContext) OutputBase() string {
400 return ""
401}
402
Sasha Smundak39a301c2022-12-29 17:11:49 -0800403func (n noopBazelContext) IsModuleNameAllowed(_ string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400404 return false
405}
406
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500407func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
408 return []bazel.BuildStatement{}
409}
410
Chris Parsons1a7aca02022-04-25 22:35:15 -0400411func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
412 return []bazel.AqueryDepset{}
413}
414
Cole Faust705968d2022-12-14 11:32:05 -0800415func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400416 disabledModules := map[string]bool{}
417 enabledModules := map[string]bool{}
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800418 addToStringSet := func(set map[string]bool, items []string) {
419 for _, item := range items {
420 set[item] = true
421 }
422 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400423
Cole Faust705968d2022-12-14 11:32:05 -0800424 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400425 case BazelProdMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800426 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800427 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000428 enabledModules[enabledAdHocModule] = true
429 }
MarkDacekb78465d2022-10-18 20:10:16 +0000430 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400431 // Staging mode includes all prod modules plus all staging modules.
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800432 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
433 addToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800434 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000435 enabledModules[enabledAdHocModule] = true
436 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400437 case BazelDevMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800438 addToStringSet(disabledModules, allowlists.MixedBuildsDisabledList)
Chris Parsonsef615e52022-08-18 22:04:11 -0400439 default:
Cole Faust705968d2022-12-14 11:32:05 -0800440 panic("Expected BazelProdMode, BazelStagingMode, or BazelDevMode")
441 }
442 return enabledModules, disabledModules
443}
444
445func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
446 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
447 enabledList := make([]string, 0, len(enabledModules))
448 for module := range enabledModules {
449 if !disabledModules[module] {
450 enabledList = append(enabledList, module)
451 }
452 }
453 sort.Strings(enabledList)
454 return enabledList
455}
456
457func NewBazelContext(c *config) (BazelContext, error) {
458 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode && c.BuildMode != BazelDevMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400459 return noopBazelContext{}, nil
460 }
461
Cole Faust705968d2022-12-14 11:32:05 -0800462 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
463
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800464 paths := bazelPaths{
465 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400466 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800467 var missing []string
468 vars := []struct {
469 name string
470 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000471
472 // True if the environment variable needs to be tracked so that changes to the variable
473 // cause the ninja file to be regenerated, false otherwise. False should only be set for
474 // environment variables that have no effect on the generated ninja file.
475 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800476 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000477 {"BAZEL_HOME", &paths.homeDir, true},
478 {"BAZEL_PATH", &paths.bazelPath, true},
479 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
480 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
481 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
482 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800483 }
484 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000485 if v.track {
486 if s := c.Getenv(v.name); len(s) > 1 {
487 *v.ptr = s
488 continue
489 }
490 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800491 *v.ptr = s
492 } else {
493 missing = append(missing, v.name)
494 }
495 }
496 if len(missing) > 0 {
497 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
498 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800499
500 targetBuildVariant := "user"
501 if c.Eng() {
502 targetBuildVariant = "eng"
503 } else if c.Debuggable() {
504 targetBuildVariant = "userdebug"
505 }
506 targetProduct := "unknown"
507 if c.HasDeviceProduct() {
508 targetProduct = c.DeviceProduct()
509 }
510
Sasha Smundak39a301c2022-12-29 17:11:49 -0800511 return &mixedBuildBazelContext{
Chris Parsonsad876012022-08-20 14:48:32 -0400512 bazelRunner: &builtinBazelRunner{},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800513 paths: &paths,
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800514 modulesDefaultToBazel: c.BuildMode == BazelDevMode,
Chris Parsonsef615e52022-08-18 22:04:11 -0400515 bazelEnabledModules: enabledModules,
Chris Parsonsad876012022-08-20 14:48:32 -0400516 bazelDisabledModules: disabledModules,
Cole Faustb85d1a12022-11-08 18:14:01 -0800517 targetProduct: targetProduct,
518 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400519 }, nil
520}
521
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400522func (p *bazelPaths) BazelMetricsDir() string {
523 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000524}
525
Sasha Smundak39a301c2022-12-29 17:11:49 -0800526func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400527 if context.bazelDisabledModules[moduleName] {
528 return false
529 }
530 if context.bazelEnabledModules[moduleName] {
531 return true
532 }
533 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400534}
535
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400536func pwdPrefix() string {
537 // Darwin doesn't have /proc
538 if runtime.GOOS != "darwin" {
539 return "PWD=/proc/self/cwd"
540 }
541 return ""
542}
543
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400544type bazelCommand struct {
545 command string
546 // query or label
547 expression string
548}
549
550type mockBazelRunner struct {
551 bazelCommandResults map[bazelCommand]string
Jason Wu52cd1942022-09-08 15:37:57 +0000552 // use *exec.Cmd as a key to get the bazelCommand, the map will be used in issueBazelCommand()
553 // Register createBazelCommand() invocations. Later, an
554 // issueBazelCommand() invocation can be mapped to the *exec.Cmd instance
555 // and then to the expected result via bazelCommandResults
556 tokens map[*exec.Cmd]bazelCommand
557 commands []bazelCommand
558 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400559}
560
Sasha Smundak0e87b182022-12-01 11:46:11 -0800561func (r *mockBazelRunner) createBazelCommand(_ *bazelPaths, _ bazel.RunName,
Jason Wu52cd1942022-09-08 15:37:57 +0000562 command bazelCommand, extraFlags ...string) *exec.Cmd {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400563 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700564 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Jason Wu52cd1942022-09-08 15:37:57 +0000565 cmd := &exec.Cmd{}
566 if r.tokens == nil {
567 r.tokens = make(map[*exec.Cmd]bazelCommand)
568 }
569 r.tokens[cmd] = command
570 return cmd
571}
572
573func (r *mockBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
574 if command, ok := r.tokens[bazelCmd]; ok {
575 return r.bazelCommandResults[command], "", nil
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400576 }
577 return "", "", nil
578}
579
580type builtinBazelRunner struct{}
581
Chris Parsons808d84c2021-03-09 20:43:32 -0500582// Issues the given bazel command with given build label and additional flags.
583// Returns (stdout, stderr, error). The first and second return values are strings
584// containing the stdout and stderr of the run command, and an error is returned if
585// the invocation returned an error code.
Jason Wu52cd1942022-09-08 15:37:57 +0000586func (r *builtinBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
587 stderr := &bytes.Buffer{}
588 bazelCmd.Stderr = stderr
589 if output, err := bazelCmd.Output(); err != nil {
590 return "", string(stderr.Bytes()),
Sasha Smundak0e87b182022-12-01 11:46:11 -0800591 fmt.Errorf("bazel command failed: %s\n---command---\n%s\n---env---\n%s\n---stderr---\n%s---",
592 err, bazelCmd, strings.Join(bazelCmd.Env, "\n"), stderr)
Jason Wu52cd1942022-09-08 15:37:57 +0000593 } else {
594 return string(output), string(stderr.Bytes()), nil
595 }
596}
597
598func (r *builtinBazelRunner) createBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
599 extraFlags ...string) *exec.Cmd {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000600 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000601 "--output_base=" + absolutePath(paths.outputBase),
602 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700603 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700604 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700605 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400606
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700607 // Set default platforms to canonicalized values for mixed builds requests.
608 // If these are set in the bazelrc, they will have values that are
609 // non-canonicalized to @sourceroot labels, and thus be invalid when
610 // referenced from the buildroot.
611 //
612 // The actual platform values here may be overridden by configuration
613 // transitions from the buildroot.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700614 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Cole Faustb85d1a12022-11-08 18:14:01 -0800615
616 // We don't need to set --host_platforms because it's set in bazelrc files
617 // that the bazel shell script wrapper passes
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700618
619 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
620 "--experimental_repository_disable_download",
621
622 // Suppress noise
623 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500624 "--noshow_progress",
625 "--norun_validations",
626 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400627 cmdFlags = append(cmdFlags, extraFlags...)
628
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400629 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200630 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700631 extraEnv := []string{
632 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200633 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700634 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700635 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000636 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700637 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500638 // Disables local host detection of gcc; toolchain information is defined
639 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700640 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
641 }
642 bazelCmd.Env = append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400643
Jason Wu52cd1942022-09-08 15:37:57 +0000644 return bazelCmd
645}
646
647func printableCqueryCommand(bazelCmd *exec.Cmd) string {
648 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(bazelCmd.Args, "\" \"") + "\""
649 return outputString
650
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400651}
652
Sasha Smundak39a301c2022-12-29 17:11:49 -0800653func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500654 // TODO(cparsons): Define configuration transitions programmatically based
655 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400656 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500657#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400658# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500659#####################################################
660
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400661def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800662 if attr.os == "android" and attr.arch == "target":
663 target = "{PRODUCT}-{VARIANT}"
664 else:
665 target = "{PRODUCT}-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500666 return {
Cole Faustb85d1a12022-11-08 18:14:01 -0800667 "//command_line_option:platforms": "@soong_injection//product_config_platforms/products/{PRODUCT}-{VARIANT}:%s" % target,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500668 }
669
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400670_config_node_transition = transition(
671 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500672 inputs = [],
673 outputs = [
674 "//command_line_option:platforms",
675 ],
676)
677
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400678def _passthrough_rule_impl(ctx):
679 return [DefaultInfo(files = depset(ctx.files.deps))]
680
681config_node = rule(
682 implementation = _passthrough_rule_impl,
683 attrs = {
684 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400685 "os" : attr.string(mandatory = True),
686 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400687 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
688 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500689)
690
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400691
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500692# Rule representing the root of the build, to depend on all Bazel targets that
693# are required for the build. Building this target will build the entire Bazel
694# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400695mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400696 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500697 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400698 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500699 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400700)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500701
702def _phony_root_impl(ctx):
703 return []
704
705# Rule to depend on other targets but build nothing.
706# This is useful as follows: building a target of this rule will generate
707# symlink forests for all dependencies of the target, without executing any
708# actions of the build.
709phony_root = rule(
710 implementation = _phony_root_impl,
711 attrs = {"deps" : attr.label_list()},
712)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400713`
Cole Faustb85d1a12022-11-08 18:14:01 -0800714
715 productReplacer := strings.NewReplacer(
716 "{PRODUCT}", context.targetProduct,
717 "{VARIANT}", context.targetBuildVariant)
718
719 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400720}
721
Sasha Smundak39a301c2022-12-29 17:11:49 -0800722func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500723 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
724 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400725 formatString := `
726# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400727load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
728
729%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400730
731mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400732 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000733 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400734)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500735
736phony_root(name = "phonyroot",
737 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000738 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500739)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400740`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400741 configNodeFormatString := `
742config_node(name = "%s",
743 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400744 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400745 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000746 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400747)
748`
749
750 configNodesSection := ""
751
Chris Parsons787fb362021-10-14 18:43:51 -0400752 labelsByConfig := map[string][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500753
754 for _, val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200755 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400756 configString := getConfigString(val)
757 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400758 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400759
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500760 // Configs need to be sorted to maintain determinism of the BUILD file.
761 sortedConfigs := make([]string, 0, len(labelsByConfig))
762 for val := range labelsByConfig {
763 sortedConfigs = append(sortedConfigs, val)
764 }
765 sort.Slice(sortedConfigs, func(i, j int) bool { return sortedConfigs[i] < sortedConfigs[j] })
766
Jingwen Chen1e347862021-09-02 12:11:49 +0000767 allLabels := []string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500768 for _, configString := range sortedConfigs {
769 labels := labelsByConfig[configString]
Chris Parsons787fb362021-10-14 18:43:51 -0400770 configTokens := strings.Split(configString, "|")
771 if len(configTokens) != 2 {
772 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000773 }
Chris Parsons787fb362021-10-14 18:43:51 -0400774 archString := configTokens[0]
775 osString := configTokens[1]
776 targetString := fmt.Sprintf("%s_%s", osString, archString)
777 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
778 labelsString := strings.Join(labels, ",\n ")
779 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400780 }
781
Jingwen Chen1e347862021-09-02 12:11:49 +0000782 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400783}
784
Chris Parsons944e7d02021-03-11 11:08:46 -0500785func indent(original string) string {
786 result := ""
787 for _, line := range strings.Split(original, "\n") {
788 result += " " + line + "\n"
789 }
790 return result
791}
792
Chris Parsons808d84c2021-03-09 20:43:32 -0500793// Returns the file contents of the buildroot.cquery file that should be used for the cquery
794// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800795// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500796// and grouped by their request type. The data retrieved for each label depends on its
797// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800798func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400799 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500800 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500801 cqueryId := getCqueryId(val)
802 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
803 requestTypeToCqueryIdEntries[val.requestType] =
804 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
805 }
806 labelRegistrationMapSection := ""
807 functionDefSection := ""
808 mainSwitchSection := ""
809
810 mapDeclarationFormatString := `
811%s = {
812 %s
813}
814`
815 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800816def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500817%s
818`
819 mainSwitchSectionFormatString := `
820 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800821 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500822`
823
Usta Shrestha0b52d832022-02-04 21:37:39 -0500824 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500825 labelMapName := requestType.Name() + "_Labels"
826 functionName := requestType.Name() + "_Fn"
827 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
828 labelMapName,
829 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
830 functionDefSection += fmt.Sprintf(functionDefFormatString,
831 functionName,
832 indent(requestType.StarlarkFunctionBody()))
833 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
834 labelMapName, functionName)
835 }
836
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400837 formatString := `
838# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400839
Usta Shrestha79fccef2022-09-02 18:37:40 -0400840# a drop-in replacement for json.encode(), not available in cquery environment
841# TODO(cparsons): bring json module in and remove this function
842def json_encode(input):
843 # Avoiding recursion by limiting
844 # - a dict to contain anything except a dict
845 # - a list to contain only primitives
846 def encode_primitive(p):
847 t = type(p)
848 if t == "string" or t == "int":
849 return repr(p)
Cole Faustb85d1a12022-11-08 18:14:01 -0800850 fail("unsupported value '%s' of type '%s'" % (p, type(p)))
Usta Shrestha79fccef2022-09-02 18:37:40 -0400851
852 def encode_list(list):
Cole Faustb85d1a12022-11-08 18:14:01 -0800853 return "[%s]" % ", ".join([encode_primitive(item) for item in list])
Usta Shrestha79fccef2022-09-02 18:37:40 -0400854
855 def encode_list_or_primitive(v):
856 return encode_list(v) if type(v) == "list" else encode_primitive(v)
857
858 if type(input) == "dict":
859 # TODO(juu): the result is read line by line so can't use '\n' yet
Cole Faustb85d1a12022-11-08 18:14:01 -0800860 kv_pairs = [("%s: %s" % (encode_primitive(k), encode_list_or_primitive(v))) for (k, v) in input.items()]
861 return "{ %s }" % ", ".join(kv_pairs)
Usta Shrestha79fccef2022-09-02 18:37:40 -0400862 else:
863 return encode_list_or_primitive(input)
864
Cole Faustb85d1a12022-11-08 18:14:01 -0800865{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500866
Cole Faustb85d1a12022-11-08 18:14:01 -0800867{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500868
869def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400870 # TODO(b/199363072): filegroups and file targets aren't associated with any
871 # specific platform architecture in mixed builds. This is consistent with how
872 # Soong treats filegroups, but it may not be the case with manually-written
873 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500874 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000875 if buildoptions == None:
876 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400877 # any specific platform architecture in mixed builds, so use the host.
878 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -0800879 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500880 if len(platforms) != 1:
881 # An individual configured target should have only one platform architecture.
882 # Note that it's fine for there to be multiple architectures for the same label,
883 # but each is its own configured target.
884 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -0800885 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -0500886 if platform_name == "host":
887 return "HOST"
Cole Faustb85d1a12022-11-08 18:14:01 -0800888 if not platform_name.startswith("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}"):
889 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))
890 platform_name = platform_name.removeprefix("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}").removeprefix("_")
891 if not platform_name:
892 return "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400893 elif platform_name.startswith("android_"):
Cole Faustb85d1a12022-11-08 18:14:01 -0800894 return platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400895 elif platform_name.startswith("linux_"):
Cole Faustb85d1a12022-11-08 18:14:01 -0800896 return platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400897 else:
Cole Faustb85d1a12022-11-08 18:14:01 -0800898 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 -0500899
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400900def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500901 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500902
Chris Parsons86dc2c22022-09-28 14:58:41 -0400903 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
904 if id_string.startswith("//"):
905 id_string = "@" + id_string
906
Cole Faustb85d1a12022-11-08 18:14:01 -0800907 {MAIN_SWITCH_SECTION}
908
Chris Parsons944e7d02021-03-11 11:08:46 -0500909 # This target was not requested via cquery, and thus must be a dependency
910 # of a requested target.
911 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400912`
Cole Faustb85d1a12022-11-08 18:14:01 -0800913 replacer := strings.NewReplacer(
914 "{TARGET_PRODUCT}", context.targetProduct,
915 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
916 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
917 "{FUNCTION_DEF_SECTION}", functionDefSection,
918 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400919
Cole Faustb85d1a12022-11-08 18:14:01 -0800920 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400921}
922
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200923// Returns a path containing build-related metadata required for interfacing
924// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400925func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200926 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500927}
928
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200929// Returns the path where the contents of the @soong_injection repository live.
930// It is used by Soong to tell Bazel things it cannot over the command line.
931func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200932 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200933}
934
935// Returns the path of the synthetic Bazel workspace that contains a symlink
936// forest composed the whole source tree and BUILD files generated by bp2build.
937func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200938 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200939}
940
Jingwen Chen8c523582021-06-01 11:19:53 +0000941// Returns the path to the top level out dir ($OUT_DIR).
942func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200943 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000944}
945
Sasha Smundak4975c822022-11-16 15:28:18 -0800946const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
947
948var (
949 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
950 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
951 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
952)
953
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400954// Issues commands to Bazel to receive results for all cquery requests
955// queued in the BazelContext.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800956func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -0800957 if ctx != nil {
958 ctx.EventHandler.Begin("bazel")
959 defer ctx.EventHandler.End("bazel")
960 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400961
Sasha Smundak4975c822022-11-16 15:28:18 -0800962 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
963 if err := os.MkdirAll(metricsDir, 0777); err != nil {
964 return err
965 }
966 }
967 context.results = make(map[cqueryKey]string)
968 if err := context.runCquery(ctx); err != nil {
969 return err
970 }
971 if err := context.runAquery(config, ctx); err != nil {
972 return err
973 }
974 if err := context.generateBazelSymlinks(ctx); err != nil {
975 return err
976 }
977
978 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500979 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -0800980 return nil
981}
982
Sasha Smundak39a301c2022-12-29 17:11:49 -0800983func (context *mixedBuildBazelContext) runCquery(ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -0800984 if ctx != nil {
985 ctx.EventHandler.Begin("cquery")
986 defer ctx.EventHandler.End("cquery")
987 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200988 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200989 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
990 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
991 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -0500992 if err != nil {
993 return err
994 }
995 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500996 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200997 return err
998 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500999 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001000 return err
1001 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001002 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001003 return err
1004 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001005 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001006 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001007 return err
1008 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001009
Jason Wu52cd1942022-09-08 15:37:57 +00001010 cqueryCommandWithFlag := context.createBazelCommand(context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001011 "--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
Wei Licbd181c2022-11-16 08:59:23 -08001012 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCommandWithFlag)
1013 if cqueryErr != nil {
1014 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001015 }
Jason Wu52cd1942022-09-08 15:37:57 +00001016 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", printableCqueryCommand(cqueryCommandWithFlag))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001017 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001018 return err
1019 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001020 cqueryResults := map[string]string{}
1021 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1022 if strings.Contains(outputLine, ">>") {
1023 splitLine := strings.SplitN(outputLine, ">>", 2)
1024 cqueryResults[splitLine[0]] = splitLine[1]
1025 }
1026 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001027 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001028 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001029 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001030 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001031 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001032 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001033 }
1034 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001035 return nil
1036}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001037
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001038func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1039 oldContents, err := os.ReadFile(path)
1040 if err != nil || !bytes.Equal(contents, oldContents) {
1041 err = os.WriteFile(path, contents, perm)
1042 }
1043 return nil
1044}
1045
Sasha Smundak39a301c2022-12-29 17:11:49 -08001046func (context *mixedBuildBazelContext) runAquery(config Config, ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -08001047 if ctx != nil {
1048 ctx.EventHandler.Begin("aquery")
1049 defer ctx.EventHandler.End("aquery")
1050 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001051 // Issue an aquery command to retrieve action information about the bazel build tree.
1052 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001053 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1054 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001055 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001056 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001057 extraFlags = append(extraFlags, "--collect_code_coverage")
1058 paths := make([]string, 0, 2)
1059 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001060 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001061 // TODO(b/259404593) convert path wildcard to regex values
1062 if p[i] == "*" {
1063 p[i] = ".*"
1064 }
1065 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001066 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1067 }
1068 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1069 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1070 }
1071 if len(paths) > 0 {
1072 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001073 }
1074 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001075 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
1076 extraFlags...))
1077 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001078 return err
1079 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001080 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
1081 return err
1082}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001083
Sasha Smundak39a301c2022-12-29 17:11:49 -08001084func (context *mixedBuildBazelContext) generateBazelSymlinks(ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -08001085 if ctx != nil {
1086 ctx.EventHandler.Begin("symlinks")
1087 defer ctx.EventHandler.End("symlinks")
1088 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001089 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1090 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1091 // but some of symlinks may be required to resolve source dependencies of the build.
Sasha Smundak4975c822022-11-16 15:28:18 -08001092 _, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd))
1093 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001094}
Chris Parsonsa798d962020-10-12 23:44:08 -04001095
Sasha Smundak39a301c2022-12-29 17:11:49 -08001096func (context *mixedBuildBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001097 return context.buildStatements
1098}
1099
Sasha Smundak39a301c2022-12-29 17:11:49 -08001100func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001101 return context.depsets
1102}
1103
Sasha Smundak39a301c2022-12-29 17:11:49 -08001104func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001105 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001106}
1107
Chris Parsonsa798d962020-10-12 23:44:08 -04001108// Singleton used for registering BUILD file ninja dependencies (needed
1109// for correctness of builds which use Bazel.
1110func BazelSingleton() Singleton {
1111 return &bazelSingleton{}
1112}
1113
1114type bazelSingleton struct{}
1115
1116func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001117 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001118 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001119 return
1120 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001121
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001122 // Add ninja file dependencies for files which all bazel invocations require.
1123 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001124 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001125 ctx.AddNinjaFileDeps(bazelBuildList)
1126
Sasha Smundak0e87b182022-12-01 11:46:11 -08001127 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001128 if err != nil {
1129 ctx.Errorf(err.Error())
1130 }
1131 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1132 for _, file := range files {
1133 ctx.AddNinjaFileDeps(file)
1134 }
1135
Chris Parsons1a7aca02022-04-25 22:35:15 -04001136 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1137 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001138 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001139 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1140 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001141 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1142 }
1143 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001144 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1145 if artifactPath == "bazel-out/volatile-status.txt" {
1146 // See https://bazel.build/docs/user-manual#workspace-status
1147 orderOnlies = append(orderOnlies, pathInBazelOut)
1148 } else {
1149 outputs = append(outputs, pathInBazelOut)
1150 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001151 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001152 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001153 ctx.Build(pctx, BuildParams{
1154 Rule: blueprint.Phony,
1155 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1156 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001157 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001158 })
1159 }
1160
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001161 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1162 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001163 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -07001164 if len(buildStatement.Command) > 0 {
1165 rule := NewRuleBuilder(pctx, ctx)
1166 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1167 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1168 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1169 continue
1170 }
1171 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1172 // and thus require special treatment. If BuildStatement were an interface implementing
1173 // buildRule(ctx) function, the code here would just call it.
1174 // Unfortunately, the BuildStatement is defined in
1175 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1176 // because this would cause circular dependency. So, until we move aquery processing
1177 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001178 switch buildStatement.Mnemonic {
1179 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001180 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1181 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001182 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001183 // build-runfiles arguments are the manifest file and the target directory
1184 // where it creates the symlink tree according to this manifest (and then
1185 // writes the MANIFEST file to it).
1186 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1187 outManifestPath := outManifest.String()
1188 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1189 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1190 }
1191 outDir := filepath.Dir(outManifestPath)
1192 ctx.Build(pctx, BuildParams{
1193 Rule: buildRunfilesRule,
1194 Output: outManifest,
1195 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1196 Description: "symlink tree for " + outDir,
1197 Args: map[string]string{
1198 "outDir": outDir,
1199 },
1200 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001201 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001202 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001203 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001204 }
1205}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001206
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001207// Register bazel-owned build statements (obtained from the aquery invocation).
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001208func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001209 // executionRoot is the action cwd.
1210 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1211
1212 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1213 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001214 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001215 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001216 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001217 }
1218 cmd.Text("&&")
1219 }
1220
1221 for _, pair := range buildStatement.Env {
1222 // Set per-action env variables, if any.
1223 cmd.Flag(pair.Key + "=" + pair.Value)
1224 }
1225
1226 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001227 if len(buildStatement.Command) > 16*1024 {
1228 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1229 WriteFileRule(ctx, commandFile, buildStatement.Command)
1230
1231 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1232 } else {
1233 cmd.Text(buildStatement.Command)
1234 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001235
1236 for _, outputPath := range buildStatement.OutputPaths {
1237 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1238 }
1239 for _, inputPath := range buildStatement.InputPaths {
1240 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1241 }
1242 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1243 otherDepsetName := bazelDepsetName(inputDepsetHash)
1244 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1245 }
1246
1247 if depfile := buildStatement.Depfile; depfile != nil {
1248 // The paths in depfile are relative to `executionRoot`.
1249 // Hence, they need to be corrected by replacing "bazel-out"
1250 // with the full `bazelOutDir`.
1251 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1252 // would be deemed missing.
1253 // (Note: The regexp uses a capture group because the version of sed
1254 // does not support a look-behind pattern.)
1255 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1256 bazelOutDir, *depfile)
1257 cmd.Text(replacement)
1258 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1259 }
1260
1261 for _, symlinkPath := range buildStatement.SymlinkPaths {
1262 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1263 }
1264}
1265
Chris Parsons8d6e4332021-02-22 16:13:50 -05001266func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001267 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001268}
1269
Chris Parsons787fb362021-10-14 18:43:51 -04001270func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001271 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001272 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001273 if key.configKey.osType.Class == Device {
1274 // For the generic Android, the expected result is "target|android", which
1275 // corresponds to the product_variable_config named "android_target" in
1276 // build/bazel/platforms/BUILD.bazel.
1277 arch = "target"
1278 } else {
1279 // Use host platform, which is currently hardcoded to be x86_64.
1280 arch = "x86_64"
1281 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001282 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001283 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001284 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001285 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001286 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001287 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001288 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -04001289}
1290
Chris Parsonsf874e462022-05-10 13:50:12 -04001291func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001292 return configKey{
1293 // use string because Arch is not a valid key in go
1294 arch: ctx.Arch().String(),
1295 osType: ctx.Os(),
1296 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001297}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001298
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001299func bazelDepsetName(contentHash string) string {
1300 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001301}