blob: 0880ad5b7decea433f88cd11fe3a9880be6c4365 [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 Kammer690fbac2023-02-10 11:11:17 -050035 "github.com/google/blueprint/metrics"
Liz Kammer8206d4f2021-03-03 16:40:52 -050036
Patrice Arruda05ab2d02020-12-12 06:24:26 +000037 "android/soong/bazel"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040038)
39
Sasha Smundak1da064c2022-06-08 16:36:16 -070040var (
Sasha Smundakc180dbd2022-07-03 14:55:58 -070041 _ = pctx.HostBinToolVariable("bazelBuildRunfilesTool", "build-runfiles")
42 buildRunfilesRule = pctx.AndroidStaticRule("bazelBuildRunfiles", blueprint.RuleParams{
43 Command: "${bazelBuildRunfilesTool} ${in} ${outDir}",
44 Depfile: "",
45 Description: "",
46 CommandDeps: []string{"${bazelBuildRunfilesTool}"},
47 }, "outDir")
Sam Delmericocb3c52c2023-02-03 17:40:08 -050048 allowedBazelEnvironmentVars = []string{
Sam Delmerico700b4d32023-02-10 16:46:28 -050049 // clang-tidy
Sam Delmericocb3c52c2023-02-03 17:40:08 -050050 "ALLOW_LOCAL_TIDY_TRUE",
51 "DEFAULT_TIDY_HEADER_DIRS",
52 "TIDY_TIMEOUT",
53 "WITH_TIDY",
54 "WITH_TIDY_FLAGS",
Sam Delmerico700b4d32023-02-10 16:46:28 -050055 "TIDY_EXTERNAL_VENDOR",
56
Sam Delmericocb3c52c2023-02-03 17:40:08 -050057 "SKIP_ABI_CHECKS",
58 "UNSAFE_DISABLE_APEX_ALLOWED_DEPS_CHECK",
59 "AUTO_ZERO_INITIALIZE",
60 "AUTO_PATTERN_INITIALIZE",
61 "AUTO_UNINITIALIZE",
62 "USE_CCACHE",
63 "LLVM_NEXT",
64 "ALLOW_UNKNOWN_WARNING_OPTION",
65
66 // Overrides the version in the apex_manifest.json. The version is unique for
67 // each branch (internal, aosp, mainline releases, dessert releases). This
68 // enables modules built on an older branch to be installed against a newer
69 // device for development purposes.
70 "OVERRIDE_APEX_MANIFEST_DEFAULT_VERSION",
71 }
Sasha Smundak1da064c2022-06-08 16:36:16 -070072)
73
Chris Parsonsf874e462022-05-10 13:50:12 -040074func init() {
75 RegisterMixedBuildsMutator(InitRegistrationContext)
76}
77
78func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammer337e9032022-08-03 15:49:43 -040079 ctx.FinalDepsMutators(func(ctx RegisterMutatorsContext) {
Chris Parsonsf874e462022-05-10 13:50:12 -040080 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
81 })
82}
83
84func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
85 if m := ctx.Module(); m.Enabled() {
86 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
87 if mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx) {
88 mixedBuildMod.QueueBazelCall(ctx)
89 }
90 }
91 }
92}
93
Liz Kammerf29df7c2021-04-02 13:37:39 -040094type cqueryRequest interface {
95 // Name returns a string name for this request type. Such request type names must be unique,
96 // and must only consist of alphanumeric characters.
97 Name() string
98
99 // StarlarkFunctionBody returns a starlark function body to process this request type.
100 // The returned string is the body of a Starlark function which obtains
101 // all request-relevant information about a target and returns a string containing
102 // this information.
103 // The function should have the following properties:
Cole Faust97d15272022-11-22 14:08:59 -0800104 // - The arguments are `target` (a configured target) and `id_string` (the label + configuration).
Liz Kammerf29df7c2021-04-02 13:37:39 -0400105 // - The return value must be a string.
106 // - The function body should not be indented outside of its own scope.
107 StarlarkFunctionBody() string
108}
109
Chris Parsons787fb362021-10-14 18:43:51 -0400110// Portion of cquery map key to describe target configuration.
111type configKey struct {
Liz Kammer0940b892022-03-18 15:55:04 -0400112 arch string
113 osType OsType
Chris Parsons787fb362021-10-14 18:43:51 -0400114}
115
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700116func (c configKey) String() string {
117 return fmt.Sprintf("%s::%s", c.arch, c.osType)
118}
119
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400120// Map key to describe bazel cquery requests.
121type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400122 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400123 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400124 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400125}
126
Chris Parsons86dc2c22022-09-28 14:58:41 -0400127func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
128 if strings.HasPrefix(label, "//") {
129 // Normalize Bazel labels to specify main repository explicitly.
130 label = "@" + label
131 }
132 return cqueryKey{label, cqueryRequest, cfgKey}
133}
134
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700135func (c cqueryKey) String() string {
136 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700137}
138
Liz Kammer690fbac2023-02-10 11:11:17 -0500139type invokeBazelContext interface {
140 GetEventHandler() *metrics.EventHandler
141}
142
Chris Parsonsf874e462022-05-10 13:50:12 -0400143// BazelContext is a context object useful for interacting with Bazel during
144// the course of a build. Use of Bazel to evaluate part of the build graph
145// is referred to as a "mixed build". (Some modules are managed by Soong,
146// some are managed by Bazel). To facilitate interop between these build
147// subgraphs, Soong may make requests to Bazel and evaluate their responses
148// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400149type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400150 // Add a cquery request to the bazel request queue. All queued requests
151 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
152 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
153
154 // ** Cquery Results Retrieval Functions
155 // The below functions pertain to retrieving cquery results from a prior
156 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400157
158 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400159 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500160
Chris Parsons944e7d02021-03-11 11:08:46 -0500161 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400162 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400163
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000164 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400165 // TODO(b/232976601): Remove.
166 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000167
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700168 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400169 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700170
Sasha Smundakedd16662022-10-07 14:44:50 -0700171 // Returns the results of the GetCcUnstrippedInfo query
172 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
173
Chris Parsonsf874e462022-05-10 13:50:12 -0400174 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400175
176 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800177 // queued in the BazelContext. The ctx argument is optional and is only
178 // used for performance data collection
Liz Kammer690fbac2023-02-10 11:11:17 -0500179 InvokeBazel(config Config, ctx invokeBazelContext) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400180
Chris Parsonsad876012022-08-20 14:48:32 -0400181 // Returns true if Bazel handling is enabled for the module with the given name.
182 // Note that this only implies "bazel mixed build" allowlisting. The caller
183 // should independently verify the module is eligible for Bazel handling
184 // (for example, that it is MixedBuildBuildable).
Sasha Smundak39a301c2022-12-29 17:11:49 -0800185 IsModuleNameAllowed(moduleName string) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500186
187 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
188 OutputBase() string
189
190 // Returns build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500191 BuildStatementsToRegister() []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400192
193 // Returns the depsets defined in Bazel's aquery response.
194 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400195}
196
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400197type bazelRunner interface {
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500198 createBazelCommand(config Config, paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) *exec.Cmd
Liz Kammer690fbac2023-02-10 11:11:17 -0500199 issueBazelCommand(bazelCmd *exec.Cmd, eventHandler *metrics.EventHandler) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400200}
201
202type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000203 homeDir string
204 bazelPath string
205 outputBase string
206 workspaceDir string
207 soongOutDir string
208 metricsDir string
209 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400210}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400211
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400212// A context object which tracks queued requests that need to be made to Bazel,
213// and their results after the requests have been made.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800214type mixedBuildBazelContext struct {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400215 bazelRunner
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500216 paths *bazelPaths
217 // cquery requests that have not yet been issued to Bazel. This list is maintained
218 // in a sorted state, and is guaranteed to have no duplicates.
219 requests []cqueryKey
220 requestMutex sync.Mutex // requests can be written in parallel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400221
222 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500223
224 // Build statements which should get registered to reflect Bazel's outputs.
Liz Kammera4655a92023-02-10 17:17:28 -0500225 buildStatements []*bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400226
227 // Depsets which should be used for Bazel's build statements.
228 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400229
230 // Per-module allowlist/denylist functionality to control whether analysis of
231 // modules are handled by Bazel. For modules which do not have a Bazel definition
232 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
233 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
234 // Per-module denylist to opt modules out of bazel handling.
235 bazelDisabledModules map[string]bool
236 // Per-module allowlist to opt modules in to bazel handling.
237 bazelEnabledModules map[string]bool
238 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
239 modulesDefaultToBazel bool
Cole Faustb85d1a12022-11-08 18:14:01 -0800240
241 targetProduct string
242 targetBuildVariant string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400243}
244
Sasha Smundak39a301c2022-12-29 17:11:49 -0800245var _ BazelContext = &mixedBuildBazelContext{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400246
247// A bazel context to use when Bazel is disabled.
248type noopBazelContext struct{}
249
250var _ BazelContext = noopBazelContext{}
251
252// A bazel context to use for tests.
253type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400254 OutputBaseDir string
255
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000256 LabelToOutputFiles map[string][]string
257 LabelToCcInfo map[string]cquery.CcInfo
258 LabelToPythonBinary map[string]string
Liz Kammerbe6a7122022-11-04 16:05:11 -0400259 LabelToApexInfo map[string]cquery.ApexInfo
Sasha Smundakedd16662022-10-07 14:44:50 -0700260 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400261}
262
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700263func (m MockBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400264 panic("unimplemented")
Chris Parsons8d6e4332021-02-22 16:13:50 -0500265}
266
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700267func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500268 result, ok := m.LabelToOutputFiles[label]
269 if !ok {
270 return []string{}, fmt.Errorf("no target with label %q in LabelToOutputFiles", label)
271 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400272 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400273}
274
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700275func (m MockBazelContext) GetCcInfo(label string, _ configKey) (cquery.CcInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500276 result, ok := m.LabelToCcInfo[label]
277 if !ok {
278 return cquery.CcInfo{}, fmt.Errorf("no target with label %q in LabelToCcInfo", label)
279 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400280 return result, nil
281}
282
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700283func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500284 result, ok := m.LabelToPythonBinary[label]
285 if !ok {
286 return "", fmt.Errorf("no target with label %q in LabelToPythonBinary", label)
287 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400288 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000289}
290
Liz Kammerbe6a7122022-11-04 16:05:11 -0400291func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500292 result, ok := m.LabelToApexInfo[label]
293 if !ok {
294 return cquery.ApexInfo{}, fmt.Errorf("no target with label %q in LabelToApexInfo", label)
295 }
Liz Kammer0e255ef2022-11-04 16:07:04 -0400296 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700297}
298
Sasha Smundakedd16662022-10-07 14:44:50 -0700299func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
Sam Delmericoce39f832023-01-23 14:04:24 -0500300 result, ok := m.LabelToCcBinary[label]
301 if !ok {
302 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no target with label %q in LabelToCcBinary", label)
303 }
Sasha Smundakedd16662022-10-07 14:44:50 -0700304 return result, nil
305}
306
Liz Kammer690fbac2023-02-10 11:11:17 -0500307func (m MockBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400308 panic("unimplemented")
309}
310
Sasha Smundak39a301c2022-12-29 17:11:49 -0800311func (m MockBazelContext) IsModuleNameAllowed(_ string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400312 return true
313}
314
Liz Kammera92e8442021-04-07 20:25:21 -0400315func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500316
Liz Kammera4655a92023-02-10 17:17:28 -0500317func (m MockBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
318 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500319}
320
Chris Parsons1a7aca02022-04-25 22:35:15 -0400321func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
322 return []bazel.AqueryDepset{}
323}
324
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400325var _ BazelContext = MockBazelContext{}
326
Sasha Smundak39a301c2022-12-29 17:11:49 -0800327func (bazelCtx *mixedBuildBazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400328 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400329 bazelCtx.requestMutex.Lock()
330 defer bazelCtx.requestMutex.Unlock()
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500331
332 // Insert key into requests, maintaining the sort, and only if it's not duplicate.
333 keyString := key.String()
334 foundEqual := false
335 notLessThanKeyString := func(i int) bool {
336 s := bazelCtx.requests[i].String()
337 v := strings.Compare(s, keyString)
338 if v == 0 {
339 foundEqual = true
340 }
341 return v >= 0
342 }
343 targetIndex := sort.Search(len(bazelCtx.requests), notLessThanKeyString)
344 if foundEqual {
345 return
346 }
347
348 if targetIndex == len(bazelCtx.requests) {
349 bazelCtx.requests = append(bazelCtx.requests, key)
350 } else {
351 bazelCtx.requests = append(bazelCtx.requests[:targetIndex+1], bazelCtx.requests[targetIndex:]...)
352 bazelCtx.requests[targetIndex] = key
353 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400354}
355
Sasha Smundak39a301c2022-12-29 17:11:49 -0800356func (bazelCtx *mixedBuildBazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400357 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400358 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500359 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400360
Chris Parsonsf874e462022-05-10 13:50:12 -0400361 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400362 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400363 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400364}
365
Sasha Smundak39a301c2022-12-29 17:11:49 -0800366func (bazelCtx *mixedBuildBazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400367 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400368 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000369 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400370 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000371 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400372 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 +0000373}
374
Sasha Smundak39a301c2022-12-29 17:11:49 -0800375func (bazelCtx *mixedBuildBazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400376 key := makeCqueryKey(label, cquery.GetPythonBinary, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400377 if rawString, ok := bazelCtx.results[key]; ok {
378 bazelOutput := strings.TrimSpace(rawString)
379 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
380 }
381 return "", fmt.Errorf("no bazel response found for %v", key)
382}
383
Sasha Smundak39a301c2022-12-29 17:11:49 -0800384func (bazelCtx *mixedBuildBazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400385 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700386 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500387 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700388 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400389 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700390}
391
Sasha Smundak39a301c2022-12-29 17:11:49 -0800392func (bazelCtx *mixedBuildBazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
Sasha Smundakedd16662022-10-07 14:44:50 -0700393 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
394 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500395 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700396 }
397 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
398}
399
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700400func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500401 panic("unimplemented")
402}
403
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700404func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500405 panic("unimplemented")
406}
407
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700408func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400409 panic("unimplemented")
410}
411
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700412func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000413 panic("unimplemented")
414}
415
Liz Kammerbe6a7122022-11-04 16:05:11 -0400416func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700417 panic("unimplemented")
418}
419
Sasha Smundakedd16662022-10-07 14:44:50 -0700420func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
421 //TODO implement me
422 panic("implement me")
423}
424
Liz Kammer690fbac2023-02-10 11:11:17 -0500425func (n noopBazelContext) InvokeBazel(_ Config, _ invokeBazelContext) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400426 panic("unimplemented")
427}
428
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500429func (m noopBazelContext) OutputBase() string {
430 return ""
431}
432
Sasha Smundak39a301c2022-12-29 17:11:49 -0800433func (n noopBazelContext) IsModuleNameAllowed(_ string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400434 return false
435}
436
Liz Kammera4655a92023-02-10 17:17:28 -0500437func (m noopBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
438 return []*bazel.BuildStatement{}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500439}
440
Chris Parsons1a7aca02022-04-25 22:35:15 -0400441func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
442 return []bazel.AqueryDepset{}
443}
444
Cole Faust705968d2022-12-14 11:32:05 -0800445func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400446 disabledModules := map[string]bool{}
447 enabledModules := map[string]bool{}
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800448 addToStringSet := func(set map[string]bool, items []string) {
449 for _, item := range items {
450 set[item] = true
451 }
452 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400453
Cole Faust705968d2022-12-14 11:32:05 -0800454 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400455 case BazelProdMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800456 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800457 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000458 enabledModules[enabledAdHocModule] = true
459 }
MarkDacekb78465d2022-10-18 20:10:16 +0000460 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400461 // Staging mode includes all prod modules plus all staging modules.
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800462 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
463 addToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800464 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000465 enabledModules[enabledAdHocModule] = true
466 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400467 case BazelDevMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800468 addToStringSet(disabledModules, allowlists.MixedBuildsDisabledList)
Chris Parsonsef615e52022-08-18 22:04:11 -0400469 default:
Cole Faust705968d2022-12-14 11:32:05 -0800470 panic("Expected BazelProdMode, BazelStagingMode, or BazelDevMode")
471 }
472 return enabledModules, disabledModules
473}
474
475func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
476 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
477 enabledList := make([]string, 0, len(enabledModules))
478 for module := range enabledModules {
479 if !disabledModules[module] {
480 enabledList = append(enabledList, module)
481 }
482 }
483 sort.Strings(enabledList)
484 return enabledList
485}
486
487func NewBazelContext(c *config) (BazelContext, error) {
488 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode && c.BuildMode != BazelDevMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400489 return noopBazelContext{}, nil
490 }
491
Cole Faust705968d2022-12-14 11:32:05 -0800492 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
493
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800494 paths := bazelPaths{
495 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400496 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800497 var missing []string
498 vars := []struct {
499 name string
500 ptr *string
Paul Duffin184366a2022-12-21 15:55:33 +0000501
502 // True if the environment variable needs to be tracked so that changes to the variable
503 // cause the ninja file to be regenerated, false otherwise. False should only be set for
504 // environment variables that have no effect on the generated ninja file.
505 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800506 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000507 {"BAZEL_HOME", &paths.homeDir, true},
508 {"BAZEL_PATH", &paths.bazelPath, true},
509 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
510 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
511 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
512 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800513 }
514 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000515 if v.track {
516 if s := c.Getenv(v.name); len(s) > 1 {
517 *v.ptr = s
518 continue
519 }
520 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800521 *v.ptr = s
522 } else {
523 missing = append(missing, v.name)
524 }
525 }
526 if len(missing) > 0 {
527 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
528 }
Cole Faustb85d1a12022-11-08 18:14:01 -0800529
530 targetBuildVariant := "user"
531 if c.Eng() {
532 targetBuildVariant = "eng"
533 } else if c.Debuggable() {
534 targetBuildVariant = "userdebug"
535 }
536 targetProduct := "unknown"
537 if c.HasDeviceProduct() {
538 targetProduct = c.DeviceProduct()
539 }
540
Sasha Smundak39a301c2022-12-29 17:11:49 -0800541 return &mixedBuildBazelContext{
Chris Parsonsad876012022-08-20 14:48:32 -0400542 bazelRunner: &builtinBazelRunner{},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800543 paths: &paths,
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800544 modulesDefaultToBazel: c.BuildMode == BazelDevMode,
Chris Parsonsef615e52022-08-18 22:04:11 -0400545 bazelEnabledModules: enabledModules,
Chris Parsonsad876012022-08-20 14:48:32 -0400546 bazelDisabledModules: disabledModules,
Cole Faustb85d1a12022-11-08 18:14:01 -0800547 targetProduct: targetProduct,
548 targetBuildVariant: targetBuildVariant,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400549 }, nil
550}
551
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400552func (p *bazelPaths) BazelMetricsDir() string {
553 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000554}
555
Sasha Smundak39a301c2022-12-29 17:11:49 -0800556func (context *mixedBuildBazelContext) IsModuleNameAllowed(moduleName string) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400557 if context.bazelDisabledModules[moduleName] {
558 return false
559 }
560 if context.bazelEnabledModules[moduleName] {
561 return true
562 }
563 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400564}
565
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400566func pwdPrefix() string {
567 // Darwin doesn't have /proc
568 if runtime.GOOS != "darwin" {
569 return "PWD=/proc/self/cwd"
570 }
571 return ""
572}
573
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400574type bazelCommand struct {
575 command string
576 // query or label
577 expression string
578}
579
580type mockBazelRunner struct {
581 bazelCommandResults map[bazelCommand]string
Jason Wu52cd1942022-09-08 15:37:57 +0000582 // use *exec.Cmd as a key to get the bazelCommand, the map will be used in issueBazelCommand()
583 // Register createBazelCommand() invocations. Later, an
584 // issueBazelCommand() invocation can be mapped to the *exec.Cmd instance
585 // and then to the expected result via bazelCommandResults
586 tokens map[*exec.Cmd]bazelCommand
587 commands []bazelCommand
588 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400589}
590
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500591func (r *mockBazelRunner) createBazelCommand(_ Config, _ *bazelPaths, _ bazel.RunName,
Jason Wu52cd1942022-09-08 15:37:57 +0000592 command bazelCommand, extraFlags ...string) *exec.Cmd {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400593 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700594 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Jason Wu52cd1942022-09-08 15:37:57 +0000595 cmd := &exec.Cmd{}
596 if r.tokens == nil {
597 r.tokens = make(map[*exec.Cmd]bazelCommand)
598 }
599 r.tokens[cmd] = command
600 return cmd
601}
602
Liz Kammer690fbac2023-02-10 11:11:17 -0500603func (r *mockBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd, _ *metrics.EventHandler) (string, string, error) {
Jason Wu52cd1942022-09-08 15:37:57 +0000604 if command, ok := r.tokens[bazelCmd]; ok {
605 return r.bazelCommandResults[command], "", nil
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400606 }
607 return "", "", nil
608}
609
610type builtinBazelRunner struct{}
611
Chris Parsons808d84c2021-03-09 20:43:32 -0500612// Issues the given bazel command with given build label and additional flags.
613// Returns (stdout, stderr, error). The first and second return values are strings
614// containing the stdout and stderr of the run command, and an error is returned if
615// the invocation returned an error code.
Liz Kammer690fbac2023-02-10 11:11:17 -0500616func (r *builtinBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd, eventHandler *metrics.EventHandler) (string, string, error) {
617 eventHandler.Begin("bazel command")
618 defer eventHandler.End("bazel command")
Jason Wu52cd1942022-09-08 15:37:57 +0000619 stderr := &bytes.Buffer{}
620 bazelCmd.Stderr = stderr
621 if output, err := bazelCmd.Output(); err != nil {
622 return "", string(stderr.Bytes()),
Sasha Smundak0e87b182022-12-01 11:46:11 -0800623 fmt.Errorf("bazel command failed: %s\n---command---\n%s\n---env---\n%s\n---stderr---\n%s---",
624 err, bazelCmd, strings.Join(bazelCmd.Env, "\n"), stderr)
Jason Wu52cd1942022-09-08 15:37:57 +0000625 } else {
626 return string(output), string(stderr.Bytes()), nil
627 }
628}
629
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500630func (r *builtinBazelRunner) createBazelCommand(config Config, paths *bazelPaths, runName bazel.RunName, command bazelCommand,
Jason Wu52cd1942022-09-08 15:37:57 +0000631 extraFlags ...string) *exec.Cmd {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000632 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000633 "--output_base=" + absolutePath(paths.outputBase),
634 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700635 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700636 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700637 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400638
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700639 // Set default platforms to canonicalized values for mixed builds requests.
640 // If these are set in the bazelrc, they will have values that are
641 // non-canonicalized to @sourceroot labels, and thus be invalid when
642 // referenced from the buildroot.
643 //
644 // The actual platform values here may be overridden by configuration
645 // transitions from the buildroot.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700646 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Cole Faustb85d1a12022-11-08 18:14:01 -0800647
648 // We don't need to set --host_platforms because it's set in bazelrc files
649 // that the bazel shell script wrapper passes
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700650
651 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
652 "--experimental_repository_disable_download",
653
654 // Suppress noise
655 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500656 "--noshow_progress",
657 "--norun_validations",
658 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400659 cmdFlags = append(cmdFlags, extraFlags...)
660
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400661 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200662 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700663 extraEnv := []string{
664 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200665 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700666 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700667 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000668 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700669 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500670 // Disables local host detection of gcc; toolchain information is defined
671 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700672 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
673 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -0500674 for _, envvar := range allowedBazelEnvironmentVars {
675 val := config.Getenv(envvar)
676 if val == "" {
677 continue
678 }
679 extraEnv = append(extraEnv, fmt.Sprintf("%s=%s", envvar, val))
680 }
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700681 bazelCmd.Env = append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400682
Jason Wu52cd1942022-09-08 15:37:57 +0000683 return bazelCmd
684}
685
686func printableCqueryCommand(bazelCmd *exec.Cmd) string {
687 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(bazelCmd.Args, "\" \"") + "\""
688 return outputString
689
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400690}
691
Sasha Smundak39a301c2022-12-29 17:11:49 -0800692func (context *mixedBuildBazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500693 // TODO(cparsons): Define configuration transitions programmatically based
694 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400695 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500696#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400697# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500698#####################################################
699
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400700def _config_node_transition_impl(settings, attr):
Cole Faustb85d1a12022-11-08 18:14:01 -0800701 if attr.os == "android" and attr.arch == "target":
702 target = "{PRODUCT}-{VARIANT}"
703 else:
704 target = "{PRODUCT}-{VARIANT}_%s_%s" % (attr.os, attr.arch)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500705 return {
Cole Faustb85d1a12022-11-08 18:14:01 -0800706 "//command_line_option:platforms": "@soong_injection//product_config_platforms/products/{PRODUCT}-{VARIANT}:%s" % target,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500707 }
708
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400709_config_node_transition = transition(
710 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500711 inputs = [],
712 outputs = [
713 "//command_line_option:platforms",
714 ],
715)
716
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400717def _passthrough_rule_impl(ctx):
718 return [DefaultInfo(files = depset(ctx.files.deps))]
719
720config_node = rule(
721 implementation = _passthrough_rule_impl,
722 attrs = {
723 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400724 "os" : attr.string(mandatory = True),
725 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400726 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
727 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500728)
729
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400730
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500731# Rule representing the root of the build, to depend on all Bazel targets that
732# are required for the build. Building this target will build the entire Bazel
733# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400734mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400735 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500736 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400737 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500738 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400739)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500740
741def _phony_root_impl(ctx):
742 return []
743
744# Rule to depend on other targets but build nothing.
745# This is useful as follows: building a target of this rule will generate
746# symlink forests for all dependencies of the target, without executing any
747# actions of the build.
748phony_root = rule(
749 implementation = _phony_root_impl,
750 attrs = {"deps" : attr.label_list()},
751)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400752`
Cole Faustb85d1a12022-11-08 18:14:01 -0800753
754 productReplacer := strings.NewReplacer(
755 "{PRODUCT}", context.targetProduct,
756 "{VARIANT}", context.targetBuildVariant)
757
758 return []byte(productReplacer.Replace(contents))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400759}
760
Sasha Smundak39a301c2022-12-29 17:11:49 -0800761func (context *mixedBuildBazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500762 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
763 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400764 formatString := `
765# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400766load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
767
768%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400769
770mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400771 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000772 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400773)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500774
775phony_root(name = "phonyroot",
776 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000777 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500778)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400779`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400780 configNodeFormatString := `
781config_node(name = "%s",
782 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400783 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400784 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000785 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400786)
787`
788
789 configNodesSection := ""
790
Chris Parsons787fb362021-10-14 18:43:51 -0400791 labelsByConfig := map[string][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500792
793 for _, val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200794 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400795 configString := getConfigString(val)
796 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400797 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400798
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500799 // Configs need to be sorted to maintain determinism of the BUILD file.
800 sortedConfigs := make([]string, 0, len(labelsByConfig))
801 for val := range labelsByConfig {
802 sortedConfigs = append(sortedConfigs, val)
803 }
804 sort.Slice(sortedConfigs, func(i, j int) bool { return sortedConfigs[i] < sortedConfigs[j] })
805
Jingwen Chen1e347862021-09-02 12:11:49 +0000806 allLabels := []string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500807 for _, configString := range sortedConfigs {
808 labels := labelsByConfig[configString]
Chris Parsons787fb362021-10-14 18:43:51 -0400809 configTokens := strings.Split(configString, "|")
810 if len(configTokens) != 2 {
811 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000812 }
Chris Parsons787fb362021-10-14 18:43:51 -0400813 archString := configTokens[0]
814 osString := configTokens[1]
815 targetString := fmt.Sprintf("%s_%s", osString, archString)
816 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
817 labelsString := strings.Join(labels, ",\n ")
818 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400819 }
820
Jingwen Chen1e347862021-09-02 12:11:49 +0000821 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400822}
823
Chris Parsons944e7d02021-03-11 11:08:46 -0500824func indent(original string) string {
825 result := ""
826 for _, line := range strings.Split(original, "\n") {
827 result += " " + line + "\n"
828 }
829 return result
830}
831
Chris Parsons808d84c2021-03-09 20:43:32 -0500832// Returns the file contents of the buildroot.cquery file that should be used for the cquery
833// expression in order to obtain information about buildroot and its dependencies.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800834// The contents of this file depend on the mixedBuildBazelContext's requests; requests are enumerated
Chris Parsons808d84c2021-03-09 20:43:32 -0500835// and grouped by their request type. The data retrieved for each label depends on its
836// request type.
Sasha Smundak39a301c2022-12-29 17:11:49 -0800837func (context *mixedBuildBazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400838 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Chris Parsons3a8d0fb2023-02-02 18:16:29 -0500839 for _, val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500840 cqueryId := getCqueryId(val)
841 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
842 requestTypeToCqueryIdEntries[val.requestType] =
843 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
844 }
845 labelRegistrationMapSection := ""
846 functionDefSection := ""
847 mainSwitchSection := ""
848
849 mapDeclarationFormatString := `
850%s = {
851 %s
852}
853`
854 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800855def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500856%s
857`
858 mainSwitchSectionFormatString := `
859 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800860 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500861`
862
Usta Shrestha0b52d832022-02-04 21:37:39 -0500863 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500864 labelMapName := requestType.Name() + "_Labels"
865 functionName := requestType.Name() + "_Fn"
866 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
867 labelMapName,
868 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
869 functionDefSection += fmt.Sprintf(functionDefFormatString,
870 functionName,
871 indent(requestType.StarlarkFunctionBody()))
872 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
873 labelMapName, functionName)
874 }
875
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400876 formatString := `
877# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400878
Usta Shrestha79fccef2022-09-02 18:37:40 -0400879# a drop-in replacement for json.encode(), not available in cquery environment
880# TODO(cparsons): bring json module in and remove this function
881def json_encode(input):
882 # Avoiding recursion by limiting
883 # - a dict to contain anything except a dict
884 # - a list to contain only primitives
885 def encode_primitive(p):
886 t = type(p)
887 if t == "string" or t == "int":
888 return repr(p)
Cole Faustb85d1a12022-11-08 18:14:01 -0800889 fail("unsupported value '%s' of type '%s'" % (p, type(p)))
Usta Shrestha79fccef2022-09-02 18:37:40 -0400890
891 def encode_list(list):
Cole Faustb85d1a12022-11-08 18:14:01 -0800892 return "[%s]" % ", ".join([encode_primitive(item) for item in list])
Usta Shrestha79fccef2022-09-02 18:37:40 -0400893
894 def encode_list_or_primitive(v):
895 return encode_list(v) if type(v) == "list" else encode_primitive(v)
896
897 if type(input) == "dict":
898 # TODO(juu): the result is read line by line so can't use '\n' yet
Cole Faustb85d1a12022-11-08 18:14:01 -0800899 kv_pairs = [("%s: %s" % (encode_primitive(k), encode_list_or_primitive(v))) for (k, v) in input.items()]
900 return "{ %s }" % ", ".join(kv_pairs)
Usta Shrestha79fccef2022-09-02 18:37:40 -0400901 else:
902 return encode_list_or_primitive(input)
903
Cole Faustb85d1a12022-11-08 18:14:01 -0800904{LABEL_REGISTRATION_MAP_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500905
Cole Faustb85d1a12022-11-08 18:14:01 -0800906{FUNCTION_DEF_SECTION}
Chris Parsons8d6e4332021-02-22 16:13:50 -0500907
908def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400909 # TODO(b/199363072): filegroups and file targets aren't associated with any
910 # specific platform architecture in mixed builds. This is consistent with how
911 # Soong treats filegroups, but it may not be the case with manually-written
912 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500913 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000914 if buildoptions == None:
915 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400916 # any specific platform architecture in mixed builds, so use the host.
917 return "x86_64|linux"
Cole Faustb85d1a12022-11-08 18:14:01 -0800918 platforms = buildoptions["//command_line_option:platforms"]
Chris Parsons8d6e4332021-02-22 16:13:50 -0500919 if len(platforms) != 1:
920 # An individual configured target should have only one platform architecture.
921 # Note that it's fine for there to be multiple architectures for the same label,
922 # but each is its own configured target.
923 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
Cole Faustb85d1a12022-11-08 18:14:01 -0800924 platform_name = platforms[0].name
Chris Parsons8d6e4332021-02-22 16:13:50 -0500925 if platform_name == "host":
926 return "HOST"
Cole Faustb85d1a12022-11-08 18:14:01 -0800927 if not platform_name.startswith("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}"):
928 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))
929 platform_name = platform_name.removeprefix("{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}").removeprefix("_")
930 if not platform_name:
931 return "target|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400932 elif platform_name.startswith("android_"):
Cole Faustb85d1a12022-11-08 18:14:01 -0800933 return platform_name.removeprefix("android_") + "|android"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400934 elif platform_name.startswith("linux_"):
Cole Faustb85d1a12022-11-08 18:14:01 -0800935 return platform_name.removeprefix("linux_") + "|linux"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400936 else:
Cole Faustb85d1a12022-11-08 18:14:01 -0800937 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 -0500938
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400939def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500940 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500941
Chris Parsons86dc2c22022-09-28 14:58:41 -0400942 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
943 if id_string.startswith("//"):
944 id_string = "@" + id_string
945
Cole Faustb85d1a12022-11-08 18:14:01 -0800946 {MAIN_SWITCH_SECTION}
947
Chris Parsons944e7d02021-03-11 11:08:46 -0500948 # This target was not requested via cquery, and thus must be a dependency
949 # of a requested target.
950 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400951`
Cole Faustb85d1a12022-11-08 18:14:01 -0800952 replacer := strings.NewReplacer(
953 "{TARGET_PRODUCT}", context.targetProduct,
954 "{TARGET_BUILD_VARIANT}", context.targetBuildVariant,
955 "{LABEL_REGISTRATION_MAP_SECTION}", labelRegistrationMapSection,
956 "{FUNCTION_DEF_SECTION}", functionDefSection,
957 "{MAIN_SWITCH_SECTION}", mainSwitchSection)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400958
Cole Faustb85d1a12022-11-08 18:14:01 -0800959 return []byte(replacer.Replace(formatString))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400960}
961
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200962// Returns a path containing build-related metadata required for interfacing
963// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400964func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200965 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500966}
967
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200968// Returns the path where the contents of the @soong_injection repository live.
969// It is used by Soong to tell Bazel things it cannot over the command line.
970func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200971 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200972}
973
974// Returns the path of the synthetic Bazel workspace that contains a symlink
975// forest composed the whole source tree and BUILD files generated by bp2build.
976func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200977 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200978}
979
Jingwen Chen8c523582021-06-01 11:19:53 +0000980// Returns the path to the top level out dir ($OUT_DIR).
981func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200982 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000983}
984
Sasha Smundak4975c822022-11-16 15:28:18 -0800985const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
986
987var (
988 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
989 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
990 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
991)
992
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400993// Issues commands to Bazel to receive results for all cquery requests
994// queued in the BazelContext.
Liz Kammer690fbac2023-02-10 11:11:17 -0500995func (context *mixedBuildBazelContext) InvokeBazel(config Config, ctx invokeBazelContext) error {
996 eventHandler := ctx.GetEventHandler()
997 eventHandler.Begin("bazel")
998 defer eventHandler.End("bazel")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400999
Sasha Smundak4975c822022-11-16 15:28:18 -08001000 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
1001 if err := os.MkdirAll(metricsDir, 0777); err != nil {
1002 return err
1003 }
1004 }
1005 context.results = make(map[cqueryKey]string)
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001006 if err := context.runCquery(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001007 return err
1008 }
1009 if err := context.runAquery(config, ctx); err != nil {
1010 return err
1011 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001012 if err := context.generateBazelSymlinks(config, ctx); err != nil {
Sasha Smundak4975c822022-11-16 15:28:18 -08001013 return err
1014 }
1015
1016 // Clear requests.
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001017 context.requests = []cqueryKey{}
Sasha Smundak4975c822022-11-16 15:28:18 -08001018 return nil
1019}
1020
Liz Kammer690fbac2023-02-10 11:11:17 -05001021func (context *mixedBuildBazelContext) runCquery(config Config, ctx invokeBazelContext) error {
1022 eventHandler := ctx.GetEventHandler()
1023 eventHandler.Begin("cquery")
1024 defer eventHandler.End("cquery")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001025 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +02001026 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
1027 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
1028 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -05001029 if err != nil {
1030 return err
1031 }
1032 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001033 if err := writeFileBytesIfChanged(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001034 return err
1035 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001036 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001037 return err
1038 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001039 if err := writeFileBytesIfChanged(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001040 return err
1041 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +02001042 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001043 if err := writeFileBytesIfChanged(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001044 return err
1045 }
Jingwen Chen1e347862021-09-02 12:11:49 +00001046
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001047 cqueryCommandWithFlag := context.createBazelCommand(config, context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001048 "--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
Liz Kammer690fbac2023-02-10 11:11:17 -05001049 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCommandWithFlag, eventHandler)
Wei Licbd181c2022-11-16 08:59:23 -08001050 if cqueryErr != nil {
1051 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -05001052 }
Jason Wu52cd1942022-09-08 15:37:57 +00001053 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", printableCqueryCommand(cqueryCommandWithFlag))
Sasha Smundak0e87b182022-12-01 11:46:11 -08001054 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001055 return err
1056 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -04001057 cqueryResults := map[string]string{}
1058 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
1059 if strings.Contains(outputLine, ">>") {
1060 splitLine := strings.SplitN(outputLine, ">>", 2)
1061 cqueryResults[splitLine[0]] = splitLine[1]
1062 }
1063 }
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001064 for _, val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -05001065 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -05001066 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001067 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -05001068 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -08001069 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001070 }
1071 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001072 return nil
1073}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001074
Chris Parsons3a8d0fb2023-02-02 18:16:29 -05001075func writeFileBytesIfChanged(path string, contents []byte, perm os.FileMode) error {
1076 oldContents, err := os.ReadFile(path)
1077 if err != nil || !bytes.Equal(contents, oldContents) {
1078 err = os.WriteFile(path, contents, perm)
1079 }
1080 return nil
1081}
1082
Liz Kammer690fbac2023-02-10 11:11:17 -05001083func (context *mixedBuildBazelContext) runAquery(config Config, ctx invokeBazelContext) error {
1084 eventHandler := ctx.GetEventHandler()
1085 eventHandler.Begin("aquery")
1086 defer eventHandler.End("aquery")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001087 // Issue an aquery command to retrieve action information about the bazel build tree.
1088 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001089 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
1090 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +00001091 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -07001092 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001093 extraFlags = append(extraFlags, "--collect_code_coverage")
1094 paths := make([]string, 0, 2)
1095 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -08001096 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -08001097 // TODO(b/259404593) convert path wildcard to regex values
1098 if p[i] == "*" {
1099 p[i] = ".*"
1100 }
1101 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -07001102 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
1103 }
1104 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
1105 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
1106 }
1107 if len(paths) > 0 {
1108 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -07001109 }
1110 }
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001111 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(config, context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
Liz Kammer690fbac2023-02-10 11:11:17 -05001112 extraFlags...), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001113 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001114 return err
1115 }
Liz Kammer690fbac2023-02-10 11:11:17 -05001116 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001117 return err
1118}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001119
Liz Kammer690fbac2023-02-10 11:11:17 -05001120func (context *mixedBuildBazelContext) generateBazelSymlinks(config Config, ctx invokeBazelContext) error {
1121 eventHandler := ctx.GetEventHandler()
1122 eventHandler.Begin("symlinks")
1123 defer eventHandler.End("symlinks")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001124 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1125 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1126 // but some of symlinks may be required to resolve source dependencies of the build.
Liz Kammer690fbac2023-02-10 11:11:17 -05001127 _, _, err := context.issueBazelCommand(context.createBazelCommand(config, context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd), eventHandler)
Sasha Smundak4975c822022-11-16 15:28:18 -08001128 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001129}
Chris Parsonsa798d962020-10-12 23:44:08 -04001130
Liz Kammera4655a92023-02-10 17:17:28 -05001131func (context *mixedBuildBazelContext) BuildStatementsToRegister() []*bazel.BuildStatement {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001132 return context.buildStatements
1133}
1134
Sasha Smundak39a301c2022-12-29 17:11:49 -08001135func (context *mixedBuildBazelContext) AqueryDepsets() []bazel.AqueryDepset {
Chris Parsons1a7aca02022-04-25 22:35:15 -04001136 return context.depsets
1137}
1138
Sasha Smundak39a301c2022-12-29 17:11:49 -08001139func (context *mixedBuildBazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001140 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001141}
1142
Chris Parsonsa798d962020-10-12 23:44:08 -04001143// Singleton used for registering BUILD file ninja dependencies (needed
1144// for correctness of builds which use Bazel.
1145func BazelSingleton() Singleton {
1146 return &bazelSingleton{}
1147}
1148
1149type bazelSingleton struct{}
1150
1151func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001152 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001153 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001154 return
1155 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001156
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001157 // Add ninja file dependencies for files which all bazel invocations require.
1158 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001159 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001160 ctx.AddNinjaFileDeps(bazelBuildList)
1161
Sasha Smundak0e87b182022-12-01 11:46:11 -08001162 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001163 if err != nil {
1164 ctx.Errorf(err.Error())
1165 }
1166 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1167 for _, file := range files {
1168 ctx.AddNinjaFileDeps(file)
1169 }
1170
Chris Parsons1a7aca02022-04-25 22:35:15 -04001171 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1172 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001173 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001174 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1175 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001176 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1177 }
1178 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001179 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1180 if artifactPath == "bazel-out/volatile-status.txt" {
1181 // See https://bazel.build/docs/user-manual#workspace-status
1182 orderOnlies = append(orderOnlies, pathInBazelOut)
1183 } else {
1184 outputs = append(outputs, pathInBazelOut)
1185 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001186 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001187 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001188 ctx.Build(pctx, BuildParams{
1189 Rule: blueprint.Phony,
1190 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1191 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001192 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001193 })
1194 }
1195
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001196 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1197 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001198 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Liz Kammera4655a92023-02-10 17:17:28 -05001199 // nil build statements are a valid case where we do not create an action because it is
1200 // unnecessary or handled by other processing
1201 if buildStatement == nil {
1202 continue
1203 }
Sasha Smundak1da064c2022-06-08 16:36:16 -07001204 if len(buildStatement.Command) > 0 {
1205 rule := NewRuleBuilder(pctx, ctx)
1206 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1207 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1208 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1209 continue
1210 }
1211 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1212 // and thus require special treatment. If BuildStatement were an interface implementing
1213 // buildRule(ctx) function, the code here would just call it.
1214 // Unfortunately, the BuildStatement is defined in
1215 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1216 // because this would cause circular dependency. So, until we move aquery processing
1217 // to the 'android' package, we need to handle special cases here.
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001218 switch buildStatement.Mnemonic {
1219 case "FileWrite", "SourceSymlinkManifest":
Cole Fausta7347492022-12-16 10:56:24 -08001220 out := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1221 WriteFileRuleVerbatim(ctx, out, buildStatement.FileContents)
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001222 case "SymlinkTree":
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001223 // build-runfiles arguments are the manifest file and the target directory
1224 // where it creates the symlink tree according to this manifest (and then
1225 // writes the MANIFEST file to it).
1226 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1227 outManifestPath := outManifest.String()
1228 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1229 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1230 }
1231 outDir := filepath.Dir(outManifestPath)
1232 ctx.Build(pctx, BuildParams{
1233 Rule: buildRunfilesRule,
1234 Output: outManifest,
1235 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1236 Description: "symlink tree for " + outDir,
1237 Args: map[string]string{
1238 "outDir": outDir,
1239 },
1240 })
Usta Shrestha13fd5ae2023-01-27 10:55:34 -05001241 default:
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001242 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001243 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001244 }
1245}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001246
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001247// Register bazel-owned build statements (obtained from the aquery invocation).
Liz Kammera4655a92023-02-10 17:17:28 -05001248func createCommand(cmd *RuleBuilderCommand, buildStatement *bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001249 // executionRoot is the action cwd.
1250 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1251
1252 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1253 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001254 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001255 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001256 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001257 }
1258 cmd.Text("&&")
1259 }
1260
1261 for _, pair := range buildStatement.Env {
1262 // Set per-action env variables, if any.
1263 cmd.Flag(pair.Key + "=" + pair.Value)
1264 }
1265
1266 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001267 if len(buildStatement.Command) > 16*1024 {
1268 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1269 WriteFileRule(ctx, commandFile, buildStatement.Command)
1270
1271 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1272 } else {
1273 cmd.Text(buildStatement.Command)
1274 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001275
1276 for _, outputPath := range buildStatement.OutputPaths {
1277 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1278 }
1279 for _, inputPath := range buildStatement.InputPaths {
1280 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1281 }
1282 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1283 otherDepsetName := bazelDepsetName(inputDepsetHash)
1284 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1285 }
1286
1287 if depfile := buildStatement.Depfile; depfile != nil {
1288 // The paths in depfile are relative to `executionRoot`.
1289 // Hence, they need to be corrected by replacing "bazel-out"
1290 // with the full `bazelOutDir`.
1291 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1292 // would be deemed missing.
1293 // (Note: The regexp uses a capture group because the version of sed
1294 // does not support a look-behind pattern.)
1295 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1296 bazelOutDir, *depfile)
1297 cmd.Text(replacement)
1298 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1299 }
1300
1301 for _, symlinkPath := range buildStatement.SymlinkPaths {
1302 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1303 }
1304}
1305
Chris Parsons8d6e4332021-02-22 16:13:50 -05001306func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001307 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001308}
1309
Chris Parsons787fb362021-10-14 18:43:51 -04001310func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001311 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001312 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001313 if key.configKey.osType.Class == Device {
1314 // For the generic Android, the expected result is "target|android", which
1315 // corresponds to the product_variable_config named "android_target" in
1316 // build/bazel/platforms/BUILD.bazel.
1317 arch = "target"
1318 } else {
1319 // Use host platform, which is currently hardcoded to be x86_64.
1320 arch = "x86_64"
1321 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001322 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001323 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001324 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001325 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001326 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001327 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001328 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -04001329}
1330
Chris Parsonsf874e462022-05-10 13:50:12 -04001331func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001332 return configKey{
1333 // use string because Arch is not a valid key in go
1334 arch: ctx.Arch().String(),
1335 osType: ctx.Os(),
1336 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001337}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001338
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001339func bazelDepsetName(contentHash string) string {
1340 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001341}
Sam Delmericocb3c52c2023-02-03 17:40:08 -05001342
1343func EnvironmentVarsFile(config Config) string {
1344 return fmt.Sprintf(bazel.GeneratedBazelFileWarning+`
1345_env = %s
1346
1347env = _env
1348`,
1349 starlark_fmt.PrintStringList(allowedBazelEnvironmentVars, 0),
1350 )
1351}