blob: ad21a2e9b7ffe1accbac07826866282db730c989 [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{
Sam Delmerico700b4d32023-02-10 16:46:28 -050048 // clang-tidy
Sam Delmericocb3c52c2023-02-03 17:40:08 -050049 "ALLOW_LOCAL_TIDY_TRUE",
50 "DEFAULT_TIDY_HEADER_DIRS",
51 "TIDY_TIMEOUT",
52 "WITH_TIDY",
53 "WITH_TIDY_FLAGS",
Sam Delmerico700b4d32023-02-10 16:46:28 -050054 "TIDY_EXTERNAL_VENDOR",
55
Sam Delmericocb3c52c2023-02-03 17:40:08 -050056 "SKIP_ABI_CHECKS",
57 "UNSAFE_DISABLE_APEX_ALLOWED_DEPS_CHECK",
58 "AUTO_ZERO_INITIALIZE",
59 "AUTO_PATTERN_INITIALIZE",
60 "AUTO_UNINITIALIZE",
61 "USE_CCACHE",
62 "LLVM_NEXT",
63 "ALLOW_UNKNOWN_WARNING_OPTION",
64
65 // Overrides the version in the apex_manifest.json. The version is unique for
66 // each branch (internal, aosp, mainline releases, dessert releases). This
67 // enables modules built on an older branch to be installed against a newer
68 // device for development purposes.
69 "OVERRIDE_APEX_MANIFEST_DEFAULT_VERSION",
70 }
Sasha Smundak1da064c2022-06-08 16:36:16 -070071)
72
Chris Parsonsf874e462022-05-10 13:50:12 -040073func init() {
74 RegisterMixedBuildsMutator(InitRegistrationContext)
75}
76
77func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammer337e9032022-08-03 15:49:43 -040078 ctx.FinalDepsMutators(func(ctx RegisterMutatorsContext) {
Chris Parsonsf874e462022-05-10 13:50:12 -040079 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
80 })
81}
82
83func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
84 if m := ctx.Module(); m.Enabled() {
85 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
86 if mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx) {
87 mixedBuildMod.QueueBazelCall(ctx)
88 }
89 }
90 }
91}
92
Liz Kammerf29df7c2021-04-02 13:37:39 -040093type cqueryRequest interface {
94 // Name returns a string name for this request type. Such request type names must be unique,
95 // and must only consist of alphanumeric characters.
96 Name() string
97
98 // StarlarkFunctionBody returns a starlark function body to process this request type.
99 // The returned string is the body of a Starlark function which obtains
100 // all request-relevant information about a target and returns a string containing
101 // this information.
102 // The function should have the following properties:
Cole Faust97d15272022-11-22 14:08:59 -0800103 // - The arguments are `target` (a configured target) and `id_string` (the label + configuration).
Liz Kammerf29df7c2021-04-02 13:37:39 -0400104 // - The return value must be a string.
105 // - The function body should not be indented outside of its own scope.
106 StarlarkFunctionBody() string
107}
108
Chris Parsons787fb362021-10-14 18:43:51 -0400109// Portion of cquery map key to describe target configuration.
110type configKey struct {
Liz Kammer0940b892022-03-18 15:55:04 -0400111 arch string
112 osType OsType
Chris Parsons787fb362021-10-14 18:43:51 -0400113}
114
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700115func (c configKey) String() string {
116 return fmt.Sprintf("%s::%s", c.arch, c.osType)
117}
118
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400119// Map key to describe bazel cquery requests.
120type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400121 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400122 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400123 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400124}
125
Chris Parsons86dc2c22022-09-28 14:58:41 -0400126func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
127 if strings.HasPrefix(label, "//") {
128 // Normalize Bazel labels to specify main repository explicitly.
129 label = "@" + label
130 }
131 return cqueryKey{label, cqueryRequest, cfgKey}
132}
133
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700134func (c cqueryKey) String() string {
135 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700136}
137
Chris Parsonsf874e462022-05-10 13:50:12 -0400138// BazelContext is a context object useful for interacting with Bazel during
139// the course of a build. Use of Bazel to evaluate part of the build graph
140// is referred to as a "mixed build". (Some modules are managed by Soong,
141// some are managed by Bazel). To facilitate interop between these build
142// subgraphs, Soong may make requests to Bazel and evaluate their responses
143// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400144type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400145 // Add a cquery request to the bazel request queue. All queued requests
146 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
147 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
148
149 // ** Cquery Results Retrieval Functions
150 // The below functions pertain to retrieving cquery results from a prior
151 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400152
153 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400154 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500155
Chris Parsons944e7d02021-03-11 11:08:46 -0500156 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400157 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400158
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000159 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400160 // TODO(b/232976601): Remove.
161 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000162
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700163 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400164 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700165
Sasha Smundakedd16662022-10-07 14:44:50 -0700166 // Returns the results of the GetCcUnstrippedInfo query
167 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
168
Chris Parsonsf874e462022-05-10 13:50:12 -0400169 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400170
171 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800172 // queued in the BazelContext. The ctx argument is optional and is only
173 // used for performance data collection
174 InvokeBazel(config Config, ctx *Context) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400175
Chris Parsonsad876012022-08-20 14:48:32 -0400176 // Returns true if Bazel handling is enabled for the module with the given name.
177 // Note that this only implies "bazel mixed build" allowlisting. The caller
178 // should independently verify the module is eligible for Bazel handling
179 // (for example, that it is MixedBuildBuildable).
Sasha Smundak39a301c2022-12-29 17:11:49 -0800180 IsModuleNameAllowed(moduleName string) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500181
182 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
183 OutputBase() string
184
185 // Returns build statements which should get registered to reflect Bazel's outputs.
186 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400187
188 // Returns the depsets defined in Bazel's aquery response.
189 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400190}
191
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400192type bazelRunner interface {
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500193 createBazelCommand(config Config, paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) *exec.Cmd
Jason Wu52cd1942022-09-08 15:37:57 +0000194 issueBazelCommand(bazelCmd *exec.Cmd) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400195}
196
197type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000198 homeDir string
199 bazelPath string
200 outputBase string
201 workspaceDir string
202 soongOutDir string
203 metricsDir string
204 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400205}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400206
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400207// A context object which tracks queued requests that need to be made to Bazel,
208// and their results after the requests have been made.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800209type mixedBuildBazelContext struct {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400210 bazelRunner
211 paths *bazelPaths
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400212 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
213 requestMutex sync.Mutex // requests can be written in parallel
214
215 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500216
217 // Build statements which should get registered to reflect Bazel's outputs.
218 buildStatements []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400219
220 // Depsets which should be used for Bazel's build statements.
221 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400222
223 // Per-module allowlist/denylist functionality to control whether analysis of
224 // modules are handled by Bazel. For modules which do not have a Bazel definition
225 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
226 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
227 // Per-module denylist to opt modules out of bazel handling.
228 bazelDisabledModules map[string]bool
229 // Per-module allowlist to opt modules in to bazel handling.
230 bazelEnabledModules map[string]bool
231 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
232 modulesDefaultToBazel bool
Cole Faustb85d1a12022-11-08 18:14:01 -0800233
234 targetProduct string
235 targetBuildVariant string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400236}
237
Sasha Smundak39a301c2022-12-29 17:11:49 -0800238var _ BazelContext = &mixedBuildBazelContext{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400239
240// A bazel context to use when Bazel is disabled.
241type noopBazelContext struct{}
242
243var _ BazelContext = noopBazelContext{}
244
245// A bazel context to use for tests.
246type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400247 OutputBaseDir string
248
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000249 LabelToOutputFiles map[string][]string
250 LabelToCcInfo map[string]cquery.CcInfo
251 LabelToPythonBinary map[string]string
Liz Kammerbe6a7122022-11-04 16:05:11 -0400252 LabelToApexInfo map[string]cquery.ApexInfo
Sasha Smundakedd16662022-10-07 14:44:50 -0700253 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400254}
255
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700256func (m MockBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400257 panic("unimplemented")
Chris Parsons8d6e4332021-02-22 16:13:50 -0500258}
259
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700260func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500261 result, ok := m.LabelToOutputFiles[label]
262 if !ok {
263 return []string{}, fmt.Errorf("no target with label %q in LabelToOutputFiles", label)
264 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400265 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400266}
267
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700268func (m MockBazelContext) GetCcInfo(label string, _ configKey) (cquery.CcInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500269 result, ok := m.LabelToCcInfo[label]
270 if !ok {
271 return cquery.CcInfo{}, fmt.Errorf("no target with label %q in LabelToCcInfo", label)
272 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400273 return result, nil
274}
275
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700276func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500277 result, ok := m.LabelToPythonBinary[label]
278 if !ok {
279 return "", fmt.Errorf("no target with label %q in LabelToPythonBinary", label)
280 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400281 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000282}
283
Liz Kammerbe6a7122022-11-04 16:05:11 -0400284func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500285 result, ok := m.LabelToApexInfo[label]
286 if !ok {
287 return cquery.ApexInfo{}, fmt.Errorf("no target with label %q in LabelToApexInfo", label)
288 }
Liz Kammer0e255ef2022-11-04 16:07:04 -0400289 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700290}
291
Sasha Smundakedd16662022-10-07 14:44:50 -0700292func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500293 result, ok := m.LabelToCcBinary[label]
294 if !ok {
295 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no target with label %q in LabelToCcBinary", label)
296 }
Sasha Smundakedd16662022-10-07 14:44:50 -0700297 return result, nil
298}
299
Sasha Smundak0e87b182022-12-01 11:46:11 -0800300func (m MockBazelContext) InvokeBazel(_ Config, _ *Context) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400301 panic("unimplemented")
302}
303
Sasha Smundak39a301c2022-12-29 17:11:49 -0800304func (m MockBazelContext) IsModuleNameAllowed(_ string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400305 return true
306}
307
Liz Kammera92e8442021-04-07 20:25:21 -0400308func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500309
310func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
311 return []bazel.BuildStatement{}
312}
313
Chris Parsons1a7aca02022-04-25 22:35:15 -0400314func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
315 return []bazel.AqueryDepset{}
316}
317
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400318var _ BazelContext = MockBazelContext{}
319
Sasha Smundak39a301c2022-12-29 17:11:49 -0800320func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400321 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400322 bazelCtx.requestMutex.Lock()
323 defer bazelCtx.requestMutex.Unlock()
324 bazelCtx.requests[key] = true
325}
326
Sasha Smundak39a301c2022-12-29 17:11:49 -0800327func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400328 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400329 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500330 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400331
Chris Parsonsf874e462022-05-10 13:50:12 -0400332 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400333 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400334 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400335}
336
Sasha Smundak39a301c2022-12-29 17:11:49 -0800337func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400338 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400339 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000340 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400341 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000342 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400343 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 +0000344}
345
Sasha Smundak39a301c2022-12-29 17:11:49 -0800346func (bazelCtx *mixedBuildBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400347 key := makeCqueryKey(label, cquery.GetPythonBinary, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400348 if rawString, ok := bazelCtx.results[key]; ok {
349 bazelOutput := strings.TrimSpace(rawString)
350 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
351 }
352 return "", fmt.Errorf("no bazel response found for %v", key)
353}
354
Sasha Smundak39a301c2022-12-29 17:11:49 -0800355func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400356 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700357 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500358 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700359 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400360 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700361}
362
Sasha Smundak39a301c2022-12-29 17:11:49 -0800363func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700364 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
365 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500366 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700367 }
368 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
369}
370
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700371func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500372 panic("unimplemented")
373}
374
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700375func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500376 panic("unimplemented")
377}
378
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700379func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400380 panic("unimplemented")
381}
382
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700383func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000384 panic("unimplemented")
385}
386
Liz Kammerbe6a7122022-11-04 16:05:11 -0400387func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700388 panic("unimplemented")
389}
390
Sasha Smundakedd16662022-10-07 14:44:50 -0700391func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
392 //TODO implement me
393 panic("implement me")
394}
395
Sasha Smundak0e87b182022-12-01 11:46:11 -0800396func (n noopBazelContext) InvokeBazel(_ Config, _ *Context) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400397 panic("unimplemented")
398}
399
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500400func (m noopBazelContext) OutputBase() string {
401 return ""
402}
403
Sasha Smundak39a301c2022-12-29 17:11:49 -0800404func (n noopBazelContext) IsModuleNameAllowed(_ string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400405 return false
406}
407
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500408func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
409 return []bazel.BuildStatement{}
410}
411
Chris Parsons1a7aca02022-04-25 22:35:15 -0400412func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
413 return []bazel.AqueryDepset{}
414}
415
Cole Faust705968d2022-12-14 11:32:05 -0800416func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400417 disabledModules := map[string]bool{}
418 enabledModules := map[string]bool{}
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800419 addToStringSet := func(set map[string]bool, items []string) {
420 for _, item := range items {
421 set[item] = true
422 }
423 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400424
Cole Faust705968d2022-12-14 11:32:05 -0800425 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400426 case BazelProdMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800427 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800428 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000429 enabledModules[enabledAdHocModule] = true
430 }
MarkDacekb78465d2022-10-18 20:10:16 +0000431 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400432 // Staging mode includes all prod modules plus all staging modules.
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800433 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
434 addToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800435 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000436 enabledModules[enabledAdHocModule] = true
437 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400438 case BazelDevMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800439 addToStringSet(disabledModules, allowlists.MixedBuildsDisabledList)
Chris Parsonsef615e52022-08-18 22:04:11 -0400440 default:
Cole Faust705968d2022-12-14 11:32:05 -0800441 panic("Expected BazelProdMode, BazelStagingMode, or BazelDevMode")
442 }
443 return enabledModules, disabledModules
444}
445
446func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
447 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
448 enabledList := make([]string, 0, len(enabledModules))
449 for module := range enabledModules {
450 if !disabledModules[module] {
451 enabledList = append(enabledList, module)
452 }
453 }
454 sort.Strings(enabledList)
455 return enabledList
456}
457
458func NewBazelContext(c *config) (BazelContext, error) {
459 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode && c.BuildMode != BazelDevMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400460 return noopBazelContext{}, nil
461 }
462
Cole Faust705968d2022-12-14 11:32:05 -0800463 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
464
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800465 paths := bazelPaths{
466 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400467 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800468 var missing []string
469 vars := []struct {
470 name string
471 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000472
473 // True if the environment variable needs to be tracked so that changes to the variable
474 // cause the ninja file to be regenerated, false otherwise. False should only be set for
475 // environment variables that have no effect on the generated ninja file.
476 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800477 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000478 {"BAZEL_HOME", &paths.homeDir, true},
479 {"BAZEL_PATH", &paths.bazelPath, true},
480 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
481 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
482 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
483 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800484 }
485 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000486 if v.track {
487 if s := c.Getenv(v.name); len(s) > 1 {
488 *v.ptr = s
489 continue
490 }
491 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800492 *v.ptr = s
493 } else {
494 missing = append(missing, v.name)
495 }
496 }
497 if len(missing) > 0 {
498 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
499 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800500
501 targetBuildVariant := "user"
502 if c.Eng() {
503 targetBuildVariant = "eng"
504 } else if c.Debuggable() {
505 targetBuildVariant = "userdebug"
506 }
507 targetProduct := "unknown"
508 if c.HasDeviceProduct() {
509 targetProduct = c.DeviceProduct()
510 }
511
Sasha Smundak39a301c2022-12-29 17:11:49 -0800512 return &mixedBuildBazelContext{
Chris Parsonsad876012022-08-20 14:48:32 -0400513 bazelRunner: &builtinBazelRunner{},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800514 paths: &paths,
Chris Parsonsad876012022-08-20 14:48:32 -0400515 requests: make(map[cqueryKey]bool),
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800516 modulesDefaultToBazel: c.BuildMode == BazelDevMode,
Chris Parsonsef615e52022-08-18 22:04:11 -0400517 bazelEnabledModules: enabledModules,
Chris Parsonsad876012022-08-20 14:48:32 -0400518 bazelDisabledModules: disabledModules,
Cole Faustb85d1a12022-11-08 18:14:01 -0800519 targetProduct: targetProduct,
520 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400521 }, nil
522}
523
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400524func (p *bazelPaths) BazelMetricsDir() string {
525 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000526}
527
Sasha Smundak39a301c2022-12-29 17:11:49 -0800528func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400529 if context.bazelDisabledModules[moduleName] {
530 return false
531 }
532 if context.bazelEnabledModules[moduleName] {
533 return true
534 }
535 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400536}
537
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400538func pwdPrefix() string {
539 // Darwin doesn't have /proc
540 if runtime.GOOS != "darwin" {
541 return "PWD=/proc/self/cwd"
542 }
543 return ""
544}
545
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400546type bazelCommand struct {
547 command string
548 // query or label
549 expression string
550}
551
552type mockBazelRunner struct {
553 bazelCommandResults map[bazelCommand]string
Jason Wu52cd1942022-09-08 15:37:57 +0000554 // use *exec.Cmd as a key to get the bazelCommand, the map will be used in issueBazelCommand()
555 // Register createBazelCommand() invocations. Later, an
556 // issueBazelCommand() invocation can be mapped to the *exec.Cmd instance
557 // and then to the expected result via bazelCommandResults
558 tokens map[*exec.Cmd]bazelCommand
559 commands []bazelCommand
560 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400561}
562
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500563func (r *mockBazelRunner) createBazelCommand(_ Config, _ *bazelPaths, _ bazel.RunName,
Jason Wu52cd1942022-09-08 15:37:57 +0000564 command bazelCommand, extraFlags ...string) *exec.Cmd {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400565 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700566 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Jason Wu52cd1942022-09-08 15:37:57 +0000567 cmd := &exec.Cmd{}
568 if r.tokens == nil {
569 r.tokens = make(map[*exec.Cmd]bazelCommand)
570 }
571 r.tokens[cmd] = command
572 return cmd
573}
574
575func (r *mockBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
576 if command, ok := r.tokens[bazelCmd]; ok {
577 return r.bazelCommandResults[command], "", nil
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400578 }
579 return "", "", nil
580}
581
582type builtinBazelRunner struct{}
583
Chris Parsons808d84c2021-03-09 20:43:32 -0500584// Issues the given bazel command with given build label and additional flags.
585// Returns (stdout, stderr, error). The first and second return values are strings
586// containing the stdout and stderr of the run command, and an error is returned if
587// the invocation returned an error code.
Jason Wu52cd1942022-09-08 15:37:57 +0000588func (r *builtinBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
589 stderr := &bytes.Buffer{}
590 bazelCmd.Stderr = stderr
591 if output, err := bazelCmd.Output(); err != nil {
592 return "", string(stderr.Bytes()),
Sasha Smundak0e87b182022-12-01 11:46:11 -0800593 fmt.Errorf("bazel command failed: %s\n---command---\n%s\n---env---\n%s\n---stderr---\n%s---",
594 err, bazelCmd, strings.Join(bazelCmd.Env, "\n"), stderr)
Jason Wu52cd1942022-09-08 15:37:57 +0000595 } else {
596 return string(output), string(stderr.Bytes()), nil
597 }
598}
599
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500600func (r *builtinBazelRunner) createBazelCommand(config Config, paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Jason Wu52cd1942022-09-08 15:37:57 +0000601 extraFlags ...string) *exec.Cmd {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000602 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000603 "--output_base=" + absolutePath(paths.outputBase),
604 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700605 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700606 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700607 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400608
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700609 // Set default platforms to canonicalized values for mixed builds requests.
610 // If these are set in the bazelrc, they will have values that are
611 // non-canonicalized to @sourceroot labels, and thus be invalid when
612 // referenced from the buildroot.
613 //
614 // The actual platform values here may be overridden by configuration
615 // transitions from the buildroot.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700616 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Cole Faustb85d1a12022-11-08 18:14:01 -0800617
618 // We don't need to set --host_platforms because it's set in bazelrc files
619 // that the bazel shell script wrapper passes
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700620
621 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
622 "--experimental_repository_disable_download",
623
624 // Suppress noise
625 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500626 "--noshow_progress",
627 "--norun_validations",
628 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400629 cmdFlags = append(cmdFlags, extraFlags...)
630
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400631 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200632 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700633 extraEnv := []string{
634 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200635 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700636 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700637 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000638 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700639 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500640 // Disables local host detection of gcc; toolchain information is defined
641 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700642 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
643 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500644 for _, envvar := range allowedBazelEnvironmentVars {
645 val := config.Getenv(envvar)
646 if val == "" {
647 continue
648 }
649 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
650 }
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700651 bazelCmd.Env = append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400652
Jason Wu52cd1942022-09-08 15:37:57 +0000653 return bazelCmd
654}
655
656func printableCqueryCommand(bazelCmd *exec.Cmd) string {
657 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(bazelCmd.Args, "\" \"") + "\""
658 return outputString
659
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400660}
661
Sasha Smundak39a301c2022-12-29 17:11:49 -0800662func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500663 // TODO(cparsons): Define configuration transitions programmatically based
664 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400665 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500666#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400667# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500668#####################################################
669
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400670def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800671 if attr.os == "android" and attr.arch == "target":
672 target = "{PRODUCT}-{VARIANT}"
673 else:
674 target = "{PRODUCT}-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500675 return {
Cole Faustb85d1a12022-11-08 18:14:01 -0800676 "//command_line_option:platforms": "@soong_injection//product_config_platforms/products/{PRODUCT}-{VARIANT}:%s" % target,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500677 }
678
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400679_config_node_transition = transition(
680 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500681 inputs = [],
682 outputs = [
683 "//command_line_option:platforms",
684 ],
685)
686
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400687def _passthrough_rule_impl(ctx):
688 return [DefaultInfo(files = depset(ctx.files.deps))]
689
690config_node = rule(
691 implementation = _passthrough_rule_impl,
692 attrs = {
693 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400694 "os" : attr.string(mandatory = True),
695 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400696 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
697 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500698)
699
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400700
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500701# Rule representing the root of the build, to depend on all Bazel targets that
702# are required for the build. Building this target will build the entire Bazel
703# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400704mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400705 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500706 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400707 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500708 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400709)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500710
711def _phony_root_impl(ctx):
712 return []
713
714# Rule to depend on other targets but build nothing.
715# This is useful as follows: building a target of this rule will generate
716# symlink forests for all dependencies of the target, without executing any
717# actions of the build.
718phony_root = rule(
719 implementation = _phony_root_impl,
720 attrs = {"deps" : attr.label_list()},
721)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400722`
Cole Faustb85d1a12022-11-08 18:14:01 -0800723
724 productReplacer := strings.NewReplacer(
725 "{PRODUCT}", context.targetProduct,
726 "{VARIANT}", context.targetBuildVariant)
727
728 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400729}
730
Sasha Smundak39a301c2022-12-29 17:11:49 -0800731func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500732 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
733 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400734 formatString := `
735# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400736load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
737
738%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400739
740mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400741 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000742 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400743)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500744
745phony_root(name = "phonyroot",
746 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000747 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500748)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400749`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400750 configNodeFormatString := `
751config_node(name = "%s",
752 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400753 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400754 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000755 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400756)
757`
758
759 configNodesSection := ""
760
Chris Parsons787fb362021-10-14 18:43:51 -0400761 labelsByConfig := map[string][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400762 for val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200763 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400764 configString := getConfigString(val)
765 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400766 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400767
Jingwen Chen1e347862021-09-02 12:11:49 +0000768 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400769 for configString, labels := range labelsByConfig {
770 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{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400800 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)
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500968 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -0800969 return err
970 }
971 if err := context.runAquery(config, ctx); err != nil {
972 return err
973 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500974 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -0800975 return err
976 }
977
978 // Clear requests.
979 context.requests = map[cqueryKey]bool{}
980 return nil
981}
982
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500983func (context *mixedBuildBazelContext) runCquery(config Config, 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 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800996 if err := os.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200997 return err
998 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800999 if err := os.WriteFile(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001000 return err
1001 }
Sasha Smundak0e87b182022-12-01 11:46:11 -08001002 if err := os.WriteFile(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")
Sasha Smundak0e87b182022-12-01 11:46:11 -08001006 if err := os.WriteFile(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
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001010 cqueryCommandWithFlag := context.createBazelCommand(config, 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 }
Usta Shrestha902fd172022-03-02 15:27:49 -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
Sasha Smundak39a301c2022-12-29 17:11:49 -08001038func (context *mixedBuildBazelContext) runAquery(config Config, ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -08001039 if ctx != nil {
1040 ctx.EventHandler.Begin("aquery")
1041 defer ctx.EventHandler.End("aquery")
1042 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001043 // Issue an aquery command to retrieve action information about the bazel build tree.
1044 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001045 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1046 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001047 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001048 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001049 extraFlags = append(extraFlags, "--collect_code_coverage")
1050 paths := make([]string, 0, 2)
1051 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001052 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001053 // TODO(b/259404593) convert path wildcard to regex values
1054 if p[i] == "*" {
1055 p[i] = ".*"
1056 }
1057 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001058 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1059 }
1060 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1061 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1062 }
1063 if len(paths) > 0 {
1064 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001065 }
1066 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001067 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
Sasha Smundak4975c822022-11-16 15:28:18 -08001068 extraFlags...))
1069 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001070 return err
1071 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001072 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
1073 return err
1074}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001075
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001076func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx *Context) error {
Sasha Smundak4975c822022-11-16 15:28:18 -08001077 if ctx != nil {
1078 ctx.EventHandler.Begin("symlinks")
1079 defer ctx.EventHandler.End("symlinks")
1080 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001081 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1082 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1083 // but some of symlinks may be required to resolve source dependencies of the build.
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001084 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd))
Sasha Smundak4975c822022-11-16 15:28:18 -08001085 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001086}
Chris Parsonsa798d962020-10-12 23:44:08 -04001087
Sasha Smundak39a301c2022-12-29 17:11:49 -08001088func (context *mixedBuildBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001089 return context.buildStatements
1090}
1091
Sasha Smundak39a301c2022-12-29 17:11:49 -08001092func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001093 return context.depsets
1094}
1095
Sasha Smundak39a301c2022-12-29 17:11:49 -08001096func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001097 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001098}
1099
Chris Parsonsa798d962020-10-12 23:44:08 -04001100// Singleton used for registering BUILD file ninja dependencies (needed
1101// for correctness of builds which use Bazel.
1102func BazelSingleton() Singleton {
1103 return &bazelSingleton{}
1104}
1105
1106type bazelSingleton struct{}
1107
1108func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001109 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001110 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001111 return
1112 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001113
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001114 // Add ninja file dependencies for files which all bazel invocations require.
1115 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001116 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001117 ctx.AddNinjaFileDeps(bazelBuildList)
1118
Sasha Smundak0e87b182022-12-01 11:46:11 -08001119 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001120 if err != nil {
1121 ctx.Errorf(err.Error())
1122 }
1123 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1124 for _, file := range files {
1125 ctx.AddNinjaFileDeps(file)
1126 }
1127
Chris Parsons1a7aca02022-04-25 22:35:15 -04001128 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1129 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001130 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001131 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1132 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001133 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1134 }
1135 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001136 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1137 if artifactPath == "bazel-out/volatile-status.txt" {
1138 // See https://bazel.build/docs/user-manual#workspace-status
1139 orderOnlies = append(orderOnlies, pathInBazelOut)
1140 } else {
1141 outputs = append(outputs, pathInBazelOut)
1142 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001143 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001144 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001145 ctx.Build(pctx, BuildParams{
1146 Rule: blueprint.Phony,
1147 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1148 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001149 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001150 })
1151 }
1152
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001153 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1154 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001155 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -07001156 if len(buildStatement.Command) > 0 {
1157 rule := NewRuleBuilder(pctx, ctx)
1158 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1159 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1160 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1161 continue
1162 }
1163 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1164 // and thus require special treatment. If BuildStatement were an interface implementing
1165 // buildRule(ctx) function, the code here would just call it.
1166 // Unfortunately, the BuildStatement is defined in
1167 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1168 // because this would cause circular dependency. So, until we move aquery processing
1169 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001170 switch buildStatement.Mnemonic {
1171 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001172 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1173 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001174 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001175 // build-runfiles arguments are the manifest file and the target directory
1176 // where it creates the symlink tree according to this manifest (and then
1177 // writes the MANIFEST file to it).
1178 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1179 outManifestPath := outManifest.String()
1180 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1181 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1182 }
1183 outDir := filepath.Dir(outManifestPath)
1184 ctx.Build(pctx, BuildParams{
1185 Rule: buildRunfilesRule,
1186 Output: outManifest,
1187 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1188 Description: "symlink tree for " + outDir,
1189 Args: map[string]string{
1190 "outDir": outDir,
1191 },
1192 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001193 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001194 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001195 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001196 }
1197}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001198
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001199// Register bazel-owned build statements (obtained from the aquery invocation).
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001200func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001201 // executionRoot is the action cwd.
1202 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1203
1204 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1205 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001206 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001207 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001208 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001209 }
1210 cmd.Text("&&")
1211 }
1212
1213 for _, pair := range buildStatement.Env {
1214 // Set per-action env variables, if any.
1215 cmd.Flag(pair.Key + "=" + pair.Value)
1216 }
1217
1218 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001219 if len(buildStatement.Command) > 16*1024 {
1220 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1221 WriteFileRule(ctx, commandFile, buildStatement.Command)
1222
1223 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1224 } else {
1225 cmd.Text(buildStatement.Command)
1226 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001227
1228 for _, outputPath := range buildStatement.OutputPaths {
1229 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1230 }
1231 for _, inputPath := range buildStatement.InputPaths {
1232 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1233 }
1234 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1235 otherDepsetName := bazelDepsetName(inputDepsetHash)
1236 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1237 }
1238
1239 if depfile := buildStatement.Depfile; depfile != nil {
1240 // The paths in depfile are relative to `executionRoot`.
1241 // Hence, they need to be corrected by replacing "bazel-out"
1242 // with the full `bazelOutDir`.
1243 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1244 // would be deemed missing.
1245 // (Note: The regexp uses a capture group because the version of sed
1246 // does not support a look-behind pattern.)
1247 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1248 bazelOutDir, *depfile)
1249 cmd.Text(replacement)
1250 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1251 }
1252
1253 for _, symlinkPath := range buildStatement.SymlinkPaths {
1254 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1255 }
1256}
1257
Chris Parsons8d6e4332021-02-22 16:13:50 -05001258func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001259 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001260}
1261
Chris Parsons787fb362021-10-14 18:43:51 -04001262func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001263 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001264 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001265 if key.configKey.osType.Class == Device {
1266 // For the generic Android, the expected result is "target|android", which
1267 // corresponds to the product_variable_config named "android_target" in
1268 // build/bazel/platforms/BUILD.bazel.
1269 arch = "target"
1270 } else {
1271 // Use host platform, which is currently hardcoded to be x86_64.
1272 arch = "x86_64"
1273 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001274 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001275 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001276 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001277 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001278 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001279 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001280 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -04001281}
1282
Chris Parsonsf874e462022-05-10 13:50:12 -04001283func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001284 return configKey{
1285 // use string because Arch is not a valid key in go
1286 arch: ctx.Arch().String(),
1287 osType: ctx.Os(),
1288 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001289}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001290
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001291func bazelDepsetName(contentHash string) string {
1292 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001293}
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001294
1295func EnvironmentVarsFile(config Config) string {
1296 return fmt.Sprintf(bazel.GeneratedBazelFileWarning+`
1297_env = %s
1298
1299env = _env
1300`,
1301 starlark_fmt.PrintStringList(allowedBazelEnvironmentVars, 0),
1302 )
1303}