blob: 17d01244712f9b1df76be0794cf53e7d0652cc74 [file] [log] [blame]
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001// Copyright 2020 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package android
16
17import (
18 "bytes"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040019 "fmt"
20 "os"
21 "os/exec"
Usta Shresthaacd5a0c2022-06-22 11:20:50 -040022 "path"
Chris Parsonsa798d962020-10-12 23:44:08 -040023 "path/filepath"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040024 "runtime"
Cole Faust705968d2022-12-14 11:32:05 -080025 "sort"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040026 "strings"
27 "sync"
Chris Parsonsa798d962020-10-12 23:44:08 -040028
Chris Parsonsad876012022-08-20 14:48:32 -040029 "android/soong/android/allowlists"
Chris Parsons944e7d02021-03-11 11:08:46 -050030 "android/soong/bazel/cquery"
Jingwen Chen1e347862021-09-02 12:11:49 +000031 "android/soong/shared"
Sam Delmericocb3c52c2023-02-03 17:40:08 -050032 "android/soong/starlark_fmt"
Liz Kammer337e9032022-08-03 15:49:43 -040033
Chris Parsons1a7aca02022-04-25 22:35:15 -040034 "github.com/google/blueprint"
Liz Kammer8206d4f2021-03-03 16:40:52 -050035
Patrice Arruda05ab2d02020-12-12 06:24:26 +000036 "android/soong/bazel"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040037)
38
Sasha Smundak1da064c2022-06-08 16:36:16 -070039var (
Sasha Smundakc180dbd2022-07-03 14:55:58 -070040 _ = pctx.HostBinToolVariable("bazelBuildRunfilesTool", "build-runfiles")
41 buildRunfilesRule = pctx.AndroidStaticRule("bazelBuildRunfiles", blueprint.RuleParams{
42 Command: "${bazelBuildRunfilesTool} ${in} ${outDir}",
43 Depfile: "",
44 Description: "",
45 CommandDeps: []string{"${bazelBuildRunfilesTool}"},
46 }, "outDir")
Sam Delmericocb3c52c2023-02-03 17:40:08 -050047 allowedBazelEnvironmentVars = []string{
48 "ALLOW_LOCAL_TIDY_TRUE",
49 "DEFAULT_TIDY_HEADER_DIRS",
50 "TIDY_TIMEOUT",
51 "WITH_TIDY",
52 "WITH_TIDY_FLAGS",
53 "SKIP_ABI_CHECKS",
54 "UNSAFE_DISABLE_APEX_ALLOWED_DEPS_CHECK",
55 "AUTO_ZERO_INITIALIZE",
56 "AUTO_PATTERN_INITIALIZE",
57 "AUTO_UNINITIALIZE",
58 "USE_CCACHE",
59 "LLVM_NEXT",
60 "ALLOW_UNKNOWN_WARNING_OPTION",
61
62 // Overrides the version in the apex_manifest.json. The version is unique for
63 // each branch (internal, aosp, mainline releases, dessert releases). This
64 // enables modules built on an older branch to be installed against a newer
65 // device for development purposes.
66 "OVERRIDE_APEX_MANIFEST_DEFAULT_VERSION",
67 }
Sasha Smundak1da064c2022-06-08 16:36:16 -070068)
69
Chris Parsonsf874e462022-05-10 13:50:12 -040070func init() {
71 RegisterMixedBuildsMutator(InitRegistrationContext)
72}
73
74func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammer337e9032022-08-03 15:49:43 -040075 ctx.FinalDepsMutators(func(ctx RegisterMutatorsContext) {
Chris Parsonsf874e462022-05-10 13:50:12 -040076 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
77 })
78}
79
80func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
81 if m := ctx.Module(); m.Enabled() {
82 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
83 if mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx) {
84 mixedBuildMod.QueueBazelCall(ctx)
85 }
86 }
87 }
88}
89
Liz Kammerf29df7c2021-04-02 13:37:39 -040090type cqueryRequest interface {
91 // Name returns a string name for this request type. Such request type names must be unique,
92 // and must only consist of alphanumeric characters.
93 Name() string
94
95 // StarlarkFunctionBody returns a starlark function body to process this request type.
96 // The returned string is the body of a Starlark function which obtains
97 // all request-relevant information about a target and returns a string containing
98 // this information.
99 // The function should have the following properties:
Cole Faust97d15272022-11-22 14:08:59 -0800100 // - The arguments are `target` (a configured target) and `id_string` (the label + configuration).
Liz Kammerf29df7c2021-04-02 13:37:39 -0400101 // - The return value must be a string.
102 // - The function body should not be indented outside of its own scope.
103 StarlarkFunctionBody() string
104}
105
Chris Parsons787fb362021-10-14 18:43:51 -0400106// Portion of cquery map key to describe target configuration.
107type configKey struct {
Liz Kammer0940b892022-03-18 15:55:04 -0400108 arch string
109 osType OsType
Chris Parsons787fb362021-10-14 18:43:51 -0400110}
111
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700112func (c configKey) String() string {
113 return fmt.Sprintf("%s::%s", c.arch, c.osType)
114}
115
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400116// Map key to describe bazel cquery requests.
117type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400118 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400119 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400120 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400121}
122
Chris Parsons86dc2c22022-09-28 14:58:41 -0400123func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
124 if strings.HasPrefix(label, "//") {
125 // Normalize Bazel labels to specify main repository explicitly.
126 label = "@" + label
127 }
128 return cqueryKey{label, cqueryRequest, cfgKey}
129}
130
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700131func (c cqueryKey) String() string {
132 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700133}
134
Chris Parsonsf874e462022-05-10 13:50:12 -0400135// BazelContext is a context object useful for interacting with Bazel during
136// the course of a build. Use of Bazel to evaluate part of the build graph
137// is referred to as a "mixed build". (Some modules are managed by Soong,
138// some are managed by Bazel). To facilitate interop between these build
139// subgraphs, Soong may make requests to Bazel and evaluate their responses
140// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400141type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400142 // Add a cquery request to the bazel request queue. All queued requests
143 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
144 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
145
146 // ** Cquery Results Retrieval Functions
147 // The below functions pertain to retrieving cquery results from a prior
148 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400149
150 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400151 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500152
Chris Parsons944e7d02021-03-11 11:08:46 -0500153 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400154 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400155
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000156 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400157 // TODO(b/232976601): Remove.
158 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000159
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700160 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400161 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700162
Sasha Smundakedd16662022-10-07 14:44:50 -0700163 // Returns the results of the GetCcUnstrippedInfo query
164 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
165
Chris Parsonsf874e462022-05-10 13:50:12 -0400166 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400167
168 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800169 // queued in the BazelContext. The ctx argument is optional and is only
170 // used for performance data collection
171 InvokeBazel(config Config, ctx *Context) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400172
Chris Parsonsad876012022-08-20 14:48:32 -0400173 // Returns true if Bazel handling is enabled for the module with the given name.
174 // Note that this only implies "bazel mixed build" allowlisting. The caller
175 // should independently verify the module is eligible for Bazel handling
176 // (for example, that it is MixedBuildBuildable).
Sasha Smundak39a301c2022-12-29 17:11:49 -0800177 IsModuleNameAllowed(moduleName string) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500178
179 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
180 OutputBase() string
181
182 // Returns build statements which should get registered to reflect Bazel's outputs.
183 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400184
185 // Returns the depsets defined in Bazel's aquery response.
186 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400187}
188
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400189type bazelRunner interface {
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500190 createBazelCommand(config Config, paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) *exec.Cmd
Jason Wu52cd1942022-09-08 15:37:57 +0000191 issueBazelCommand(bazelCmd *exec.Cmd) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400192}
193
194type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000195 homeDir string
196 bazelPath string
197 outputBase string
198 workspaceDir string
199 soongOutDir string
200 metricsDir string
201 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400202}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400203
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400204// A context object which tracks queued requests that need to be made to Bazel,
205// and their results after the requests have been made.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800206type mixedBuildBazelContext struct {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400207 bazelRunner
208 paths *bazelPaths
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400209 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
210 requestMutex sync.Mutex // requests can be written in parallel
211
212 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500213
214 // Build statements which should get registered to reflect Bazel's outputs.
215 buildStatements []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400216
217 // Depsets which should be used for Bazel's build statements.
218 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400219
220 // Per-module allowlist/denylist functionality to control whether analysis of
221 // modules are handled by Bazel. For modules which do not have a Bazel definition
222 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
223 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
224 // Per-module denylist to opt modules out of bazel handling.
225 bazelDisabledModules map[string]bool
226 // Per-module allowlist to opt modules in to bazel handling.
227 bazelEnabledModules map[string]bool
228 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
229 modulesDefaultToBazel bool
Cole Faustb85d1a12022-11-08 18:14:01 -0800230
231 targetProduct string
232 targetBuildVariant string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400233}
234
Sasha Smundak39a301c2022-12-29 17:11:49 -0800235var _ BazelContext = &mixedBuildBazelContext{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400236
237// A bazel context to use when Bazel is disabled.
238type noopBazelContext struct{}
239
240var _ BazelContext = noopBazelContext{}
241
242// A bazel context to use for tests.
243type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400244 OutputBaseDir string
245
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000246 LabelToOutputFiles map[string][]string
247 LabelToCcInfo map[string]cquery.CcInfo
248 LabelToPythonBinary map[string]string
Liz Kammerbe6a7122022-11-04 16:05:11 -0400249 LabelToApexInfo map[string]cquery.ApexInfo
Sasha Smundakedd16662022-10-07 14:44:50 -0700250 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400251}
252
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700253func (m MockBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400254 panic("unimplemented")
Chris Parsons8d6e4332021-02-22 16:13:50 -0500255}
256
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700257func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500258 result, ok := m.LabelToOutputFiles[label]
259 if !ok {
260 return []string{}, fmt.Errorf("no target with label %q in LabelToOutputFiles", label)
261 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400262 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400263}
264
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700265func (m MockBazelContext) GetCcInfo(label string, _ configKey) (cquery.CcInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500266 result, ok := m.LabelToCcInfo[label]
267 if !ok {
268 return cquery.CcInfo{}, fmt.Errorf("no target with label %q in LabelToCcInfo", label)
269 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400270 return result, nil
271}
272
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700273func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500274 result, ok := m.LabelToPythonBinary[label]
275 if !ok {
276 return "", fmt.Errorf("no target with label %q in LabelToPythonBinary", label)
277 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400278 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000279}
280
Liz Kammerbe6a7122022-11-04 16:05:11 -0400281func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500282 result, ok := m.LabelToApexInfo[label]
283 if !ok {
284 return cquery.ApexInfo{}, fmt.Errorf("no target with label %q in LabelToApexInfo", label)
285 }
Liz Kammer0e255ef2022-11-04 16:07:04 -0400286 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700287}
288
Sasha Smundakedd16662022-10-07 14:44:50 -0700289func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500290 result, ok := m.LabelToCcBinary[label]
291 if !ok {
292 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no target with label %q in LabelToCcBinary", label)
293 }
Sasha Smundakedd16662022-10-07 14:44:50 -0700294 return result, nil
295}
296
Sasha Smundak0e87b182022-12-01 11:46:11 -0800297func (m MockBazelContext) InvokeBazel(_ Config, _ *Context) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400298 panic("unimplemented")
299}
300
Sasha Smundak39a301c2022-12-29 17:11:49 -0800301func (m MockBazelContext) IsModuleNameAllowed(_ string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400302 return true
303}
304
Liz Kammera92e8442021-04-07 20:25:21 -0400305func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500306
307func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
308 return []bazel.BuildStatement{}
309}
310
Chris Parsons1a7aca02022-04-25 22:35:15 -0400311func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
312 return []bazel.AqueryDepset{}
313}
314
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400315var _ BazelContext = MockBazelContext{}
316
Sasha Smundak39a301c2022-12-29 17:11:49 -0800317func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400318 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400319 bazelCtx.requestMutex.Lock()
320 defer bazelCtx.requestMutex.Unlock()
321 bazelCtx.requests[key] = true
322}
323
Sasha Smundak39a301c2022-12-29 17:11:49 -0800324func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400325 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400326 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500327 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400328
Chris Parsonsf874e462022-05-10 13:50:12 -0400329 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400330 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400331 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400332}
333
Sasha Smundak39a301c2022-12-29 17:11:49 -0800334func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400335 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400336 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000337 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400338 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000339 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400340 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 +0000341}
342
Sasha Smundak39a301c2022-12-29 17:11:49 -0800343func (bazelCtx *mixedBuildBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400344 key := makeCqueryKey(label, cquery.GetPythonBinary, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400345 if rawString, ok := bazelCtx.results[key]; ok {
346 bazelOutput := strings.TrimSpace(rawString)
347 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
348 }
349 return "", fmt.Errorf("no bazel response found for %v", key)
350}
351
Sasha Smundak39a301c2022-12-29 17:11:49 -0800352func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400353 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700354 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500355 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700356 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400357 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700358}
359
Sasha Smundak39a301c2022-12-29 17:11:49 -0800360func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700361 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
362 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500363 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700364 }
365 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
366}
367
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700368func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500369 panic("unimplemented")
370}
371
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700372func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500373 panic("unimplemented")
374}
375
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700376func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400377 panic("unimplemented")
378}
379
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700380func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000381 panic("unimplemented")
382}
383
Liz Kammerbe6a7122022-11-04 16:05:11 -0400384func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700385 panic("unimplemented")
386}
387
Sasha Smundakedd16662022-10-07 14:44:50 -0700388func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
389 //TODO implement me
390 panic("implement me")
391}
392
Sasha Smundak0e87b182022-12-01 11:46:11 -0800393func (n noopBazelContext) InvokeBazel(_ Config, _ *Context) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400394 panic("unimplemented")
395}
396
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500397func (m noopBazelContext) OutputBase() string {
398 return ""
399}
400
Sasha Smundak39a301c2022-12-29 17:11:49 -0800401func (n noopBazelContext) IsModuleNameAllowed(_ string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400402 return false
403}
404
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500405func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
406 return []bazel.BuildStatement{}
407}
408
Chris Parsons1a7aca02022-04-25 22:35:15 -0400409func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
410 return []bazel.AqueryDepset{}
411}
412
Cole Faust705968d2022-12-14 11:32:05 -0800413func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400414 disabledModules := map[string]bool{}
415 enabledModules := map[string]bool{}
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800416 addToStringSet := func(set map[string]bool, items []string) {
417 for _, item := range items {
418 set[item] = true
419 }
420 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400421
Cole Faust705968d2022-12-14 11:32:05 -0800422 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400423 case BazelProdMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800424 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800425 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000426 enabledModules[enabledAdHocModule] = true
427 }
MarkDacekb78465d2022-10-18 20:10:16 +0000428 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400429 // Staging mode includes all prod modules plus all staging modules.
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800430 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
431 addToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800432 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000433 enabledModules[enabledAdHocModule] = true
434 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400435 case BazelDevMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800436 addToStringSet(disabledModules, allowlists.MixedBuildsDisabledList)
Chris Parsonsef615e52022-08-18 22:04:11 -0400437 default:
Cole Faust705968d2022-12-14 11:32:05 -0800438 panic("Expected BazelProdMode, BazelStagingMode, or BazelDevMode")
439 }
440 return enabledModules, disabledModules
441}
442
443func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
444 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
445 enabledList := make([]string, 0, len(enabledModules))
446 for module := range enabledModules {
447 if !disabledModules[module] {
448 enabledList = append(enabledList, module)
449 }
450 }
451 sort.Strings(enabledList)
452 return enabledList
453}
454
455func NewBazelContext(c *config) (BazelContext, error) {
456 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode && c.BuildMode != BazelDevMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400457 return noopBazelContext{}, nil
458 }
459
Cole Faust705968d2022-12-14 11:32:05 -0800460 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
461
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800462 paths := bazelPaths{
463 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400464 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800465 var missing []string
466 vars := []struct {
467 name string
468 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000469
470 // True if the environment variable needs to be tracked so that changes to the variable
471 // cause the ninja file to be regenerated, false otherwise. False should only be set for
472 // environment variables that have no effect on the generated ninja file.
473 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800474 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000475 {"BAZEL_HOME", &paths.homeDir, true},
476 {"BAZEL_PATH", &paths.bazelPath, true},
477 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
478 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
479 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
480 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800481 }
482 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000483 if v.track {
484 if s := c.Getenv(v.name); len(s) > 1 {
485 *v.ptr = s
486 continue
487 }
488 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800489 *v.ptr = s
490 } else {
491 missing = append(missing, v.name)
492 }
493 }
494 if len(missing) > 0 {
495 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
496 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800497
498 targetBuildVariant := "user"
499 if c.Eng() {
500 targetBuildVariant = "eng"
501 } else if c.Debuggable() {
502 targetBuildVariant = "userdebug"
503 }
504 targetProduct := "unknown"
505 if c.HasDeviceProduct() {
506 targetProduct = c.DeviceProduct()
507 }
508
Sasha Smundak39a301c2022-12-29 17:11:49 -0800509 return &mixedBuildBazelContext{
Chris Parsonsad876012022-08-20 14:48:32 -0400510 bazelRunner: &builtinBazelRunner{},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800511 paths: &paths,
Chris Parsonsad876012022-08-20 14:48:32 -0400512 requests: make(map[cqueryKey]bool),
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800513 modulesDefaultToBazel: c.BuildMode == BazelDevMode,
Chris Parsonsef615e52022-08-18 22:04:11 -0400514 bazelEnabledModules: enabledModules,
Chris Parsonsad876012022-08-20 14:48:32 -0400515 bazelDisabledModules: disabledModules,
Cole Faustb85d1a12022-11-08 18:14:01 -0800516 targetProduct: targetProduct,
517 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400518 }, nil
519}
520
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400521func (p *bazelPaths) BazelMetricsDir() string {
522 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000523}
524
Sasha Smundak39a301c2022-12-29 17:11:49 -0800525func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400526 if context.bazelDisabledModules[moduleName] {
527 return false
528 }
529 if context.bazelEnabledModules[moduleName] {
530 return true
531 }
532 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400533}
534
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400535func pwdPrefix() string {
536 // Darwin doesn't have /proc
537 if runtime.GOOS != "darwin" {
538 return "PWD=/proc/self/cwd"
539 }
540 return ""
541}
542
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400543type bazelCommand struct {
544 command string
545 // query or label
546 expression string
547}
548
549type mockBazelRunner struct {
550 bazelCommandResults map[bazelCommand]string
Jason Wu52cd1942022-09-08 15:37:57 +0000551 // use *exec.Cmd as a key to get the bazelCommand, the map will be used in issueBazelCommand()
552 // Register createBazelCommand() invocations. Later, an
553 // issueBazelCommand() invocation can be mapped to the *exec.Cmd instance
554 // and then to the expected result via bazelCommandResults
555 tokens map[*exec.Cmd]bazelCommand
556 commands []bazelCommand
557 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400558}
559
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500560func (r *mockBazelRunner) createBazelCommand(_ Config, _ *bazelPaths, _ bazel.RunName,
Jason Wu52cd1942022-09-08 15:37:57 +0000561 command bazelCommand, extraFlags ...string) *exec.Cmd {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400562 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700563 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Jason Wu52cd1942022-09-08 15:37:57 +0000564 cmd := &exec.Cmd{}
565 if r.tokens == nil {
566 r.tokens = make(map[*exec.Cmd]bazelCommand)
567 }
568 r.tokens[cmd] = command
569 return cmd
570}
571
572func (r *mockBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
573 if command, ok := r.tokens[bazelCmd]; ok {
574 return r.bazelCommandResults[command], "", nil
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400575 }
576 return "", "", nil
577}
578
579type builtinBazelRunner struct{}
580
Chris Parsons808d84c2021-03-09 20:43:32 -0500581// Issues the given bazel command with given build label and additional flags.
582// Returns (stdout, stderr, error). The first and second return values are strings
583// containing the stdout and stderr of the run command, and an error is returned if
584// the invocation returned an error code.
Jason Wu52cd1942022-09-08 15:37:57 +0000585func (r *builtinBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
586 stderr := &bytes.Buffer{}
587 bazelCmd.Stderr = stderr
588 if output, err := bazelCmd.Output(); err != nil {
589 return "", string(stderr.Bytes()),
Sasha Smundak0e87b182022-12-01 11:46:11 -0800590 fmt.Errorf("bazel command failed: %s\n---command---\n%s\n---env---\n%s\n---stderr---\n%s---",
591 err, bazelCmd, strings.Join(bazelCmd.Env, "\n"), stderr)
Jason Wu52cd1942022-09-08 15:37:57 +0000592 } else {
593 return string(output), string(stderr.Bytes()), nil
594 }
595}
596
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500597func (r *builtinBazelRunner) createBazelCommand(config Config, paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Jason Wu52cd1942022-09-08 15:37:57 +0000598 extraFlags ...string) *exec.Cmd {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000599 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000600 "--output_base=" + absolutePath(paths.outputBase),
601 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700602 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700603 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700604 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400605
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700606 // Set default platforms to canonicalized values for mixed builds requests.
607 // If these are set in the bazelrc, they will have values that are
608 // non-canonicalized to @sourceroot labels, and thus be invalid when
609 // referenced from the buildroot.
610 //
611 // The actual platform values here may be overridden by configuration
612 // transitions from the buildroot.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700613 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Cole Faustb85d1a12022-11-08 18:14:01 -0800614
615 // We don't need to set --host_platforms because it's set in bazelrc files
616 // that the bazel shell script wrapper passes
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700617
618 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
619 "--experimental_repository_disable_download",
620
621 // Suppress noise
622 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500623 "--noshow_progress",
624 "--norun_validations",
625 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400626 cmdFlags = append(cmdFlags, extraFlags...)
627
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400628 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200629 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700630 extraEnv := []string{
631 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200632 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700633 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700634 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000635 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700636 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500637 // Disables local host detection of gcc; toolchain information is defined
638 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700639 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
640 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500641 for _, envvar := range allowedBazelEnvironmentVars {
642 val := config.Getenv(envvar)
643 if val == "" {
644 continue
645 }
646 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
647 }
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700648 bazelCmd.Env = append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400649
Jason Wu52cd1942022-09-08 15:37:57 +0000650 return bazelCmd
651}
652
653func printableCqueryCommand(bazelCmd *exec.Cmd) string {
654 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(bazelCmd.Args, "\" \"") + "\""
655 return outputString
656
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400657}
658
Sasha Smundak39a301c2022-12-29 17:11:49 -0800659func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500660 // TODO(cparsons): Define configuration transitions programmatically based
661 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400662 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500663#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400664# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500665#####################################################
666
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400667def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800668 if attr.os == "android" and attr.arch == "target":
669 target = "{PRODUCT}-{VARIANT}"
670 else:
671 target = "{PRODUCT}-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500672 return {
Cole Faustb85d1a12022-11-08 18:14:01 -0800673 "//command_line_option:platforms": "@soong_injection//product_config_platforms/products/{PRODUCT}-{VARIANT}:%s" % target,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500674 }
675
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400676_config_node_transition = transition(
677 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500678 inputs = [],
679 outputs = [
680 "//command_line_option:platforms",
681 ],
682)
683
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400684def _passthrough_rule_impl(ctx):
685 return [DefaultInfo(files = depset(ctx.files.deps))]
686
687config_node = rule(
688 implementation = _passthrough_rule_impl,
689 attrs = {
690 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400691 "os" : attr.string(mandatory = True),
692 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400693 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
694 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500695)
696
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400697
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500698# Rule representing the root of the build, to depend on all Bazel targets that
699# are required for the build. Building this target will build the entire Bazel
700# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400701mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400702 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500703 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400704 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500705 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400706)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500707
708def _phony_root_impl(ctx):
709 return []
710
711# Rule to depend on other targets but build nothing.
712# This is useful as follows: building a target of this rule will generate
713# symlink forests for all dependencies of the target, without executing any
714# actions of the build.
715phony_root = rule(
716 implementation = _phony_root_impl,
717 attrs = {"deps" : attr.label_list()},
718)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400719`
Cole Faustb85d1a12022-11-08 18:14:01 -0800720
721 productReplacer := strings.NewReplacer(
722 "{PRODUCT}", context.targetProduct,
723 "{VARIANT}", context.targetBuildVariant)
724
725 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400726}
727
Sasha Smundak39a301c2022-12-29 17:11:49 -0800728func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500729 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
730 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400731 formatString := `
732# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400733load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
734
735%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400736
737mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400738 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000739 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400740)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500741
742phony_root(name = "phonyroot",
743 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000744 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500745)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400746`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400747 configNodeFormatString := `
748config_node(name = "%s",
749 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400750 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400751 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000752 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400753)
754`
755
756 configNodesSection := ""
757
Chris Parsons787fb362021-10-14 18:43:51 -0400758 labelsByConfig := map[string][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400759 for val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200760 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400761 configString := getConfigString(val)
762 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400763 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400764
Jingwen Chen1e347862021-09-02 12:11:49 +0000765 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400766 for configString, labels := range labelsByConfig {
767 configTokens := strings.Split(configString, "|")
768 if len(configTokens) != 2 {
769 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000770 }
Chris Parsons787fb362021-10-14 18:43:51 -0400771 archString := configTokens[0]
772 osString := configTokens[1]
773 targetString := fmt.Sprintf("%s_%s", osString, archString)
774 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
775 labelsString := strings.Join(labels, ",\n ")
776 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400777 }
778
Jingwen Chen1e347862021-09-02 12:11:49 +0000779 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400780}
781
Chris Parsons944e7d02021-03-11 11:08:46 -0500782func indent(original string) string {
783 result := ""
784 for _, line := range strings.Split(original, "\n") {
785 result += " " + line + "\n"
786 }
787 return result
788}
789
Chris Parsons808d84c2021-03-09 20:43:32 -0500790// Returns the file contents of the buildroot.cquery file that should be used for the cquery
791// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800792// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500793// and grouped by their request type. The data retrieved for each label depends on its
794// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800795func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400796 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400797 for val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500798 cqueryId := getCqueryId(val)
799 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
800 requestTypeToCqueryIdEntries[val.requestType] =
801 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
802 }
803 labelRegistrationMapSection := ""
804 functionDefSection := ""
805 mainSwitchSection := ""
806
807 mapDeclarationFormatString := `
808%s = {
809 %s
810}
811`
812 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800813def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500814%s
815`
816 mainSwitchSectionFormatString := `
817 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800818 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500819`
820
Usta Shrestha0b52d832022-02-04 21:37:39 -0500821 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500822 labelMapName := requestType.Name() + "_Labels"
823 functionName := requestType.Name() + "_Fn"
824 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
825 labelMapName,
826 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
827 functionDefSection += fmt.Sprintf(functionDefFormatString,
828 functionName,
829 indent(requestType.StarlarkFunctionBody()))
830 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
831 labelMapName, functionName)
832 }
833
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400834 formatString := `
835# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400836
Usta Shrestha79fccef2022-09-02 18:37:40 -0400837# a drop-in replacement for json.encode(), not available in cquery environment
838# TODO(cparsons): bring json module in and remove this function
839def json_encode(input):
840 # Avoiding recursion by limiting
841 # - a dict to contain anything except a dict
842 # - a list to contain only primitives
843 def encode_primitive(p):
844 t = type(p)
845 if t == "string" or t == "int":
846 return repr(p)
Cole Faustb85d1a12022-11-08 18:14:01 -0800847 fail("unsupported value '%s' of type '%s'" % (p, type(p)))
Usta Shrestha79fccef2022-09-02 18:37:40 -0400848
849 def encode_list(list):
Cole Faustb85d1a12022-11-08 18:14:01 -0800850 return "[%s]" % ", ".join([encode_primitive(item) for item in list])
Usta Shrestha79fccef2022-09-02 18:37:40 -0400851
852 def encode_list_or_primitive(v):
853 return encode_list(v) if type(v) == "list" else encode_primitive(v)
854
855 if type(input) == "dict":
856 # TODO(juu): the result is read line by line so can't use '\n' yet
Cole Faustb85d1a12022-11-08 18:14:01 -0800857 kv_pairs = [("%s: %s" % (encode_primitive(k), encode_list_or_primitive(v))) for (k, v) in input.items()]
858 return "{ %s }" % ", ".join(kv_pairs)
Usta Shrestha79fccef2022-09-02 18:37:40 -0400859 else:
860 return encode_list_or_primitive(input)
861
Cole Faustb85d1a12022-11-08 18:14:01 -0800862{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500863
Cole Faustb85d1a12022-11-08 18:14:01 -0800864{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500865
866def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400867 # TODO(b/199363072): filegroups and file targets aren't associated with any
868 # specific platform architecture in mixed builds. This is consistent with how
869 # Soong treats filegroups, but it may not be the case with manually-written
870 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500871 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000872 if buildoptions == None:
873 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400874 # any specific platform architecture in mixed builds, so use the host.
875 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -0800876 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500877 if len(platforms) != 1:
878 # An individual configured target should have only one platform architecture.
879 # Note that it's fine for there to be multiple architectures for the same label,
880 # but each is its own configured target.
881 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -0800882 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -0500883 if platform_name == "host":
884 return "HOST"
Cole Faustb85d1a12022-11-08 18:14:01 -0800885 if not platform_name.startswith("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}"):
886 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))
887 platform_name = platform_name.removeprefix("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}").removeprefix("_")
888 if not platform_name:
889 return "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400890 elif platform_name.startswith("android_"):
Cole Faustb85d1a12022-11-08 18:14:01 -0800891 return platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400892 elif platform_name.startswith("linux_"):
Cole Faustb85d1a12022-11-08 18:14:01 -0800893 return platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400894 else:
Cole Faustb85d1a12022-11-08 18:14:01 -0800895 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 -0500896
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400897def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500898 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500899
Chris Parsons86dc2c22022-09-28 14:58:41 -0400900 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
901 if id_string.startswith("//"):
902 id_string = "@" + id_string
903
Cole Faustb85d1a12022-11-08 18:14:01 -0800904 {MAIN_SWITCH_SECTION}
905
Chris Parsons944e7d02021-03-11 11:08:46 -0500906 # This target was not requested via cquery, and thus must be a dependency
907 # of a requested target.
908 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400909`
Cole Faustb85d1a12022-11-08 18:14:01 -0800910 replacer := strings.NewReplacer(
911 "{TARGET_PRODUCT}", context.targetProduct,
912 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
913 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
914 "{FUNCTION_DEF_SECTION}", functionDefSection,
915 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400916
Cole Faustb85d1a12022-11-08 18:14:01 -0800917 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400918}
919
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200920// Returns a path containing build-related metadata required for interfacing
921// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400922func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200923 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500924}
925
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200926// Returns the path where the contents of the @soong_injection repository live.
927// It is used by Soong to tell Bazel things it cannot over the command line.
928func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200929 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200930}
931
932// Returns the path of the synthetic Bazel workspace that contains a symlink
933// forest composed the whole source tree and BUILD files generated by bp2build.
934func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200935 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200936}
937
Jingwen Chen8c523582021-06-01 11:19:53 +0000938// Returns the path to the top level out dir ($OUT_DIR).
939func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200940 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000941}
942
Sasha Smundak4975c822022-11-16 15:28:18 -0800943const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
944
945var (
946 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
947 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
948 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
949)
950
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400951// Issues commands to Bazel to receive results for all cquery requests
952// queued in the BazelContext.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800953func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -0800954 if ctx != nil {
955 ctx.EventHandler.Begin("bazel")
956 defer ctx.EventHandler.End("bazel")
957 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400958
Sasha Smundak4975c822022-11-16 15:28:18 -0800959 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
960 if err := os.MkdirAll(metricsDir, 0777); err != nil {
961 return err
962 }
963 }
964 context.results = make(map[cqueryKey]string)
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500965 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -0800966 return err
967 }
968 if err := context.runAquery(config, ctx); err != nil {
969 return err
970 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500971 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -0800972 return err
973 }
974
975 // Clear requests.
976 context.requests = map[cqueryKey]bool{}
977 return nil
978}
979
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500980func (context *mixedBuildBazelContext) runCquery(config Config, ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -0800981 if ctx != nil {
982 ctx.EventHandler.Begin("cquery")
983 defer ctx.EventHandler.End("cquery")
984 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200985 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200986 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
987 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
988 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -0500989 if err != nil {
990 return err
991 }
992 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800993 if err := os.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200994 return err
995 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800996 if err := os.WriteFile(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400997 return err
998 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800999 if err := os.WriteFile(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001000 return err
1001 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001002 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Sasha Smundak0e87b182022-12-01 11:46:11 -08001003 if err := os.WriteFile(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001004 return err
1005 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001006
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001007 cqueryCommandWithFlag := context.createBazelCommand(config, context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001008 "--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
Wei Licbd181c2022-11-16 08:59:23 -08001009 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCommandWithFlag)
1010 if cqueryErr != nil {
1011 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001012 }
Jason Wu52cd1942022-09-08 15:37:57 +00001013 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", printableCqueryCommand(cqueryCommandWithFlag))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001014 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001015 return err
1016 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001017 cqueryResults := map[string]string{}
1018 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1019 if strings.Contains(outputLine, ">>") {
1020 splitLine := strings.SplitN(outputLine, ">>", 2)
1021 cqueryResults[splitLine[0]] = splitLine[1]
1022 }
1023 }
Usta Shrestha902fd172022-03-02 15:27:49 -05001024 for val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001025 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001026 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001027 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001028 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001029 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001030 }
1031 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001032 return nil
1033}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001034
Sasha Smundak39a301c2022-12-29 17:11:49 -08001035func (context *mixedBuildBazelContext) runAquery(config Config, ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -08001036 if ctx != nil {
1037 ctx.EventHandler.Begin("aquery")
1038 defer ctx.EventHandler.End("aquery")
1039 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001040 // Issue an aquery command to retrieve action information about the bazel build tree.
1041 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001042 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1043 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001044 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001045 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001046 extraFlags = append(extraFlags, "--collect_code_coverage")
1047 paths := make([]string, 0, 2)
1048 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001049 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001050 // TODO(b/259404593) convert path wildcard to regex values
1051 if p[i] == "*" {
1052 p[i] = ".*"
1053 }
1054 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001055 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1056 }
1057 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1058 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1059 }
1060 if len(paths) > 0 {
1061 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001062 }
1063 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001064 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
Sasha Smundak4975c822022-11-16 15:28:18 -08001065 extraFlags...))
1066 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001067 return err
1068 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001069 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
1070 return err
1071}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001072
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001073func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -08001074 if ctx != nil {
1075 ctx.EventHandler.Begin("symlinks")
1076 defer ctx.EventHandler.End("symlinks")
1077 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001078 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1079 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1080 // but some of symlinks may be required to resolve source dependencies of the build.
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001081 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd))
Sasha Smundak4975c822022-11-16 15:28:18 -08001082 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001083}
Chris Parsonsa798d962020-10-12 23:44:08 -04001084
Sasha Smundak39a301c2022-12-29 17:11:49 -08001085func (context *mixedBuildBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001086 return context.buildStatements
1087}
1088
Sasha Smundak39a301c2022-12-29 17:11:49 -08001089func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001090 return context.depsets
1091}
1092
Sasha Smundak39a301c2022-12-29 17:11:49 -08001093func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001094 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001095}
1096
Chris Parsonsa798d962020-10-12 23:44:08 -04001097// Singleton used for registering BUILD file ninja dependencies (needed
1098// for correctness of builds which use Bazel.
1099func BazelSingleton() Singleton {
1100 return &bazelSingleton{}
1101}
1102
1103type bazelSingleton struct{}
1104
1105func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001106 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001107 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001108 return
1109 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001110
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001111 // Add ninja file dependencies for files which all bazel invocations require.
1112 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001113 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001114 ctx.AddNinjaFileDeps(bazelBuildList)
1115
Sasha Smundak0e87b182022-12-01 11:46:11 -08001116 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001117 if err != nil {
1118 ctx.Errorf(err.Error())
1119 }
1120 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1121 for _, file := range files {
1122 ctx.AddNinjaFileDeps(file)
1123 }
1124
Chris Parsons1a7aca02022-04-25 22:35:15 -04001125 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1126 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001127 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001128 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1129 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001130 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1131 }
1132 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001133 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1134 if artifactPath == "bazel-out/volatile-status.txt" {
1135 // See https://bazel.build/docs/user-manual#workspace-status
1136 orderOnlies = append(orderOnlies, pathInBazelOut)
1137 } else {
1138 outputs = append(outputs, pathInBazelOut)
1139 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001140 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001141 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001142 ctx.Build(pctx, BuildParams{
1143 Rule: blueprint.Phony,
1144 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1145 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001146 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001147 })
1148 }
1149
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001150 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1151 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001152 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -07001153 if len(buildStatement.Command) > 0 {
1154 rule := NewRuleBuilder(pctx, ctx)
1155 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1156 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1157 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1158 continue
1159 }
1160 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1161 // and thus require special treatment. If BuildStatement were an interface implementing
1162 // buildRule(ctx) function, the code here would just call it.
1163 // Unfortunately, the BuildStatement is defined in
1164 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1165 // because this would cause circular dependency. So, until we move aquery processing
1166 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001167 switch buildStatement.Mnemonic {
1168 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001169 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1170 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001171 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001172 // build-runfiles arguments are the manifest file and the target directory
1173 // where it creates the symlink tree according to this manifest (and then
1174 // writes the MANIFEST file to it).
1175 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1176 outManifestPath := outManifest.String()
1177 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1178 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1179 }
1180 outDir := filepath.Dir(outManifestPath)
1181 ctx.Build(pctx, BuildParams{
1182 Rule: buildRunfilesRule,
1183 Output: outManifest,
1184 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1185 Description: "symlink tree for " + outDir,
1186 Args: map[string]string{
1187 "outDir": outDir,
1188 },
1189 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001190 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001191 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001192 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001193 }
1194}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001195
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001196// Register bazel-owned build statements (obtained from the aquery invocation).
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001197func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001198 // executionRoot is the action cwd.
1199 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1200
1201 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1202 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001203 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001204 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001205 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001206 }
1207 cmd.Text("&&")
1208 }
1209
1210 for _, pair := range buildStatement.Env {
1211 // Set per-action env variables, if any.
1212 cmd.Flag(pair.Key + "=" + pair.Value)
1213 }
1214
1215 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001216 if len(buildStatement.Command) > 16*1024 {
1217 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1218 WriteFileRule(ctx, commandFile, buildStatement.Command)
1219
1220 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1221 } else {
1222 cmd.Text(buildStatement.Command)
1223 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001224
1225 for _, outputPath := range buildStatement.OutputPaths {
1226 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1227 }
1228 for _, inputPath := range buildStatement.InputPaths {
1229 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1230 }
1231 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1232 otherDepsetName := bazelDepsetName(inputDepsetHash)
1233 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1234 }
1235
1236 if depfile := buildStatement.Depfile; depfile != nil {
1237 // The paths in depfile are relative to `executionRoot`.
1238 // Hence, they need to be corrected by replacing "bazel-out"
1239 // with the full `bazelOutDir`.
1240 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1241 // would be deemed missing.
1242 // (Note: The regexp uses a capture group because the version of sed
1243 // does not support a look-behind pattern.)
1244 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1245 bazelOutDir, *depfile)
1246 cmd.Text(replacement)
1247 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1248 }
1249
1250 for _, symlinkPath := range buildStatement.SymlinkPaths {
1251 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1252 }
1253}
1254
Chris Parsons8d6e4332021-02-22 16:13:50 -05001255func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001256 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001257}
1258
Chris Parsons787fb362021-10-14 18:43:51 -04001259func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001260 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001261 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001262 if key.configKey.osType.Class == Device {
1263 // For the generic Android, the expected result is "target|android", which
1264 // corresponds to the product_variable_config named "android_target" in
1265 // build/bazel/platforms/BUILD.bazel.
1266 arch = "target"
1267 } else {
1268 // Use host platform, which is currently hardcoded to be x86_64.
1269 arch = "x86_64"
1270 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001271 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001272 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001273 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001274 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001275 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001276 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001277 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -04001278}
1279
Chris Parsonsf874e462022-05-10 13:50:12 -04001280func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001281 return configKey{
1282 // use string because Arch is not a valid key in go
1283 arch: ctx.Arch().String(),
1284 osType: ctx.Os(),
1285 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001286}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001287
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001288func bazelDepsetName(contentHash string) string {
1289 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001290}
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001291
1292func EnvironmentVarsFile(config Config) string {
1293 return fmt.Sprintf(bazel.GeneratedBazelFileWarning+`
1294_env = %s
1295
1296env = _env
1297`,
1298 starlark_fmt.PrintStringList(allowedBazelEnvironmentVars, 0),
1299 )
1300}