blob: b56d31b431352633117c9a07dc9b8580b783f837 [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
Paul Duffin184366a2022-12-21 15:55:33 +0000440
441 // True if the environment variable needs to be tracked so that changes to the variable
442 // cause the ninja file to be regenerated, false otherwise. False should only be set for
443 // environment variables that have no effect on the generated ninja file.
444 track bool
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800445 }{
Paul Duffin184366a2022-12-21 15:55:33 +0000446 {"BAZEL_HOME", &paths.homeDir, true},
447 {"BAZEL_PATH", &paths.bazelPath, true},
448 {"BAZEL_OUTPUT_BASE", &paths.outputBase, true},
449 {"BAZEL_WORKSPACE", &paths.workspaceDir, true},
450 {"BAZEL_METRICS_DIR", &paths.metricsDir, false},
451 {"BAZEL_DEPS_FILE", &paths.bazelDepsFile, true},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800452 }
453 for _, v := range vars {
Paul Duffin184366a2022-12-21 15:55:33 +0000454 if v.track {
455 if s := c.Getenv(v.name); len(s) > 1 {
456 *v.ptr = s
457 continue
458 }
459 } else if s, ok := c.env[v.name]; ok {
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800460 *v.ptr = s
461 } else {
462 missing = append(missing, v.name)
463 }
464 }
465 if len(missing) > 0 {
466 return nil, fmt.Errorf("missing required env vars to use bazel: %s", missing)
467 }
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400468 return &bazelContext{
Chris Parsonsad876012022-08-20 14:48:32 -0400469 bazelRunner: &builtinBazelRunner{},
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800470 paths: &paths,
Chris Parsonsad876012022-08-20 14:48:32 -0400471 requests: make(map[cqueryKey]bool),
Sasha Smundakdc87f2d2022-12-06 20:27:54 -0800472 modulesDefaultToBazel: c.BuildMode == BazelDevMode,
Chris Parsonsef615e52022-08-18 22:04:11 -0400473 bazelEnabledModules: enabledModules,
Chris Parsonsad876012022-08-20 14:48:32 -0400474 bazelDisabledModules: disabledModules,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400475 }, nil
476}
477
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400478func (p *bazelPaths) BazelMetricsDir() string {
479 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000480}
481
Chris Parsonsad876012022-08-20 14:48:32 -0400482func (context *bazelContext) BazelAllowlisted(moduleName string) bool {
483 if context.bazelDisabledModules[moduleName] {
484 return false
485 }
486 if context.bazelEnabledModules[moduleName] {
487 return true
488 }
489 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400490}
491
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400492func pwdPrefix() string {
493 // Darwin doesn't have /proc
494 if runtime.GOOS != "darwin" {
495 return "PWD=/proc/self/cwd"
496 }
497 return ""
498}
499
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400500type bazelCommand struct {
501 command string
502 // query or label
503 expression string
504}
505
506type mockBazelRunner struct {
507 bazelCommandResults map[bazelCommand]string
Jason Wu52cd1942022-09-08 15:37:57 +0000508 // use *exec.Cmd as a key to get the bazelCommand, the map will be used in issueBazelCommand()
509 // Register createBazelCommand() invocations. Later, an
510 // issueBazelCommand() invocation can be mapped to the *exec.Cmd instance
511 // and then to the expected result via bazelCommandResults
512 tokens map[*exec.Cmd]bazelCommand
513 commands []bazelCommand
514 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400515}
516
Sasha Smundak0e87b182022-12-01 11:46:11 -0800517func (r *mockBazelRunner) createBazelCommand(_ *bazelPaths, _ bazel.RunName,
Jason Wu52cd1942022-09-08 15:37:57 +0000518 command bazelCommand, extraFlags ...string) *exec.Cmd {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400519 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700520 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Jason Wu52cd1942022-09-08 15:37:57 +0000521 cmd := &exec.Cmd{}
522 if r.tokens == nil {
523 r.tokens = make(map[*exec.Cmd]bazelCommand)
524 }
525 r.tokens[cmd] = command
526 return cmd
527}
528
529func (r *mockBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
530 if command, ok := r.tokens[bazelCmd]; ok {
531 return r.bazelCommandResults[command], "", nil
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400532 }
533 return "", "", nil
534}
535
536type builtinBazelRunner struct{}
537
Chris Parsons808d84c2021-03-09 20:43:32 -0500538// Issues the given bazel command with given build label and additional flags.
539// Returns (stdout, stderr, error). The first and second return values are strings
540// containing the stdout and stderr of the run command, and an error is returned if
541// the invocation returned an error code.
Jason Wu52cd1942022-09-08 15:37:57 +0000542func (r *builtinBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
543 stderr := &bytes.Buffer{}
544 bazelCmd.Stderr = stderr
545 if output, err := bazelCmd.Output(); err != nil {
546 return "", string(stderr.Bytes()),
Sasha Smundak0e87b182022-12-01 11:46:11 -0800547 fmt.Errorf("bazel command failed: %s\n---command---\n%s\n---env---\n%s\n---stderr---\n%s---",
548 err, bazelCmd, strings.Join(bazelCmd.Env, "\n"), stderr)
Jason Wu52cd1942022-09-08 15:37:57 +0000549 } else {
550 return string(output), string(stderr.Bytes()), nil
551 }
552}
553
554func (r *builtinBazelRunner) createBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
555 extraFlags ...string) *exec.Cmd {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000556 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000557 "--output_base=" + absolutePath(paths.outputBase),
558 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700559 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700560 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700561 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400562
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700563 // Set default platforms to canonicalized values for mixed builds requests.
564 // If these are set in the bazelrc, they will have values that are
565 // non-canonicalized to @sourceroot labels, and thus be invalid when
566 // referenced from the buildroot.
567 //
568 // The actual platform values here may be overridden by configuration
569 // transitions from the buildroot.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700570 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700571 // This should be parameterized on the host OS, but let's restrict to linux
572 // to keep things simple for now.
573 fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"),
574
575 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
576 "--experimental_repository_disable_download",
577
578 // Suppress noise
579 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500580 "--noshow_progress",
581 "--norun_validations",
582 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400583 cmdFlags = append(cmdFlags, extraFlags...)
584
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400585 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200586 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700587 extraEnv := []string{
588 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200589 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700590 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700591 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000592 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700593 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500594 // Disables local host detection of gcc; toolchain information is defined
595 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700596 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
597 }
598 bazelCmd.Env = append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400599
Jason Wu52cd1942022-09-08 15:37:57 +0000600 return bazelCmd
601}
602
603func printableCqueryCommand(bazelCmd *exec.Cmd) string {
604 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(bazelCmd.Args, "\" \"") + "\""
605 return outputString
606
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400607}
608
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400609func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500610 // TODO(cparsons): Define configuration transitions programmatically based
611 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400612 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500613#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400614# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500615#####################################################
616
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400617def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500618 return {
Chris Parsons787fb362021-10-14 18:43:51 -0400619 "//command_line_option:platforms": "@//build/bazel/platforms:%s_%s" % (attr.os, attr.arch),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500620 }
621
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400622_config_node_transition = transition(
623 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500624 inputs = [],
625 outputs = [
626 "//command_line_option:platforms",
627 ],
628)
629
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400630def _passthrough_rule_impl(ctx):
631 return [DefaultInfo(files = depset(ctx.files.deps))]
632
633config_node = rule(
634 implementation = _passthrough_rule_impl,
635 attrs = {
636 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400637 "os" : attr.string(mandatory = True),
638 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400639 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
640 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500641)
642
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400643
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500644# Rule representing the root of the build, to depend on all Bazel targets that
645# are required for the build. Building this target will build the entire Bazel
646# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400647mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400648 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500649 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400650 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500651 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400652)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500653
654def _phony_root_impl(ctx):
655 return []
656
657# Rule to depend on other targets but build nothing.
658# This is useful as follows: building a target of this rule will generate
659# symlink forests for all dependencies of the target, without executing any
660# actions of the build.
661phony_root = rule(
662 implementation = _phony_root_impl,
663 attrs = {"deps" : attr.label_list()},
664)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400665`
666 return []byte(contents)
667}
668
669func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500670 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
671 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400672 formatString := `
673# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400674load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
675
676%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400677
678mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400679 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000680 testonly = True, # Unblocks testonly deps.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400681)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500682
683phony_root(name = "phonyroot",
684 deps = [":buildroot"],
Jingwen Chen3952a902022-12-12 12:20:58 +0000685 testonly = True, # Unblocks testonly deps.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500686)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400687`
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400688 configNodeFormatString := `
689config_node(name = "%s",
690 arch = "%s",
Chris Parsons787fb362021-10-14 18:43:51 -0400691 os = "%s",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400692 deps = [%s],
Jingwen Chen3952a902022-12-12 12:20:58 +0000693 testonly = True, # Unblocks testonly deps.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400694)
695`
696
697 configNodesSection := ""
698
Chris Parsons787fb362021-10-14 18:43:51 -0400699 labelsByConfig := map[string][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400700 for val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200701 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400702 configString := getConfigString(val)
703 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400704 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400705
Jingwen Chen1e347862021-09-02 12:11:49 +0000706 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400707 for configString, labels := range labelsByConfig {
708 configTokens := strings.Split(configString, "|")
709 if len(configTokens) != 2 {
710 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000711 }
Chris Parsons787fb362021-10-14 18:43:51 -0400712 archString := configTokens[0]
713 osString := configTokens[1]
714 targetString := fmt.Sprintf("%s_%s", osString, archString)
715 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
716 labelsString := strings.Join(labels, ",\n ")
717 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400718 }
719
Jingwen Chen1e347862021-09-02 12:11:49 +0000720 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400721}
722
Chris Parsons944e7d02021-03-11 11:08:46 -0500723func indent(original string) string {
724 result := ""
725 for _, line := range strings.Split(original, "\n") {
726 result += " " + line + "\n"
727 }
728 return result
729}
730
Chris Parsons808d84c2021-03-09 20:43:32 -0500731// Returns the file contents of the buildroot.cquery file that should be used for the cquery
732// expression in order to obtain information about buildroot and its dependencies.
733// The contents of this file depend on the bazelContext's requests; requests are enumerated
734// and grouped by their request type. The data retrieved for each label depends on its
735// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400736func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400737 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400738 for val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500739 cqueryId := getCqueryId(val)
740 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
741 requestTypeToCqueryIdEntries[val.requestType] =
742 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
743 }
744 labelRegistrationMapSection := ""
745 functionDefSection := ""
746 mainSwitchSection := ""
747
748 mapDeclarationFormatString := `
749%s = {
750 %s
751}
752`
753 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800754def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500755%s
756`
757 mainSwitchSectionFormatString := `
758 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800759 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500760`
761
Usta Shrestha0b52d832022-02-04 21:37:39 -0500762 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500763 labelMapName := requestType.Name() + "_Labels"
764 functionName := requestType.Name() + "_Fn"
765 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
766 labelMapName,
767 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
768 functionDefSection += fmt.Sprintf(functionDefFormatString,
769 functionName,
770 indent(requestType.StarlarkFunctionBody()))
771 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
772 labelMapName, functionName)
773 }
774
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400775 formatString := `
776# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400777
Usta Shrestha79fccef2022-09-02 18:37:40 -0400778# a drop-in replacement for json.encode(), not available in cquery environment
779# TODO(cparsons): bring json module in and remove this function
780def json_encode(input):
781 # Avoiding recursion by limiting
782 # - a dict to contain anything except a dict
783 # - a list to contain only primitives
784 def encode_primitive(p):
785 t = type(p)
786 if t == "string" or t == "int":
787 return repr(p)
788 fail("unsupported value '%%s' of type '%%s'" %% (p, type(p)))
789
790 def encode_list(list):
791 return "[%%s]" %% ", ".join([encode_primitive(item) for item in list])
792
793 def encode_list_or_primitive(v):
794 return encode_list(v) if type(v) == "list" else encode_primitive(v)
795
796 if type(input) == "dict":
797 # TODO(juu): the result is read line by line so can't use '\n' yet
798 kv_pairs = [("%%s: %%s" %% (encode_primitive(k), encode_list_or_primitive(v))) for (k, v) in input.items()]
799 return "{ %%s }" %% ", ".join(kv_pairs)
800 else:
801 return encode_list_or_primitive(input)
802
Chris Parsons944e7d02021-03-11 11:08:46 -0500803# Label Map Section
804%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500805
Chris Parsons944e7d02021-03-11 11:08:46 -0500806# Function Def Section
807%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500808
809def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400810 # TODO(b/199363072): filegroups and file targets aren't associated with any
811 # specific platform architecture in mixed builds. This is consistent with how
812 # Soong treats filegroups, but it may not be the case with manually-written
813 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500814 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000815 if buildoptions == None:
816 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400817 # any specific platform architecture in mixed builds, so use the host.
818 return "x86_64|linux"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500819 platforms = build_options(target)["//command_line_option:platforms"]
820 if len(platforms) != 1:
821 # An individual configured target should have only one platform architecture.
822 # Note that it's fine for there to be multiple architectures for the same label,
823 # but each is its own configured target.
824 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
825 platform_name = build_options(target)["//command_line_option:platforms"][0].name
826 if platform_name == "host":
827 return "HOST"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400828 elif platform_name.startswith("android_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400829 return platform_name[len("android_"):] + "|" + platform_name[:len("android_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400830 elif platform_name.startswith("linux_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400831 return platform_name[len("linux_"):] + "|" + platform_name[:len("linux_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400832 else:
833 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500834 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500835
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400836def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500837 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500838
Chris Parsons86dc2c22022-09-28 14:58:41 -0400839 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
840 if id_string.startswith("//"):
841 id_string = "@" + id_string
842
Chris Parsons944e7d02021-03-11 11:08:46 -0500843 # Main switch section
844 %s
845 # This target was not requested via cquery, and thus must be a dependency
846 # of a requested target.
847 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400848`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400849
Chris Parsons944e7d02021-03-11 11:08:46 -0500850 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
851 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400852}
853
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200854// Returns a path containing build-related metadata required for interfacing
855// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400856func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200857 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500858}
859
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200860// Returns the path where the contents of the @soong_injection repository live.
861// It is used by Soong to tell Bazel things it cannot over the command line.
862func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200863 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200864}
865
866// Returns the path of the synthetic Bazel workspace that contains a symlink
867// forest composed the whole source tree and BUILD files generated by bp2build.
868func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200869 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200870}
871
Jingwen Chen8c523582021-06-01 11:19:53 +0000872// Returns the path to the top level out dir ($OUT_DIR).
873func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200874 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000875}
876
Sasha Smundak4975c822022-11-16 15:28:18 -0800877const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
878
879var (
880 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
881 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
882 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
883)
884
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400885// Issues commands to Bazel to receive results for all cquery requests
886// queued in the BazelContext.
Sasha Smundak4975c822022-11-16 15:28:18 -0800887func (context *bazelContext) InvokeBazel(config Config, ctx *Context) error {
888 if ctx != nil {
889 ctx.EventHandler.Begin("bazel")
890 defer ctx.EventHandler.End("bazel")
891 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400892
Sasha Smundak4975c822022-11-16 15:28:18 -0800893 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
894 if err := os.MkdirAll(metricsDir, 0777); err != nil {
895 return err
896 }
897 }
898 context.results = make(map[cqueryKey]string)
899 if err := context.runCquery(ctx); err != nil {
900 return err
901 }
902 if err := context.runAquery(config, ctx); err != nil {
903 return err
904 }
905 if err := context.generateBazelSymlinks(ctx); err != nil {
906 return err
907 }
908
909 // Clear requests.
910 context.requests = map[cqueryKey]bool{}
911 return nil
912}
913
914func (context *bazelContext) runCquery(ctx *Context) error {
915 if ctx != nil {
916 ctx.EventHandler.Begin("cquery")
917 defer ctx.EventHandler.End("cquery")
918 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200919 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200920 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
921 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
922 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -0500923 if err != nil {
924 return err
925 }
926 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800927 if err := os.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200928 return err
929 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800930 if err := os.WriteFile(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400931 return err
932 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800933 if err := os.WriteFile(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400934 return err
935 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200936 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Sasha Smundak0e87b182022-12-01 11:46:11 -0800937 if err := os.WriteFile(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400938 return err
939 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000940
Jason Wu52cd1942022-09-08 15:37:57 +0000941 cqueryCommandWithFlag := context.createBazelCommand(context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700942 "--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
Wei Licbd181c2022-11-16 08:59:23 -0800943 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCommandWithFlag)
944 if cqueryErr != nil {
945 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -0500946 }
Jason Wu52cd1942022-09-08 15:37:57 +0000947 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", printableCqueryCommand(cqueryCommandWithFlag))
Sasha Smundak0e87b182022-12-01 11:46:11 -0800948 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400949 return err
950 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400951 cqueryResults := map[string]string{}
952 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
953 if strings.Contains(outputLine, ">>") {
954 splitLine := strings.SplitN(outputLine, ">>", 2)
955 cqueryResults[splitLine[0]] = splitLine[1]
956 }
957 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500958 for val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500959 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -0500960 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400961 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500962 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -0800963 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400964 }
965 }
Sasha Smundak4975c822022-11-16 15:28:18 -0800966 return nil
967}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400968
Sasha Smundak4975c822022-11-16 15:28:18 -0800969func (context *bazelContext) runAquery(config Config, ctx *Context) error {
970 if ctx != nil {
971 ctx.EventHandler.Begin("aquery")
972 defer ctx.EventHandler.End("aquery")
973 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500974 // Issue an aquery command to retrieve action information about the bazel build tree.
975 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700976 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
977 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +0000978 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -0700979 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700980 extraFlags = append(extraFlags, "--collect_code_coverage")
981 paths := make([]string, 0, 2)
982 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -0800983 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -0800984 // TODO(b/259404593) convert path wildcard to regex values
985 if p[i] == "*" {
986 p[i] = ".*"
987 }
988 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700989 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
990 }
991 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
992 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
993 }
994 if len(paths) > 0 {
995 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -0700996 }
997 }
Sasha Smundak4975c822022-11-16 15:28:18 -0800998 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
999 extraFlags...))
1000 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001001 return err
1002 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001003 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
1004 return err
1005}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001006
Sasha Smundak4975c822022-11-16 15:28:18 -08001007func (context *bazelContext) generateBazelSymlinks(ctx *Context) error {
1008 if ctx != nil {
1009 ctx.EventHandler.Begin("symlinks")
1010 defer ctx.EventHandler.End("symlinks")
1011 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001012 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1013 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1014 // but some of symlinks may be required to resolve source dependencies of the build.
Sasha Smundak4975c822022-11-16 15:28:18 -08001015 _, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd))
1016 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001017}
Chris Parsonsa798d962020-10-12 23:44:08 -04001018
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001019func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
1020 return context.buildStatements
1021}
1022
Chris Parsons1a7aca02022-04-25 22:35:15 -04001023func (context *bazelContext) AqueryDepsets() []bazel.AqueryDepset {
1024 return context.depsets
1025}
1026
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001027func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001028 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001029}
1030
Chris Parsonsa798d962020-10-12 23:44:08 -04001031// Singleton used for registering BUILD file ninja dependencies (needed
1032// for correctness of builds which use Bazel.
1033func BazelSingleton() Singleton {
1034 return &bazelSingleton{}
1035}
1036
1037type bazelSingleton struct{}
1038
1039func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001040 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001041 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001042 return
1043 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001044
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001045 // Add ninja file dependencies for files which all bazel invocations require.
1046 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001047 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001048 ctx.AddNinjaFileDeps(bazelBuildList)
1049
Sasha Smundak0e87b182022-12-01 11:46:11 -08001050 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001051 if err != nil {
1052 ctx.Errorf(err.Error())
1053 }
1054 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1055 for _, file := range files {
1056 ctx.AddNinjaFileDeps(file)
1057 }
1058
Chris Parsons1a7aca02022-04-25 22:35:15 -04001059 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1060 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001061 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001062 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1063 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001064 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1065 }
1066 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001067 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1068 if artifactPath == "bazel-out/volatile-status.txt" {
1069 // See https://bazel.build/docs/user-manual#workspace-status
1070 orderOnlies = append(orderOnlies, pathInBazelOut)
1071 } else {
1072 outputs = append(outputs, pathInBazelOut)
1073 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001074 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001075 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001076 ctx.Build(pctx, BuildParams{
1077 Rule: blueprint.Phony,
1078 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1079 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001080 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001081 })
1082 }
1083
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001084 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1085 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001086 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -07001087 if len(buildStatement.Command) > 0 {
1088 rule := NewRuleBuilder(pctx, ctx)
1089 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1090 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1091 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1092 continue
1093 }
1094 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1095 // and thus require special treatment. If BuildStatement were an interface implementing
1096 // buildRule(ctx) function, the code here would just call it.
1097 // Unfortunately, the BuildStatement is defined in
1098 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1099 // because this would cause circular dependency. So, until we move aquery processing
1100 // to the 'android' package, we need to handle special cases here.
1101 if buildStatement.Mnemonic == "FileWrite" || buildStatement.Mnemonic == "SourceSymlinkManifest" {
1102 // Pass file contents as the value of the rule's "content" argument.
1103 // Escape newlines and $ in the contents (the action "writeBazelFile" restores "\\n"
1104 // back to the newline, and Ninja reads $$ as $.
1105 escaped := strings.ReplaceAll(strings.ReplaceAll(buildStatement.FileContents, "\n", "\\n"),
1106 "$", "$$")
1107 ctx.Build(pctx, BuildParams{
1108 Rule: writeBazelFile,
1109 Output: PathForBazelOut(ctx, buildStatement.OutputPaths[0]),
1110 Description: fmt.Sprintf("%s %s", buildStatement.Mnemonic, buildStatement.OutputPaths[0]),
1111 Args: map[string]string{
1112 "content": escaped,
1113 },
1114 })
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001115 } else if buildStatement.Mnemonic == "SymlinkTree" {
1116 // build-runfiles arguments are the manifest file and the target directory
1117 // where it creates the symlink tree according to this manifest (and then
1118 // writes the MANIFEST file to it).
1119 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1120 outManifestPath := outManifest.String()
1121 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1122 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1123 }
1124 outDir := filepath.Dir(outManifestPath)
1125 ctx.Build(pctx, BuildParams{
1126 Rule: buildRunfilesRule,
1127 Output: outManifest,
1128 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1129 Description: "symlink tree for " + outDir,
1130 Args: map[string]string{
1131 "outDir": outDir,
1132 },
1133 })
Sasha Smundak1da064c2022-06-08 16:36:16 -07001134 } else {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001135 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001136 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001137 }
1138}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001139
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001140// Register bazel-owned build statements (obtained from the aquery invocation).
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001141func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx BuilderContext) {
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001142 // executionRoot is the action cwd.
1143 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1144
1145 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1146 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001147 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001148 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001149 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001150 }
1151 cmd.Text("&&")
1152 }
1153
1154 for _, pair := range buildStatement.Env {
1155 // Set per-action env variables, if any.
1156 cmd.Flag(pair.Key + "=" + pair.Value)
1157 }
1158
1159 // The actual Bazel action.
Colin Crossd5c7ddb2022-12-06 16:27:17 -08001160 if len(buildStatement.Command) > 16*1024 {
1161 commandFile := PathForBazelOut(ctx, buildStatement.OutputPaths[0]+".sh")
1162 WriteFileRule(ctx, commandFile, buildStatement.Command)
1163
1164 cmd.Text("bash").Text(buildStatement.OutputPaths[0] + ".sh").Implicit(commandFile)
1165 } else {
1166 cmd.Text(buildStatement.Command)
1167 }
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001168
1169 for _, outputPath := range buildStatement.OutputPaths {
1170 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1171 }
1172 for _, inputPath := range buildStatement.InputPaths {
1173 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1174 }
1175 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1176 otherDepsetName := bazelDepsetName(inputDepsetHash)
1177 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1178 }
1179
1180 if depfile := buildStatement.Depfile; depfile != nil {
1181 // The paths in depfile are relative to `executionRoot`.
1182 // Hence, they need to be corrected by replacing "bazel-out"
1183 // with the full `bazelOutDir`.
1184 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1185 // would be deemed missing.
1186 // (Note: The regexp uses a capture group because the version of sed
1187 // does not support a look-behind pattern.)
1188 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1189 bazelOutDir, *depfile)
1190 cmd.Text(replacement)
1191 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1192 }
1193
1194 for _, symlinkPath := range buildStatement.SymlinkPaths {
1195 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1196 }
1197}
1198
Chris Parsons8d6e4332021-02-22 16:13:50 -05001199func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001200 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001201}
1202
Chris Parsons787fb362021-10-14 18:43:51 -04001203func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001204 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001205 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001206 if key.configKey.osType.Class == Device {
1207 // For the generic Android, the expected result is "target|android", which
1208 // corresponds to the product_variable_config named "android_target" in
1209 // build/bazel/platforms/BUILD.bazel.
1210 arch = "target"
1211 } else {
1212 // Use host platform, which is currently hardcoded to be x86_64.
1213 arch = "x86_64"
1214 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001215 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001216 osName := key.configKey.osType.Name
Colin Cross046fcea2022-12-20 15:32:18 -08001217 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" || osName == "linux_musl" {
Chris Parsons787fb362021-10-14 18:43:51 -04001218 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001219 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001220 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001221 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -04001222}
1223
Chris Parsonsf874e462022-05-10 13:50:12 -04001224func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001225 return configKey{
1226 // use string because Arch is not a valid key in go
1227 arch: ctx.Arch().String(),
1228 osType: ctx.Os(),
1229 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001230}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001231
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001232func bazelDepsetName(contentHash string) string {
1233 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001234}