blob: e9c97d0ce435971db76d20a50bb941e3572df99e [file] [log] [blame]
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001// Copyright 2020 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package android
16
17import (
18 "bytes"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040019 "fmt"
20 "os"
21 "os/exec"
Usta Shresthaacd5a0c2022-06-22 11:20:50 -040022 "path"
Chris Parsonsa798d962020-10-12 23:44:08 -040023 "path/filepath"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040024 "runtime"
Cole Faust705968d2022-12-14 11:32:05 -080025 "sort"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040026 "strings"
27 "sync"
Chris Parsonsa798d962020-10-12 23:44:08 -040028
Chris Parsonsad876012022-08-20 14:48:32 -040029 "android/soong/android/allowlists"
Chris Parsons944e7d02021-03-11 11:08:46 -050030 "android/soong/bazel/cquery"
Jingwen Chen1e347862021-09-02 12:11:49 +000031 "android/soong/shared"
Liz Kammer337e9032022-08-03 15:49:43 -040032
Chris Parsons1a7aca02022-04-25 22:35:15 -040033 "github.com/google/blueprint"
Liz Kammer8206d4f2021-03-03 16:40:52 -050034
Patrice Arruda05ab2d02020-12-12 06:24:26 +000035 "android/soong/bazel"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040036)
37
Sasha Smundak1da064c2022-06-08 16:36:16 -070038var (
39 writeBazelFile = pctx.AndroidStaticRule("bazelWriteFileRule", blueprint.RuleParams{
40 Command: `sed "s/\\\\n/\n/g" ${out}.rsp >${out}`,
41 Rspfile: "${out}.rsp",
42 RspfileContent: "${content}",
43 }, "content")
Sasha Smundakc180dbd2022-07-03 14:55:58 -070044 _ = pctx.HostBinToolVariable("bazelBuildRunfilesTool", "build-runfiles")
45 buildRunfilesRule = pctx.AndroidStaticRule("bazelBuildRunfiles", blueprint.RuleParams{
46 Command: "${bazelBuildRunfilesTool} ${in} ${outDir}",
47 Depfile: "",
48 Description: "",
49 CommandDeps: []string{"${bazelBuildRunfilesTool}"},
50 }, "outDir")
Sasha Smundak1da064c2022-06-08 16:36:16 -070051)
52
Chris Parsonsf874e462022-05-10 13:50:12 -040053func init() {
54 RegisterMixedBuildsMutator(InitRegistrationContext)
55}
56
57func RegisterMixedBuildsMutator(ctx RegistrationContext) {
Liz Kammer337e9032022-08-03 15:49:43 -040058 ctx.FinalDepsMutators(func(ctx RegisterMutatorsContext) {
Chris Parsonsf874e462022-05-10 13:50:12 -040059 ctx.BottomUp("mixed_builds_prep", mixedBuildsPrepareMutator).Parallel()
60 })
61}
62
63func mixedBuildsPrepareMutator(ctx BottomUpMutatorContext) {
64 if m := ctx.Module(); m.Enabled() {
65 if mixedBuildMod, ok := m.(MixedBuildBuildable); ok {
66 if mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx) {
67 mixedBuildMod.QueueBazelCall(ctx)
68 }
69 }
70 }
71}
72
Liz Kammerf29df7c2021-04-02 13:37:39 -040073type cqueryRequest interface {
74 // Name returns a string name for this request type. Such request type names must be unique,
75 // and must only consist of alphanumeric characters.
76 Name() string
77
78 // StarlarkFunctionBody returns a starlark function body to process this request type.
79 // The returned string is the body of a Starlark function which obtains
80 // all request-relevant information about a target and returns a string containing
81 // this information.
82 // The function should have the following properties:
Cole Faust97d15272022-11-22 14:08:59 -080083 // - The arguments are `target` (a configured target) and `id_string` (the label + configuration).
Liz Kammerf29df7c2021-04-02 13:37:39 -040084 // - The return value must be a string.
85 // - The function body should not be indented outside of its own scope.
86 StarlarkFunctionBody() string
87}
88
Chris Parsons787fb362021-10-14 18:43:51 -040089// Portion of cquery map key to describe target configuration.
90type configKey struct {
Liz Kammer0940b892022-03-18 15:55:04 -040091 arch string
92 osType OsType
Chris Parsons787fb362021-10-14 18:43:51 -040093}
94
Sasha Smundakfe9a5b82022-07-27 14:51:45 -070095func (c configKey) String() string {
96 return fmt.Sprintf("%s::%s", c.arch, c.osType)
97}
98
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040099// Map key to describe bazel cquery requests.
100type cqueryKey struct {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400101 label string
Liz Kammerf29df7c2021-04-02 13:37:39 -0400102 requestType cqueryRequest
Chris Parsons787fb362021-10-14 18:43:51 -0400103 configKey configKey
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400104}
105
Chris Parsons86dc2c22022-09-28 14:58:41 -0400106func makeCqueryKey(label string, cqueryRequest cqueryRequest, cfgKey configKey) cqueryKey {
107 if strings.HasPrefix(label, "//") {
108 // Normalize Bazel labels to specify main repository explicitly.
109 label = "@" + label
110 }
111 return cqueryKey{label, cqueryRequest, cfgKey}
112}
113
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700114func (c cqueryKey) String() string {
115 return fmt.Sprintf("cquery(%s,%s,%s)", c.label, c.requestType.Name(), c.configKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700116}
117
Chris Parsonsf874e462022-05-10 13:50:12 -0400118// BazelContext is a context object useful for interacting with Bazel during
119// the course of a build. Use of Bazel to evaluate part of the build graph
120// is referred to as a "mixed build". (Some modules are managed by Soong,
121// some are managed by Bazel). To facilitate interop between these build
122// subgraphs, Soong may make requests to Bazel and evaluate their responses
123// so that Soong modules may accurately depend on Bazel targets.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400124type BazelContext interface {
Chris Parsonsf874e462022-05-10 13:50:12 -0400125 // Add a cquery request to the bazel request queue. All queued requests
126 // will be sent to Bazel on a subsequent invocation of InvokeBazel.
127 QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey)
128
129 // ** Cquery Results Retrieval Functions
130 // The below functions pertain to retrieving cquery results from a prior
131 // InvokeBazel function call and parsing the results.
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400132
133 // Returns result files built by building the given bazel target label.
Chris Parsonsf874e462022-05-10 13:50:12 -0400134 GetOutputFiles(label string, cfgKey configKey) ([]string, error)
Chris Parsons8d6e4332021-02-22 16:13:50 -0500135
Chris Parsons944e7d02021-03-11 11:08:46 -0500136 // Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
Chris Parsonsf874e462022-05-10 13:50:12 -0400137 GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error)
Liz Kammer3f9e1552021-04-02 18:47:09 -0400138
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000139 // Returns the executable binary resultant from building together the python sources
Chris Parsonsf874e462022-05-10 13:50:12 -0400140 // TODO(b/232976601): Remove.
141 GetPythonBinary(label string, cfgKey configKey) (string, error)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000142
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700143 // Returns the results of the GetApexInfo query (including output files)
Liz Kammerbe6a7122022-11-04 16:05:11 -0400144 GetApexInfo(label string, cfgkey configKey) (cquery.ApexInfo, error)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700145
Sasha Smundakedd16662022-10-07 14:44:50 -0700146 // Returns the results of the GetCcUnstrippedInfo query
147 GetCcUnstrippedInfo(label string, cfgkey configKey) (cquery.CcUnstrippedInfo, error)
148
Chris Parsonsf874e462022-05-10 13:50:12 -0400149 // ** end Cquery Results Retrieval Functions
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400150
151 // Issues commands to Bazel to receive results for all cquery requests
Sasha Smundak4975c822022-11-16 15:28:18 -0800152 // queued in the BazelContext. The ctx argument is optional and is only
153 // used for performance data collection
154 InvokeBazel(config Config, ctx *Context) error
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400155
Chris Parsonsad876012022-08-20 14:48:32 -0400156 // Returns true if Bazel handling is enabled for the module with the given name.
157 // Note that this only implies "bazel mixed build" allowlisting. The caller
158 // should independently verify the module is eligible for Bazel handling
159 // (for example, that it is MixedBuildBuildable).
160 BazelAllowlisted(moduleName string) bool
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500161
162 // Returns the bazel output base (the root directory for all bazel intermediate outputs).
163 OutputBase() string
164
165 // Returns build statements which should get registered to reflect Bazel's outputs.
166 BuildStatementsToRegister() []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400167
168 // Returns the depsets defined in Bazel's aquery response.
169 AqueryDepsets() []bazel.AqueryDepset
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400170}
171
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400172type bazelRunner interface {
Jason Wu52cd1942022-09-08 15:37:57 +0000173 createBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand, extraFlags ...string) *exec.Cmd
174 issueBazelCommand(bazelCmd *exec.Cmd) (output string, errorMessage string, error error)
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400175}
176
177type bazelPaths struct {
MarkDacek0d5bca52022-10-10 20:07:48 +0000178 homeDir string
179 bazelPath string
180 outputBase string
181 workspaceDir string
182 soongOutDir string
183 metricsDir string
184 bazelDepsFile string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400185}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400186
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400187// A context object which tracks queued requests that need to be made to Bazel,
188// and their results after the requests have been made.
189type bazelContext struct {
190 bazelRunner
191 paths *bazelPaths
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400192 requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel
193 requestMutex sync.Mutex // requests can be written in parallel
194
195 results map[cqueryKey]string // Results of cquery requests after Bazel invocations
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500196
197 // Build statements which should get registered to reflect Bazel's outputs.
198 buildStatements []bazel.BuildStatement
Chris Parsons1a7aca02022-04-25 22:35:15 -0400199
200 // Depsets which should be used for Bazel's build statements.
201 depsets []bazel.AqueryDepset
Chris Parsonsad876012022-08-20 14:48:32 -0400202
203 // Per-module allowlist/denylist functionality to control whether analysis of
204 // modules are handled by Bazel. For modules which do not have a Bazel definition
205 // (or do not sufficiently support bazel handling via MixedBuildBuildable),
206 // this allowlist will have no effect, even if the module is explicitly allowlisted here.
207 // Per-module denylist to opt modules out of bazel handling.
208 bazelDisabledModules map[string]bool
209 // Per-module allowlist to opt modules in to bazel handling.
210 bazelEnabledModules map[string]bool
211 // If true, modules are bazel-enabled by default, unless present in bazelDisabledModules.
212 modulesDefaultToBazel bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400213}
214
215var _ BazelContext = &bazelContext{}
216
217// A bazel context to use when Bazel is disabled.
218type noopBazelContext struct{}
219
220var _ BazelContext = noopBazelContext{}
221
222// A bazel context to use for tests.
223type MockBazelContext struct {
Liz Kammera92e8442021-04-07 20:25:21 -0400224 OutputBaseDir string
225
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000226 LabelToOutputFiles map[string][]string
227 LabelToCcInfo map[string]cquery.CcInfo
228 LabelToPythonBinary map[string]string
Liz Kammerbe6a7122022-11-04 16:05:11 -0400229 LabelToApexInfo map[string]cquery.ApexInfo
Sasha Smundakedd16662022-10-07 14:44:50 -0700230 LabelToCcBinary map[string]cquery.CcUnstrippedInfo
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400231}
232
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700233func (m MockBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400234 panic("unimplemented")
Chris Parsons8d6e4332021-02-22 16:13:50 -0500235}
236
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700237func (m MockBazelContext) GetOutputFiles(label string, _ configKey) ([]string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400238 result, _ := m.LabelToOutputFiles[label]
239 return result, nil
Liz Kammer3f9e1552021-04-02 18:47:09 -0400240}
241
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700242func (m MockBazelContext) GetCcInfo(label string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400243 result, _ := m.LabelToCcInfo[label]
244 return result, nil
245}
246
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700247func (m MockBazelContext) GetPythonBinary(label string, _ configKey) (string, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400248 result, _ := m.LabelToPythonBinary[label]
249 return result, nil
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000250}
251
Liz Kammerbe6a7122022-11-04 16:05:11 -0400252func (m MockBazelContext) GetApexInfo(label string, _ configKey) (cquery.ApexInfo, error) {
Liz Kammer0e255ef2022-11-04 16:07:04 -0400253 result, _ := m.LabelToApexInfo[label]
254 return result, nil
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700255}
256
Sasha Smundakedd16662022-10-07 14:44:50 -0700257func (m MockBazelContext) GetCcUnstrippedInfo(label string, _ configKey) (cquery.CcUnstrippedInfo, error) {
258 result, _ := m.LabelToCcBinary[label]
259 return result, nil
260}
261
Sasha Smundak0e87b182022-12-01 11:46:11 -0800262func (m MockBazelContext) InvokeBazel(_ Config, _ *Context) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400263 panic("unimplemented")
264}
265
Sasha Smundak0e87b182022-12-01 11:46:11 -0800266func (m MockBazelContext) BazelAllowlisted(_ string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400267 return true
268}
269
Liz Kammera92e8442021-04-07 20:25:21 -0400270func (m MockBazelContext) OutputBase() string { return m.OutputBaseDir }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500271
272func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
273 return []bazel.BuildStatement{}
274}
275
Chris Parsons1a7aca02022-04-25 22:35:15 -0400276func (m MockBazelContext) AqueryDepsets() []bazel.AqueryDepset {
277 return []bazel.AqueryDepset{}
278}
279
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400280var _ BazelContext = MockBazelContext{}
281
Chris Parsonsf874e462022-05-10 13:50:12 -0400282func (bazelCtx *bazelContext) QueueBazelRequest(label string, requestType cqueryRequest, cfgKey configKey) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400283 key := makeCqueryKey(label, requestType, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400284 bazelCtx.requestMutex.Lock()
285 defer bazelCtx.requestMutex.Unlock()
286 bazelCtx.requests[key] = true
287}
288
289func (bazelCtx *bazelContext) GetOutputFiles(label string, cfgKey configKey) ([]string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400290 key := makeCqueryKey(label, cquery.GetOutputFiles, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400291 if rawString, ok := bazelCtx.results[key]; ok {
Chris Parsons944e7d02021-03-11 11:08:46 -0500292 bazelOutput := strings.TrimSpace(rawString)
Chris Parsons86dc2c22022-09-28 14:58:41 -0400293
Chris Parsonsf874e462022-05-10 13:50:12 -0400294 return cquery.GetOutputFiles.ParseResult(bazelOutput), nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400295 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400296 return nil, fmt.Errorf("no bazel response found for %v", key)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400297}
298
Chris Parsonsf874e462022-05-10 13:50:12 -0400299func (bazelCtx *bazelContext) GetCcInfo(label string, cfgKey configKey) (cquery.CcInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400300 key := makeCqueryKey(label, cquery.GetCcInfo, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400301 if rawString, ok := bazelCtx.results[key]; ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000302 bazelOutput := strings.TrimSpace(rawString)
Chris Parsonsf874e462022-05-10 13:50:12 -0400303 return cquery.GetCcInfo.ParseResult(bazelOutput)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000304 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400305 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 +0000306}
307
Chris Parsonsf874e462022-05-10 13:50:12 -0400308func (bazelCtx *bazelContext) GetPythonBinary(label string, cfgKey configKey) (string, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400309 key := makeCqueryKey(label, cquery.GetPythonBinary, cfgKey)
Chris Parsonsf874e462022-05-10 13:50:12 -0400310 if rawString, ok := bazelCtx.results[key]; ok {
311 bazelOutput := strings.TrimSpace(rawString)
312 return cquery.GetPythonBinary.ParseResult(bazelOutput), nil
313 }
314 return "", fmt.Errorf("no bazel response found for %v", key)
315}
316
Liz Kammerbe6a7122022-11-04 16:05:11 -0400317func (bazelCtx *bazelContext) GetApexInfo(label string, cfgKey configKey) (cquery.ApexInfo, error) {
Chris Parsons86dc2c22022-09-28 14:58:41 -0400318 key := makeCqueryKey(label, cquery.GetApexInfo, cfgKey)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700319 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500320 return cquery.GetApexInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700321 }
Liz Kammerbe6a7122022-11-04 16:05:11 -0400322 return cquery.ApexInfo{}, fmt.Errorf("no bazel response found for %v", key)
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700323}
324
Sasha Smundakedd16662022-10-07 14:44:50 -0700325func (bazelCtx *bazelContext) GetCcUnstrippedInfo(label string, cfgKey configKey) (cquery.CcUnstrippedInfo, error) {
326 key := makeCqueryKey(label, cquery.GetCcUnstrippedInfo, cfgKey)
327 if rawString, ok := bazelCtx.results[key]; ok {
Liz Kammer1b7ed9b2022-11-09 10:05:05 -0500328 return cquery.GetCcUnstrippedInfo.ParseResult(strings.TrimSpace(rawString))
Sasha Smundakedd16662022-10-07 14:44:50 -0700329 }
330 return cquery.CcUnstrippedInfo{}, fmt.Errorf("no bazel response for %s", key)
331}
332
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700333func (n noopBazelContext) QueueBazelRequest(_ string, _ cqueryRequest, _ configKey) {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500334 panic("unimplemented")
335}
336
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700337func (n noopBazelContext) GetOutputFiles(_ string, _ configKey) ([]string, error) {
Chris Parsons808d84c2021-03-09 20:43:32 -0500338 panic("unimplemented")
339}
340
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700341func (n noopBazelContext) GetCcInfo(_ string, _ configKey) (cquery.CcInfo, error) {
Chris Parsonsf874e462022-05-10 13:50:12 -0400342 panic("unimplemented")
343}
344
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700345func (n noopBazelContext) GetPythonBinary(_ string, _ configKey) (string, error) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa05a2552021-08-11 16:48:30 +0000346 panic("unimplemented")
347}
348
Liz Kammerbe6a7122022-11-04 16:05:11 -0400349func (n noopBazelContext) GetApexInfo(_ string, _ configKey) (cquery.ApexInfo, error) {
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700350 panic("unimplemented")
351}
352
Sasha Smundakedd16662022-10-07 14:44:50 -0700353func (n noopBazelContext) GetCcUnstrippedInfo(_ string, _ configKey) (cquery.CcUnstrippedInfo, error) {
354 //TODO implement me
355 panic("implement me")
356}
357
Sasha Smundak0e87b182022-12-01 11:46:11 -0800358func (n noopBazelContext) InvokeBazel(_ Config, _ *Context) error {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400359 panic("unimplemented")
360}
361
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500362func (m noopBazelContext) OutputBase() string {
363 return ""
364}
365
Sasha Smundak0e87b182022-12-01 11:46:11 -0800366func (n noopBazelContext) BazelAllowlisted(_ string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400367 return false
368}
369
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500370func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
371 return []bazel.BuildStatement{}
372}
373
Chris Parsons1a7aca02022-04-25 22:35:15 -0400374func (m noopBazelContext) AqueryDepsets() []bazel.AqueryDepset {
375 return []bazel.AqueryDepset{}
376}
377
Cole Faust705968d2022-12-14 11:32:05 -0800378func GetBazelEnabledAndDisabledModules(buildMode SoongBuildMode, forceEnabled map[string]struct{}) (map[string]bool, map[string]bool) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400379 disabledModules := map[string]bool{}
380 enabledModules := map[string]bool{}
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800381 addToStringSet := func(set map[string]bool, items []string) {
382 for _, item := range items {
383 set[item] = true
384 }
385 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400386
Cole Faust705968d2022-12-14 11:32:05 -0800387 switch buildMode {
Chris Parsonsef615e52022-08-18 22:04:11 -0400388 case BazelProdMode:
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800389 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800390 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000391 enabledModules[enabledAdHocModule] = true
392 }
MarkDacekb78465d2022-10-18 20:10:16 +0000393 case BazelStagingMode:
Chris Parsons66fc7452022-11-04 13:26:17 -0400394 // Staging mode includes all prod modules plus all staging modules.
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800395 addToStringSet(enabledModules, allowlists.ProdMixedBuildsEnabledList)
396 addToStringSet(enabledModules, allowlists.StagingMixedBuildsEnabledList)
Cole Faust705968d2022-12-14 11:32:05 -0800397 for enabledAdHocModule := range forceEnabled {
MarkDacekd06db5d2022-11-29 00:47:59 +0000398 enabledModules[enabledAdHocModule] = true
399 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400400 case BazelDevMode:
Chris Parsonsef615e52022-08-18 22:04:11 -0400401 // Don't use partially-converted cc_library targets in mixed builds,
402 // since mixed builds would generally rely on both static and shared
403 // variants of a cc_library.
Sasha Smundak0e87b182022-12-01 11:46:11 -0800404 for staticOnlyModule := range GetBp2BuildAllowList().ccLibraryStaticOnly {
Chris Parsonsef615e52022-08-18 22:04:11 -0400405 disabledModules[staticOnlyModule] = true
406 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800407 addToStringSet(disabledModules, allowlists.MixedBuildsDisabledList)
Chris Parsonsef615e52022-08-18 22:04:11 -0400408 default:
Cole Faust705968d2022-12-14 11:32:05 -0800409 panic("Expected BazelProdMode, BazelStagingMode, or BazelDevMode")
410 }
411 return enabledModules, disabledModules
412}
413
414func GetBazelEnabledModules(buildMode SoongBuildMode) []string {
415 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(buildMode, nil)
416 enabledList := make([]string, 0, len(enabledModules))
417 for module := range enabledModules {
418 if !disabledModules[module] {
419 enabledList = append(enabledList, module)
420 }
421 }
422 sort.Strings(enabledList)
423 return enabledList
424}
425
426func NewBazelContext(c *config) (BazelContext, error) {
427 if c.BuildMode != BazelProdMode && c.BuildMode != BazelStagingMode && c.BuildMode != BazelDevMode {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400428 return noopBazelContext{}, nil
429 }
430
Cole Faust705968d2022-12-14 11:32:05 -0800431 enabledModules, disabledModules := GetBazelEnabledAndDisabledModules(c.BuildMode, c.BazelModulesForceEnabledByFlag())
432
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800433 paths := bazelPaths{
434 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400435 }
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800436 var missing []string
437 vars := []struct {
438 name string
439 ptr *string
440 }{
441 {"BAZEL_HOME", &paths.homeDir},
442 {"BAZEL_PATH", &paths.bazelPath},
443 {"BAZEL_OUTPUT_BASE", &paths.outputBase},
444 {"BAZEL_WORKSPACE", &paths.workspaceDir},
445 {"BAZEL_METRICS_DIR", &paths.metricsDir},
446 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile},
447 }
448 for _, v := range vars {
449 if s := c.Getenv(v.name); len(s) > 1 {
450 *v.ptr = s
451 } else {
452 missing = append(missing, v.name)
453 }
454 }
455 if len(missing) > 0 {
456 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
457 }
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400458 return &bazelContext{
Chris Parsonsad876012022-08-20 14:48:32 -0400459 bazelRunner: &builtinBazelRunner{},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800460 paths: &paths,
Chris Parsonsad876012022-08-20 14:48:32 -0400461 requests: make(map[cqueryKey]bool),
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800462 modulesDefaultToBazel: c.BuildMode == BazelDevMode,
Chris Parsonsef615e52022-08-18 22:04:11 -0400463 bazelEnabledModules: enabledModules,
Chris Parsonsad876012022-08-20 14:48:32 -0400464 bazelDisabledModules: disabledModules,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400465 }, nil
466}
467
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400468func (p *bazelPaths) BazelMetricsDir() string {
469 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000470}
471
Chris Parsonsad876012022-08-20 14:48:32 -0400472func (context *bazelContext) BazelAllowlisted(moduleName string) bool {
473 if context.bazelDisabledModules[moduleName] {
474 return false
475 }
476 if context.bazelEnabledModules[moduleName] {
477 return true
478 }
479 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400480}
481
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400482func pwdPrefix() string {
483 // Darwin doesn't have /proc
484 if runtime.GOOS != "darwin" {
485 return "PWD=/proc/self/cwd"
486 }
487 return ""
488}
489
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400490type bazelCommand struct {
491 command string
492 // query or label
493 expression string
494}
495
496type mockBazelRunner struct {
497 bazelCommandResults map[bazelCommand]string
Jason Wu52cd1942022-09-08 15:37:57 +0000498 // use *exec.Cmd as a key to get the bazelCommand, the map will be used in issueBazelCommand()
499 // Register createBazelCommand() invocations. Later, an
500 // issueBazelCommand() invocation can be mapped to the *exec.Cmd instance
501 // and then to the expected result via bazelCommandResults
502 tokens map[*exec.Cmd]bazelCommand
503 commands []bazelCommand
504 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400505}
506
Sasha Smundak0e87b182022-12-01 11:46:11 -0800507func (r *mockBazelRunner) createBazelCommand(_ *bazelPaths, _ bazel.RunName,
Jason Wu52cd1942022-09-08 15:37:57 +0000508 command bazelCommand, extraFlags ...string) *exec.Cmd {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400509 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700510 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Jason Wu52cd1942022-09-08 15:37:57 +0000511 cmd := &exec.Cmd{}
512 if r.tokens == nil {
513 r.tokens = make(map[*exec.Cmd]bazelCommand)
514 }
515 r.tokens[cmd] = command
516 return cmd
517}
518
519func (r *mockBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
520 if command, ok := r.tokens[bazelCmd]; ok {
521 return r.bazelCommandResults[command], "", nil
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400522 }
523 return "", "", nil
524}
525
526type builtinBazelRunner struct{}
527
Chris Parsons808d84c2021-03-09 20:43:32 -0500528// Issues the given bazel command with given build label and additional flags.
529// Returns (stdout, stderr, error). The first and second return values are strings
530// containing the stdout and stderr of the run command, and an error is returned if
531// the invocation returned an error code.
Jason Wu52cd1942022-09-08 15:37:57 +0000532func (r *builtinBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
533 stderr := &bytes.Buffer{}
534 bazelCmd.Stderr = stderr
535 if output, err := bazelCmd.Output(); err != nil {
536 return "", string(stderr.Bytes()),
Sasha Smundak0e87b182022-12-01 11:46:11 -0800537 fmt.Errorf("bazel command failed: %s\n---command---\n%s\n---env---\n%s\n---stderr---\n%s---",
538 err, bazelCmd, strings.Join(bazelCmd.Env, "\n"), stderr)
Jason Wu52cd1942022-09-08 15:37:57 +0000539 } else {
540 return string(output), string(stderr.Bytes()), nil
541 }
542}
543
544func (r *builtinBazelRunner) createBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
545 extraFlags ...string) *exec.Cmd {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000546 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000547 "--output_base=" + absolutePath(paths.outputBase),
548 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700549 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700550 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700551 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400552
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700553 // Set default platforms to canonicalized values for mixed builds requests.
554 // If these are set in the bazelrc, they will have values that are
555 // non-canonicalized to @sourceroot labels, and thus be invalid when
556 // referenced from the buildroot.
557 //
558 // The actual platform values here may be overridden by configuration
559 // transitions from the buildroot.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700560 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700561 // This should be parameterized on the host OS, but let's restrict to linux
562 // to keep things simple for now.
563 fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"),
564
565 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
566 "--experimental_repository_disable_download",
567
568 // Suppress noise
569 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500570 "--noshow_progress",
571 "--norun_validations",
572 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400573 cmdFlags = append(cmdFlags, extraFlags...)
574
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400575 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200576 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700577 extraEnv := []string{
578 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200579 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700580 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700581 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000582 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700583 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500584 // Disables local host detection of gcc; toolchain information is defined
585 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700586 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
587 }
588 bazelCmd.Env = append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400589
Jason Wu52cd1942022-09-08 15:37:57 +0000590 return bazelCmd
591}
592
593func printableCqueryCommand(bazelCmd *exec.Cmd) string {
594 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(bazelCmd.Args, "\" \"") + "\""
595 return outputString
596
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400597}
598
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400599func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500600 // TODO(cparsons): Define configuration transitions programmatically based
601 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400602 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500603#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400604# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500605#####################################################
606
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400607def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500608 return {
Chris Parsons787fb362021-10-14 18:43:51 -0400609 "//command_line_option:platforms": "@//build/bazel/platforms:%s_%s" % (attr.os, attr.arch),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500610 }
611
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400612_config_node_transition = transition(
613 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500614 inputs = [],
615 outputs = [
616 "//command_line_option:platforms",
617 ],
618)
619
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400620def _passthrough_rule_impl(ctx):
621 return [DefaultInfo(files = depset(ctx.files.deps))]
622
623config_node = rule(
624 implementation = _passthrough_rule_impl,
625 attrs = {
626 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400627 "os" : attr.string(mandatory = True),
628 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400629 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
630 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500631)
632
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400633
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500634# Rule representing the root of the build, to depend on all Bazel targets that
635# are required for the build. Building this target will build the entire Bazel
636# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400637mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400638 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500639 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400640 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500641 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400642)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500643
644def _phony_root_impl(ctx):
645 return []
646
647# Rule to depend on other targets but build nothing.
648# This is useful as follows: building a target of this rule will generate
649# symlink forests for all dependencies of the target, without executing any
650# actions of the build.
651phony_root = rule(
652 implementation = _phony_root_impl,
653 attrs = {"deps" : attr.label_list()},
654)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400655`
656 return []byte(contents)
657}
658
659func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500660 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
661 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400662 formatString := `
663# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400664load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
665
666%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400667
668mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400669 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000670 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400671)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500672
673phony_root(name = "phonyroot",
674 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000675 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500676)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400677`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400678 configNodeFormatString := `
679config_node(name = "%s",
680 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400681 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400682 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000683 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400684)
685`
686
687 configNodesSection := ""
688
Chris Parsons787fb362021-10-14 18:43:51 -0400689 labelsByConfig := map[string][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400690 for val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200691 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400692 configString := getConfigString(val)
693 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400694 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400695
Jingwen Chen1e347862021-09-02 12:11:49 +0000696 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400697 for configString, labels := range labelsByConfig {
698 configTokens := strings.Split(configString, "|")
699 if len(configTokens) != 2 {
700 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000701 }
Chris Parsons787fb362021-10-14 18:43:51 -0400702 archString := configTokens[0]
703 osString := configTokens[1]
704 targetString := fmt.Sprintf("%s_%s", osString, archString)
705 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
706 labelsString := strings.Join(labels, ",\n ")
707 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400708 }
709
Jingwen Chen1e347862021-09-02 12:11:49 +0000710 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400711}
712
Chris Parsons944e7d02021-03-11 11:08:46 -0500713func indent(original string) string {
714 result := ""
715 for _, line := range strings.Split(original, "\n") {
716 result += " " + line + "\n"
717 }
718 return result
719}
720
Chris Parsons808d84c2021-03-09 20:43:32 -0500721// Returns the file contents of the buildroot.cquery file that should be used for the cquery
722// expression in order to obtain information about buildroot and its dependencies.
723// The contents of this file depend on the bazelContext's requests; requests are enumerated
724// and grouped by their request type. The data retrieved for each label depends on its
725// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400726func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400727 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400728 for val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500729 cqueryId := getCqueryId(val)
730 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
731 requestTypeToCqueryIdEntries[val.requestType] =
732 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
733 }
734 labelRegistrationMapSection := ""
735 functionDefSection := ""
736 mainSwitchSection := ""
737
738 mapDeclarationFormatString := `
739%s = {
740 %s
741}
742`
743 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800744def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500745%s
746`
747 mainSwitchSectionFormatString := `
748 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800749 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500750`
751
Usta Shrestha0b52d832022-02-04 21:37:39 -0500752 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500753 labelMapName := requestType.Name() + "_Labels"
754 functionName := requestType.Name() + "_Fn"
755 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
756 labelMapName,
757 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
758 functionDefSection += fmt.Sprintf(functionDefFormatString,
759 functionName,
760 indent(requestType.StarlarkFunctionBody()))
761 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
762 labelMapName, functionName)
763 }
764
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400765 formatString := `
766# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400767
Usta Shrestha79fccef2022-09-02 18:37:40 -0400768# a drop-in replacement for json.encode(), not available in cquery environment
769# TODO(cparsons): bring json module in and remove this function
770def json_encode(input):
771 # Avoiding recursion by limiting
772 # - a dict to contain anything except a dict
773 # - a list to contain only primitives
774 def encode_primitive(p):
775 t = type(p)
776 if t == "string" or t == "int":
777 return repr(p)
778 fail("unsupported value '%%s' of type '%%s'" %% (p, type(p)))
779
780 def encode_list(list):
781 return "[%%s]" %% ", ".join([encode_primitive(item) for item in list])
782
783 def encode_list_or_primitive(v):
784 return encode_list(v) if type(v) == "list" else encode_primitive(v)
785
786 if type(input) == "dict":
787 # TODO(juu): the result is read line by line so can't use '\n' yet
788 kv_pairs = [("%%s: %%s" %% (encode_primitive(k), encode_list_or_primitive(v))) for (k, v) in input.items()]
789 return "{ %%s }" %% ", ".join(kv_pairs)
790 else:
791 return encode_list_or_primitive(input)
792
Chris Parsons944e7d02021-03-11 11:08:46 -0500793# Label Map Section
794%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500795
Chris Parsons944e7d02021-03-11 11:08:46 -0500796# Function Def Section
797%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500798
799def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400800 # TODO(b/199363072): filegroups and file targets aren't associated with any
801 # specific platform architecture in mixed builds. This is consistent with how
802 # Soong treats filegroups, but it may not be the case with manually-written
803 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500804 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000805 if buildoptions == None:
806 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400807 # any specific platform architecture in mixed builds, so use the host.
808 return "x86_64|linux"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500809 platforms = build_options(target)["//command_line_option:platforms"]
810 if len(platforms) != 1:
811 # An individual configured target should have only one platform architecture.
812 # Note that it's fine for there to be multiple architectures for the same label,
813 # but each is its own configured target.
814 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
815 platform_name = build_options(target)["//command_line_option:platforms"][0].name
816 if platform_name == "host":
817 return "HOST"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400818 elif platform_name.startswith("android_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400819 return platform_name[len("android_"):] + "|" + platform_name[:len("android_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400820 elif platform_name.startswith("linux_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400821 return platform_name[len("linux_"):] + "|" + platform_name[:len("linux_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400822 else:
823 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500824 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500825
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400826def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500827 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500828
Chris Parsons86dc2c22022-09-28 14:58:41 -0400829 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
830 if id_string.startswith("//"):
831 id_string = "@" + id_string
832
Chris Parsons944e7d02021-03-11 11:08:46 -0500833 # Main switch section
834 %s
835 # This target was not requested via cquery, and thus must be a dependency
836 # of a requested target.
837 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400838`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400839
Chris Parsons944e7d02021-03-11 11:08:46 -0500840 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
841 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400842}
843
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200844// Returns a path containing build-related metadata required for interfacing
845// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400846func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200847 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500848}
849
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200850// Returns the path where the contents of the @soong_injection repository live.
851// It is used by Soong to tell Bazel things it cannot over the command line.
852func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200853 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200854}
855
856// Returns the path of the synthetic Bazel workspace that contains a symlink
857// forest composed the whole source tree and BUILD files generated by bp2build.
858func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200859 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200860}
861
Jingwen Chen8c523582021-06-01 11:19:53 +0000862// Returns the path to the top level out dir ($OUT_DIR).
863func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200864 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000865}
866
Sasha Smundak4975c822022-11-16 15:28:18 -0800867const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
868
869var (
870 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
871 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
872 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
873)
874
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400875// Issues commands to Bazel to receive results for all cquery requests
876// queued in the BazelContext.
Sasha Smundak4975c822022-11-16 15:28:18 -0800877func (context *bazelContext) InvokeBazel(config Config, ctx *Context) error {
878 if ctx != nil {
879 ctx.EventHandler.Begin("bazel")
880 defer ctx.EventHandler.End("bazel")
881 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400882
Sasha Smundak4975c822022-11-16 15:28:18 -0800883 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
884 if err := os.MkdirAll(metricsDir, 0777); err != nil {
885 return err
886 }
887 }
888 context.results = make(map[cqueryKey]string)
889 if err := context.runCquery(ctx); err != nil {
890 return err
891 }
892 if err := context.runAquery(config, ctx); err != nil {
893 return err
894 }
895 if err := context.generateBazelSymlinks(ctx); err != nil {
896 return err
897 }
898
899 // Clear requests.
900 context.requests = map[cqueryKey]bool{}
901 return nil
902}
903
904func (context *bazelContext) runCquery(ctx *Context) error {
905 if ctx != nil {
906 ctx.EventHandler.Begin("cquery")
907 defer ctx.EventHandler.End("cquery")
908 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200909 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200910 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
911 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
912 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -0500913 if err != nil {
914 return err
915 }
916 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800917 if err := os.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200918 return err
919 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800920 if err := os.WriteFile(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400921 return err
922 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800923 if err := os.WriteFile(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400924 return err
925 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200926 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Sasha Smundak0e87b182022-12-01 11:46:11 -0800927 if err := os.WriteFile(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400928 return err
929 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000930
Jason Wu52cd1942022-09-08 15:37:57 +0000931 cqueryCommandWithFlag := context.createBazelCommand(context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700932 "--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
Wei Licbd181c2022-11-16 08:59:23 -0800933 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCommandWithFlag)
934 if cqueryErr != nil {
935 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -0500936 }
Jason Wu52cd1942022-09-08 15:37:57 +0000937 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", printableCqueryCommand(cqueryCommandWithFlag))
Sasha Smundak0e87b182022-12-01 11:46:11 -0800938 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400939 return err
940 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400941 cqueryResults := map[string]string{}
942 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
943 if strings.Contains(outputLine, ">>") {
944 splitLine := strings.SplitN(outputLine, ">>", 2)
945 cqueryResults[splitLine[0]] = splitLine[1]
946 }
947 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500948 for val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500949 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -0500950 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400951 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500952 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -0800953 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400954 }
955 }
Sasha Smundak4975c822022-11-16 15:28:18 -0800956 return nil
957}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400958
Sasha Smundak4975c822022-11-16 15:28:18 -0800959func (context *bazelContext) runAquery(config Config, ctx *Context) error {
960 if ctx != nil {
961 ctx.EventHandler.Begin("aquery")
962 defer ctx.EventHandler.End("aquery")
963 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500964 // Issue an aquery command to retrieve action information about the bazel build tree.
965 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700966 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
967 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +0000968 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -0700969 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700970 extraFlags = append(extraFlags, "--collect_code_coverage")
971 paths := make([]string, 0, 2)
972 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -0800973 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -0800974 // TODO(b/259404593) convert path wildcard to regex values
975 if p[i] == "*" {
976 p[i] = ".*"
977 }
978 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700979 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
980 }
981 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
982 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
983 }
984 if len(paths) > 0 {
985 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -0700986 }
987 }
Sasha Smundak4975c822022-11-16 15:28:18 -0800988 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
989 extraFlags...))
990 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -0500991 return err
992 }
Sasha Smundak4975c822022-11-16 15:28:18 -0800993 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
994 return err
995}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500996
Sasha Smundak4975c822022-11-16 15:28:18 -0800997func (context *bazelContext) generateBazelSymlinks(ctx *Context) error {
998 if ctx != nil {
999 ctx.EventHandler.Begin("symlinks")
1000 defer ctx.EventHandler.End("symlinks")
1001 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001002 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1003 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1004 // but some of symlinks may be required to resolve source dependencies of the build.
Sasha Smundak4975c822022-11-16 15:28:18 -08001005 _, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd))
1006 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001007}
Chris Parsonsa798d962020-10-12 23:44:08 -04001008
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001009func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
1010 return context.buildStatements
1011}
1012
Chris Parsons1a7aca02022-04-25 22:35:15 -04001013func (context *bazelContext) AqueryDepsets() []bazel.AqueryDepset {
1014 return context.depsets
1015}
1016
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001017func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001018 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001019}
1020
Chris Parsonsa798d962020-10-12 23:44:08 -04001021// Singleton used for registering BUILD file ninja dependencies (needed
1022// for correctness of builds which use Bazel.
1023func BazelSingleton() Singleton {
1024 return &bazelSingleton{}
1025}
1026
1027type bazelSingleton struct{}
1028
1029func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001030 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001031 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001032 return
1033 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001034
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001035 // Add ninja file dependencies for files which all bazel invocations require.
1036 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001037 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001038 ctx.AddNinjaFileDeps(bazelBuildList)
1039
Sasha Smundak0e87b182022-12-01 11:46:11 -08001040 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001041 if err != nil {
1042 ctx.Errorf(err.Error())
1043 }
1044 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1045 for _, file := range files {
1046 ctx.AddNinjaFileDeps(file)
1047 }
1048
Chris Parsons1a7aca02022-04-25 22:35:15 -04001049 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1050 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001051 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001052 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1053 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001054 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1055 }
1056 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001057 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1058 if artifactPath == "bazel-out/volatile-status.txt" {
1059 // See https://bazel.build/docs/user-manual#workspace-status
1060 orderOnlies = append(orderOnlies, pathInBazelOut)
1061 } else {
1062 outputs = append(outputs, pathInBazelOut)
1063 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001064 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001065 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001066 ctx.Build(pctx, BuildParams{
1067 Rule: blueprint.Phony,
1068 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1069 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001070 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001071 })
1072 }
1073
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001074 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1075 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001076 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -07001077 if len(buildStatement.Command) > 0 {
1078 rule := NewRuleBuilder(pctx, ctx)
1079 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1080 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1081 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1082 continue
1083 }
1084 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1085 // and thus require special treatment. If BuildStatement were an interface implementing
1086 // buildRule(ctx) function, the code here would just call it.
1087 // Unfortunately, the BuildStatement is defined in
1088 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1089 // because this would cause circular dependency. So, until we move aquery processing
1090 // to the 'android' package, we need to handle special cases here.
1091 if buildStatement.Mnemonic == "FileWrite" || buildStatement.Mnemonic == "SourceSymlinkManifest" {
1092 // Pass file contents as the value of the rule's "content" argument.
1093 // Escape newlines and $ in the contents (the action "writeBazelFile" restores "\\n"
1094 // back to the newline, and Ninja reads $$ as $.
1095 escaped := strings.ReplaceAll(strings.ReplaceAll(buildStatement.FileContents, "\n", "\\n"),
1096 "$", "$$")
1097 ctx.Build(pctx, BuildParams{
1098 Rule: writeBazelFile,
1099 Output: PathForBazelOut(ctx, buildStatement.OutputPaths[0]),
1100 Description: fmt.Sprintf("%s %s", buildStatement.Mnemonic, buildStatement.OutputPaths[0]),
1101 Args: map[string]string{
1102 "content": escaped,
1103 },
1104 })
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001105 } else if buildStatement.Mnemonic == "SymlinkTree" {
1106 // build-runfiles arguments are the manifest file and the target directory
1107 // where it creates the symlink tree according to this manifest (and then
1108 // writes the MANIFEST file to it).
1109 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1110 outManifestPath := outManifest.String()
1111 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1112 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1113 }
1114 outDir := filepath.Dir(outManifestPath)
1115 ctx.Build(pctx, BuildParams{
1116 Rule: buildRunfilesRule,
1117 Output: outManifest,
1118 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1119 Description: "symlink tree for " + outDir,
1120 Args: map[string]string{
1121 "outDir": outDir,
1122 },
1123 })
Sasha Smundak1da064c2022-06-08 16:36:16 -07001124 } else {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001125 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001126 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001127 }
1128}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001129
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001130// Register bazel-owned build statements (obtained from the aquery invocation).
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001131func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001132 // executionRoot is the action cwd.
1133 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1134
1135 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1136 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001137 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001138 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001139 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001140 }
1141 cmd.Text("&&")
1142 }
1143
1144 for _, pair := range buildStatement.Env {
1145 // Set per-action env variables, if any.
1146 cmd.Flag(pair.Key + "=" + pair.Value)
1147 }
1148
1149 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001150 if len(buildStatement.Command) > 16*1024 {
1151 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1152 WriteFileRule(ctx, commandFile, buildStatement.Command)
1153
1154 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1155 } else {
1156 cmd.Text(buildStatement.Command)
1157 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001158
1159 for _, outputPath := range buildStatement.OutputPaths {
1160 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1161 }
1162 for _, inputPath := range buildStatement.InputPaths {
1163 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1164 }
1165 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1166 otherDepsetName := bazelDepsetName(inputDepsetHash)
1167 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1168 }
1169
1170 if depfile := buildStatement.Depfile; depfile != nil {
1171 // The paths in depfile are relative to `executionRoot`.
1172 // Hence, they need to be corrected by replacing "bazel-out"
1173 // with the full `bazelOutDir`.
1174 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1175 // would be deemed missing.
1176 // (Note: The regexp uses a capture group because the version of sed
1177 // does not support a look-behind pattern.)
1178 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1179 bazelOutDir, *depfile)
1180 cmd.Text(replacement)
1181 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1182 }
1183
1184 for _, symlinkPath := range buildStatement.SymlinkPaths {
1185 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1186 }
1187}
1188
Chris Parsons8d6e4332021-02-22 16:13:50 -05001189func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001190 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001191}
1192
Chris Parsons787fb362021-10-14 18:43:51 -04001193func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001194 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001195 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001196 if key.configKey.osType.Class == Device {
1197 // For the generic Android, the expected result is "target|android", which
1198 // corresponds to the product_variable_config named "android_target" in
1199 // build/bazel/platforms/BUILD.bazel.
1200 arch = "target"
1201 } else {
1202 // Use host platform, which is currently hardcoded to be x86_64.
1203 arch = "x86_64"
1204 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001205 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001206 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001207 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001208 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001209 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001210 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001211 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -04001212}
1213
Chris Parsonsf874e462022-05-10 13:50:12 -04001214func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001215 return configKey{
1216 // use string because Arch is not a valid key in go
1217 arch: ctx.Arch().String(),
1218 osType: ctx.Os(),
1219 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001220}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001221
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001222func bazelDepsetName(contentHash string) string {
1223 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001224}