blob: 122495f781b75753c6097e5dc3a13983ff350c0e [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"
19 "errors"
20 "fmt"
21 "os"
22 "os/exec"
Usta Shresthaacd5a0c2022-06-22 11:20:50 -040023 "path"
Chris Parsonsa798d962020-10-12 23:44:08 -040024 "path/filepath"
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040025 "runtime"
26 "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
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400378func NewBazelContext(c *config) (BazelContext, error) {
Chris Parsonsef615e52022-08-18 22:04:11 -0400379 var modulesDefaultToBazel bool
380 disabledModules := map[string]bool{}
381 enabledModules := map[string]bool{}
382
383 switch c.BuildMode {
384 case BazelProdMode:
385 modulesDefaultToBazel = false
386
387 for _, enabledProdModule := range allowlists.ProdMixedBuildsEnabledList {
388 enabledModules[enabledProdModule] = true
389 }
MarkDacekd06db5d2022-11-29 00:47:59 +0000390
391 for enabledAdHocModule := range c.BazelModulesForceEnabledByFlag() {
392 enabledModules[enabledAdHocModule] = true
393 }
MarkDacekb78465d2022-10-18 20:10:16 +0000394 case BazelStagingMode:
395 modulesDefaultToBazel = false
Chris Parsons66fc7452022-11-04 13:26:17 -0400396 // Staging mode includes all prod modules plus all staging modules.
397 for _, enabledProdModule := range allowlists.ProdMixedBuildsEnabledList {
398 enabledModules[enabledProdModule] = true
399 }
MarkDacekb78465d2022-10-18 20:10:16 +0000400 for _, enabledStagingMode := range allowlists.StagingMixedBuildsEnabledList {
401 enabledModules[enabledStagingMode] = true
MarkDacekb78465d2022-10-18 20:10:16 +0000402 }
MarkDacekd06db5d2022-11-29 00:47:59 +0000403
404 for enabledAdHocModule := range c.BazelModulesForceEnabledByFlag() {
405 enabledModules[enabledAdHocModule] = true
406 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400407 case BazelDevMode:
408 modulesDefaultToBazel = true
409
410 // Don't use partially-converted cc_library targets in mixed builds,
411 // since mixed builds would generally rely on both static and shared
412 // variants of a cc_library.
Sasha Smundak0e87b182022-12-01 11:46:11 -0800413 for staticOnlyModule := range GetBp2BuildAllowList().ccLibraryStaticOnly {
Chris Parsonsef615e52022-08-18 22:04:11 -0400414 disabledModules[staticOnlyModule] = true
415 }
416 for _, disabledDevModule := range allowlists.MixedBuildsDisabledList {
417 disabledModules[disabledDevModule] = true
418 }
419 default:
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400420 return noopBazelContext{}, nil
421 }
422
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400423 p, err := bazelPathsFromConfig(c)
424 if err != nil {
425 return nil, err
426 }
Chris Parsonsad876012022-08-20 14:48:32 -0400427
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400428 return &bazelContext{
Chris Parsonsad876012022-08-20 14:48:32 -0400429 bazelRunner: &builtinBazelRunner{},
430 paths: p,
431 requests: make(map[cqueryKey]bool),
Chris Parsonsef615e52022-08-18 22:04:11 -0400432 modulesDefaultToBazel: modulesDefaultToBazel,
433 bazelEnabledModules: enabledModules,
Chris Parsonsad876012022-08-20 14:48:32 -0400434 bazelDisabledModules: disabledModules,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400435 }, nil
436}
437
438func bazelPathsFromConfig(c *config) (*bazelPaths, error) {
439 p := bazelPaths{
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200440 soongOutDir: c.soongOutDir,
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400441 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700442 var missingEnvVars []string
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400443 if len(c.Getenv("BAZEL_HOME")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400444 p.homeDir = c.Getenv("BAZEL_HOME")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400445 } else {
446 missingEnvVars = append(missingEnvVars, "BAZEL_HOME")
447 }
448 if len(c.Getenv("BAZEL_PATH")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400449 p.bazelPath = c.Getenv("BAZEL_PATH")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400450 } else {
451 missingEnvVars = append(missingEnvVars, "BAZEL_PATH")
452 }
453 if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400454 p.outputBase = c.Getenv("BAZEL_OUTPUT_BASE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400455 } else {
456 missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE")
457 }
458 if len(c.Getenv("BAZEL_WORKSPACE")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400459 p.workspaceDir = c.Getenv("BAZEL_WORKSPACE")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400460 } else {
461 missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE")
462 }
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000463 if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400464 p.metricsDir = c.Getenv("BAZEL_METRICS_DIR")
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000465 } else {
466 missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR")
467 }
MarkDacek0d5bca52022-10-10 20:07:48 +0000468 if len(c.Getenv("BAZEL_DEPS_FILE")) > 1 {
469 p.bazelDepsFile = c.Getenv("BAZEL_DEPS_FILE")
470 } else {
471 missingEnvVars = append(missingEnvVars, "BAZEL_DEPS_FILE")
472 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400473 if len(missingEnvVars) > 0 {
474 return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars))
475 } else {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400476 return &p, nil
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400477 }
478}
479
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400480func (p *bazelPaths) BazelMetricsDir() string {
481 return p.metricsDir
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000482}
483
Chris Parsonsad876012022-08-20 14:48:32 -0400484func (context *bazelContext) BazelAllowlisted(moduleName string) bool {
485 if context.bazelDisabledModules[moduleName] {
486 return false
487 }
488 if context.bazelEnabledModules[moduleName] {
489 return true
490 }
491 return context.modulesDefaultToBazel
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400492}
493
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400494func pwdPrefix() string {
495 // Darwin doesn't have /proc
496 if runtime.GOOS != "darwin" {
497 return "PWD=/proc/self/cwd"
498 }
499 return ""
500}
501
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400502type bazelCommand struct {
503 command string
504 // query or label
505 expression string
506}
507
508type mockBazelRunner struct {
509 bazelCommandResults map[bazelCommand]string
Jason Wu52cd1942022-09-08 15:37:57 +0000510 // use *exec.Cmd as a key to get the bazelCommand, the map will be used in issueBazelCommand()
511 // Register createBazelCommand() invocations. Later, an
512 // issueBazelCommand() invocation can be mapped to the *exec.Cmd instance
513 // and then to the expected result via bazelCommandResults
514 tokens map[*exec.Cmd]bazelCommand
515 commands []bazelCommand
516 extraFlags []string
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400517}
518
Sasha Smundak0e87b182022-12-01 11:46:11 -0800519func (r *mockBazelRunner) createBazelCommand(_ *bazelPaths, _ bazel.RunName,
Jason Wu52cd1942022-09-08 15:37:57 +0000520 command bazelCommand, extraFlags ...string) *exec.Cmd {
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400521 r.commands = append(r.commands, command)
Yu Liu8d82ac52022-05-17 15:13:28 -0700522 r.extraFlags = append(r.extraFlags, strings.Join(extraFlags, " "))
Jason Wu52cd1942022-09-08 15:37:57 +0000523 cmd := &exec.Cmd{}
524 if r.tokens == nil {
525 r.tokens = make(map[*exec.Cmd]bazelCommand)
526 }
527 r.tokens[cmd] = command
528 return cmd
529}
530
531func (r *mockBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
532 if command, ok := r.tokens[bazelCmd]; ok {
533 return r.bazelCommandResults[command], "", nil
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400534 }
535 return "", "", nil
536}
537
538type builtinBazelRunner struct{}
539
Chris Parsons808d84c2021-03-09 20:43:32 -0500540// Issues the given bazel command with given build label and additional flags.
541// Returns (stdout, stderr, error). The first and second return values are strings
542// containing the stdout and stderr of the run command, and an error is returned if
543// the invocation returned an error code.
Jason Wu52cd1942022-09-08 15:37:57 +0000544func (r *builtinBazelRunner) issueBazelCommand(bazelCmd *exec.Cmd) (string, string, error) {
545 stderr := &bytes.Buffer{}
546 bazelCmd.Stderr = stderr
547 if output, err := bazelCmd.Output(); err != nil {
548 return "", string(stderr.Bytes()),
Sasha Smundak0e87b182022-12-01 11:46:11 -0800549 fmt.Errorf("bazel command failed: %s\n---command---\n%s\n---env---\n%s\n---stderr---\n%s---",
550 err, bazelCmd, strings.Join(bazelCmd.Env, "\n"), stderr)
Jason Wu52cd1942022-09-08 15:37:57 +0000551 } else {
552 return string(output), string(stderr.Bytes()), nil
553 }
554}
555
556func (r *builtinBazelRunner) createBazelCommand(paths *bazelPaths, runName bazel.RunName, command bazelCommand,
557 extraFlags ...string) *exec.Cmd {
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000558 cmdFlags := []string{
Romain Jobredeaux41fd5e42021-08-27 15:59:39 +0000559 "--output_base=" + absolutePath(paths.outputBase),
560 command.command,
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700561 command.expression,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700562 // TODO(asmundak): is it needed in every build?
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700563 "--profile=" + shared.BazelMetricsFilename(paths, runName),
Jingwen Chen91220d72021-03-24 02:18:33 -0400564
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700565 // Set default platforms to canonicalized values for mixed builds requests.
566 // If these are set in the bazelrc, they will have values that are
567 // non-canonicalized to @sourceroot labels, and thus be invalid when
568 // referenced from the buildroot.
569 //
570 // The actual platform values here may be overridden by configuration
571 // transitions from the buildroot.
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700572 fmt.Sprintf("--extra_toolchains=%s", "//prebuilts/clang/host/linux-x86:all"),
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700573 // This should be parameterized on the host OS, but let's restrict to linux
574 // to keep things simple for now.
575 fmt.Sprintf("--host_platform=%s", "//build/bazel/platforms:linux_x86_64"),
576
577 // Explicitly disable downloading rules (such as canonical C++ and Java rules) from the network.
578 "--experimental_repository_disable_download",
579
580 // Suppress noise
581 "--ui_event_filters=-INFO",
Sam Delmerico658a4da2022-11-07 15:53:38 -0500582 "--noshow_progress",
583 "--norun_validations",
584 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400585 cmdFlags = append(cmdFlags, extraFlags...)
586
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400587 bazelCmd := exec.Command(paths.bazelPath, cmdFlags...)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200588 bazelCmd.Dir = absolutePath(paths.syntheticWorkspaceDir())
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700589 extraEnv := []string{
590 "HOME=" + paths.homeDir,
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200591 pwdPrefix(),
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700592 "BUILD_DIR=" + absolutePath(paths.soongOutDir),
Joe Onoratoba29f382022-10-24 06:38:11 -0700593 // Make OUT_DIR absolute here so build/bazel/bin/bazel uses the correct
Jingwen Chen8c523582021-06-01 11:19:53 +0000594 // OUT_DIR at <root>/out, instead of <root>/out/soong/workspace/out.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700595 "OUT_DIR=" + absolutePath(paths.outDir()),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500596 // Disables local host detection of gcc; toolchain information is defined
597 // explicitly in BUILD files.
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700598 "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1",
599 }
600 bazelCmd.Env = append(os.Environ(), extraEnv...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400601
Jason Wu52cd1942022-09-08 15:37:57 +0000602 return bazelCmd
603}
604
605func printableCqueryCommand(bazelCmd *exec.Cmd) string {
606 outputString := strings.Join(bazelCmd.Env, " ") + " \"" + strings.Join(bazelCmd.Args, "\" \"") + "\""
607 return outputString
608
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400609}
610
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400611func (context *bazelContext) mainBzlFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500612 // TODO(cparsons): Define configuration transitions programmatically based
613 // on available archs.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400614 contents := `
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500615#####################################################
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400616# This file is generated by soong_build. Do not edit.
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500617#####################################################
618
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400619def _config_node_transition_impl(settings, attr):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500620 return {
Chris Parsons787fb362021-10-14 18:43:51 -0400621 "//command_line_option:platforms": "@//build/bazel/platforms:%s_%s" % (attr.os, attr.arch),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500622 }
623
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400624_config_node_transition = transition(
625 implementation = _config_node_transition_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500626 inputs = [],
627 outputs = [
628 "//command_line_option:platforms",
629 ],
630)
631
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400632def _passthrough_rule_impl(ctx):
633 return [DefaultInfo(files = depset(ctx.files.deps))]
634
635config_node = rule(
636 implementation = _passthrough_rule_impl,
637 attrs = {
638 "arch" : attr.string(mandatory = True),
Chris Parsons787fb362021-10-14 18:43:51 -0400639 "os" : attr.string(mandatory = True),
640 "deps" : attr.label_list(cfg = _config_node_transition, allow_files = True),
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400641 "_allowlist_function_transition": attr.label(default = "@bazel_tools//tools/allowlists/function_transition_allowlist"),
642 },
Chris Parsons8d6e4332021-02-22 16:13:50 -0500643)
644
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400645
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500646# Rule representing the root of the build, to depend on all Bazel targets that
647# are required for the build. Building this target will build the entire Bazel
648# build tree.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400649mixed_build_root = rule(
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400650 implementation = _passthrough_rule_impl,
Chris Parsons8d6e4332021-02-22 16:13:50 -0500651 attrs = {
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400652 "deps" : attr.label_list(),
Chris Parsons8d6e4332021-02-22 16:13:50 -0500653 },
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400654)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500655
656def _phony_root_impl(ctx):
657 return []
658
659# Rule to depend on other targets but build nothing.
660# This is useful as follows: building a target of this rule will generate
661# symlink forests for all dependencies of the target, without executing any
662# actions of the build.
663phony_root = rule(
664 implementation = _phony_root_impl,
665 attrs = {"deps" : attr.label_list()},
666)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400667`
668 return []byte(contents)
669}
670
671func (context *bazelContext) mainBuildFileContents() []byte {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500672 // TODO(cparsons): Map label to attribute programmatically; don't use hard-coded
673 // architecture mapping.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400674 formatString := `
675# This file is generated by soong_build. Do not edit.
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400676load(":main.bzl", "config_node", "mixed_build_root", "phony_root")
677
678%s
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400679
680mixed_build_root(name = "buildroot",
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400681 deps = [%s],
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400682)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500683
684phony_root(name = "phonyroot",
685 deps = [":buildroot"],
686)
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],
693)
694`
695
696 configNodesSection := ""
697
Chris Parsons787fb362021-10-14 18:43:51 -0400698 labelsByConfig := map[string][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400699 for val := range context.requests {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200700 labelString := fmt.Sprintf("\"@%s\"", val.label)
Chris Parsons787fb362021-10-14 18:43:51 -0400701 configString := getConfigString(val)
702 labelsByConfig[configString] = append(labelsByConfig[configString], labelString)
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400703 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400704
Jingwen Chen1e347862021-09-02 12:11:49 +0000705 allLabels := []string{}
Chris Parsons787fb362021-10-14 18:43:51 -0400706 for configString, labels := range labelsByConfig {
707 configTokens := strings.Split(configString, "|")
708 if len(configTokens) != 2 {
709 panic(fmt.Errorf("Unexpected config string format: %s", configString))
Jingwen Chen1e347862021-09-02 12:11:49 +0000710 }
Chris Parsons787fb362021-10-14 18:43:51 -0400711 archString := configTokens[0]
712 osString := configTokens[1]
713 targetString := fmt.Sprintf("%s_%s", osString, archString)
714 allLabels = append(allLabels, fmt.Sprintf("\":%s\"", targetString))
715 labelsString := strings.Join(labels, ",\n ")
716 configNodesSection += fmt.Sprintf(configNodeFormatString, targetString, archString, osString, labelsString)
Chris Parsonsad0b5ba2021-03-29 21:09:24 -0400717 }
718
Jingwen Chen1e347862021-09-02 12:11:49 +0000719 return []byte(fmt.Sprintf(formatString, configNodesSection, strings.Join(allLabels, ",\n ")))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400720}
721
Chris Parsons944e7d02021-03-11 11:08:46 -0500722func indent(original string) string {
723 result := ""
724 for _, line := range strings.Split(original, "\n") {
725 result += " " + line + "\n"
726 }
727 return result
728}
729
Chris Parsons808d84c2021-03-09 20:43:32 -0500730// Returns the file contents of the buildroot.cquery file that should be used for the cquery
731// expression in order to obtain information about buildroot and its dependencies.
732// The contents of this file depend on the bazelContext's requests; requests are enumerated
733// and grouped by their request type. The data retrieved for each label depends on its
734// request type.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400735func (context *bazelContext) cqueryStarlarkFileContents() []byte {
Liz Kammerf29df7c2021-04-02 13:37:39 -0400736 requestTypeToCqueryIdEntries := map[cqueryRequest][]string{}
Usta Shrestha2bc1cd92022-06-23 13:45:24 -0400737 for val := range context.requests {
Chris Parsons944e7d02021-03-11 11:08:46 -0500738 cqueryId := getCqueryId(val)
739 mapEntryString := fmt.Sprintf("%q : True", cqueryId)
740 requestTypeToCqueryIdEntries[val.requestType] =
741 append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
742 }
743 labelRegistrationMapSection := ""
744 functionDefSection := ""
745 mainSwitchSection := ""
746
747 mapDeclarationFormatString := `
748%s = {
749 %s
750}
751`
752 functionDefFormatString := `
Cole Faust97d15272022-11-22 14:08:59 -0800753def %s(target, id_string):
Chris Parsons944e7d02021-03-11 11:08:46 -0500754%s
755`
756 mainSwitchSectionFormatString := `
757 if id_string in %s:
Cole Faust97d15272022-11-22 14:08:59 -0800758 return id_string + ">>" + %s(target, id_string)
Chris Parsons944e7d02021-03-11 11:08:46 -0500759`
760
Usta Shrestha0b52d832022-02-04 21:37:39 -0500761 for requestType := range requestTypeToCqueryIdEntries {
Chris Parsons944e7d02021-03-11 11:08:46 -0500762 labelMapName := requestType.Name() + "_Labels"
763 functionName := requestType.Name() + "_Fn"
764 labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
765 labelMapName,
766 strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n "))
767 functionDefSection += fmt.Sprintf(functionDefFormatString,
768 functionName,
769 indent(requestType.StarlarkFunctionBody()))
770 mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
771 labelMapName, functionName)
772 }
773
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400774 formatString := `
775# This file is generated by soong_build. Do not edit.
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400776
Usta Shrestha79fccef2022-09-02 18:37:40 -0400777# a drop-in replacement for json.encode(), not available in cquery environment
778# TODO(cparsons): bring json module in and remove this function
779def json_encode(input):
780 # Avoiding recursion by limiting
781 # - a dict to contain anything except a dict
782 # - a list to contain only primitives
783 def encode_primitive(p):
784 t = type(p)
785 if t == "string" or t == "int":
786 return repr(p)
787 fail("unsupported value '%%s' of type '%%s'" %% (p, type(p)))
788
789 def encode_list(list):
790 return "[%%s]" %% ", ".join([encode_primitive(item) for item in list])
791
792 def encode_list_or_primitive(v):
793 return encode_list(v) if type(v) == "list" else encode_primitive(v)
794
795 if type(input) == "dict":
796 # TODO(juu): the result is read line by line so can't use '\n' yet
797 kv_pairs = [("%%s: %%s" %% (encode_primitive(k), encode_list_or_primitive(v))) for (k, v) in input.items()]
798 return "{ %%s }" %% ", ".join(kv_pairs)
799 else:
800 return encode_list_or_primitive(input)
801
Chris Parsons944e7d02021-03-11 11:08:46 -0500802# Label Map Section
803%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500804
Chris Parsons944e7d02021-03-11 11:08:46 -0500805# Function Def Section
806%s
Chris Parsons8d6e4332021-02-22 16:13:50 -0500807
808def get_arch(target):
Chris Parsons787fb362021-10-14 18:43:51 -0400809 # TODO(b/199363072): filegroups and file targets aren't associated with any
810 # specific platform architecture in mixed builds. This is consistent with how
811 # Soong treats filegroups, but it may not be the case with manually-written
812 # filegroup BUILD targets.
Chris Parsons8d6e4332021-02-22 16:13:50 -0500813 buildoptions = build_options(target)
Jingwen Chen8f222742021-10-07 12:02:23 +0000814 if buildoptions == None:
815 # File targets do not have buildoptions. File targets aren't associated with
Chris Parsons787fb362021-10-14 18:43:51 -0400816 # any specific platform architecture in mixed builds, so use the host.
817 return "x86_64|linux"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500818 platforms = build_options(target)["//command_line_option:platforms"]
819 if len(platforms) != 1:
820 # An individual configured target should have only one platform architecture.
821 # Note that it's fine for there to be multiple architectures for the same label,
822 # but each is its own configured target.
823 fail("expected exactly 1 platform for " + str(target.label) + " but got " + str(platforms))
824 platform_name = build_options(target)["//command_line_option:platforms"][0].name
825 if platform_name == "host":
826 return "HOST"
Chris Parsons94a0bba2021-06-04 15:03:47 -0400827 elif platform_name.startswith("android_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400828 return platform_name[len("android_"):] + "|" + platform_name[:len("android_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400829 elif platform_name.startswith("linux_"):
Chris Parsons787fb362021-10-14 18:43:51 -0400830 return platform_name[len("linux_"):] + "|" + platform_name[:len("linux_")-1]
Chris Parsons94a0bba2021-06-04 15:03:47 -0400831 else:
832 fail("expected platform name of the form 'android_<arch>' or 'linux_<arch>', but was " + str(platforms))
Chris Parsons8d6e4332021-02-22 16:13:50 -0500833 return "UNKNOWN"
Chris Parsons8d6e4332021-02-22 16:13:50 -0500834
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400835def format(target):
Chris Parsons8d6e4332021-02-22 16:13:50 -0500836 id_string = str(target.label) + "|" + get_arch(target)
Chris Parsons944e7d02021-03-11 11:08:46 -0500837
Chris Parsons86dc2c22022-09-28 14:58:41 -0400838 # TODO(b/248106697): Remove once Bazel is updated to always normalize labels.
839 if id_string.startswith("//"):
840 id_string = "@" + id_string
841
Chris Parsons944e7d02021-03-11 11:08:46 -0500842 # Main switch section
843 %s
844 # This target was not requested via cquery, and thus must be a dependency
845 # of a requested target.
846 return id_string + ">>NONE"
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400847`
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400848
Chris Parsons944e7d02021-03-11 11:08:46 -0500849 return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
850 mainSwitchSection))
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400851}
852
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200853// Returns a path containing build-related metadata required for interfacing
854// with Bazel. Example: out/soong/bazel.
Liz Kammer8d62a4f2021-04-08 09:47:28 -0400855func (p *bazelPaths) intermediatesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200856 return filepath.Join(p.soongOutDir, "bazel")
Chris Parsons8ccdb632020-11-17 15:41:01 -0500857}
858
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200859// Returns the path where the contents of the @soong_injection repository live.
860// It is used by Soong to tell Bazel things it cannot over the command line.
861func (p *bazelPaths) injectedFilesDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200862 return filepath.Join(p.soongOutDir, bazel.SoongInjectionDirName)
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200863}
864
865// Returns the path of the synthetic Bazel workspace that contains a symlink
866// forest composed the whole source tree and BUILD files generated by bp2build.
867func (p *bazelPaths) syntheticWorkspaceDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200868 return filepath.Join(p.soongOutDir, "workspace")
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200869}
870
Jingwen Chen8c523582021-06-01 11:19:53 +0000871// Returns the path to the top level out dir ($OUT_DIR).
872func (p *bazelPaths) outDir() string {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200873 return filepath.Dir(p.soongOutDir)
Jingwen Chen8c523582021-06-01 11:19:53 +0000874}
875
Sasha Smundak4975c822022-11-16 15:28:18 -0800876const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
877
878var (
879 cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
880 aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
881 buildCmd = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
882)
883
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400884// Issues commands to Bazel to receive results for all cquery requests
885// queued in the BazelContext.
Sasha Smundak4975c822022-11-16 15:28:18 -0800886func (context *bazelContext) InvokeBazel(config Config, ctx *Context) error {
887 if ctx != nil {
888 ctx.EventHandler.Begin("bazel")
889 defer ctx.EventHandler.End("bazel")
890 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400891
Sasha Smundak4975c822022-11-16 15:28:18 -0800892 if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
893 if err := os.MkdirAll(metricsDir, 0777); err != nil {
894 return err
895 }
896 }
897 context.results = make(map[cqueryKey]string)
898 if err := context.runCquery(ctx); err != nil {
899 return err
900 }
901 if err := context.runAquery(config, ctx); err != nil {
902 return err
903 }
904 if err := context.generateBazelSymlinks(ctx); err != nil {
905 return err
906 }
907
908 // Clear requests.
909 context.requests = map[cqueryKey]bool{}
910 return nil
911}
912
913func (context *bazelContext) runCquery(ctx *Context) error {
914 if ctx != nil {
915 ctx.EventHandler.Begin("cquery")
916 defer ctx.EventHandler.End("cquery")
917 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200918 soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
Lukacs T. Berki3069dd92021-05-11 16:54:29 +0200919 mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
920 if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
921 err = os.MkdirAll(mixedBuildsPath, 0777)
Usta Shrestha902fd172022-03-02 15:27:49 -0500922 if err != nil {
923 return err
924 }
925 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800926 if err := os.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200927 return err
928 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800929 if err := os.WriteFile(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400930 return err
931 }
Sasha Smundak0e87b182022-12-01 11:46:11 -0800932 if err := os.WriteFile(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400933 return err
934 }
Lukacs T. Berkid6cd8132021-04-20 13:01:07 +0200935 cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
Sasha Smundak0e87b182022-12-01 11:46:11 -0800936 if err := os.WriteFile(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400937 return err
938 }
Jingwen Chen1e347862021-09-02 12:11:49 +0000939
Jason Wu52cd1942022-09-08 15:37:57 +0000940 cqueryCommandWithFlag := context.createBazelCommand(context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700941 "--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
Wei Licbd181c2022-11-16 08:59:23 -0800942 cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCommandWithFlag)
943 if cqueryErr != nil {
944 return cqueryErr
Chris Parsons8d6e4332021-02-22 16:13:50 -0500945 }
Jason Wu52cd1942022-09-08 15:37:57 +0000946 cqueryCommandPrint := fmt.Sprintf("cquery command line:\n %s \n\n\n", printableCqueryCommand(cqueryCommandWithFlag))
Sasha Smundak0e87b182022-12-01 11:46:11 -0800947 if err := os.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400948 return err
949 }
Chris Parsonsb0f8ac42020-10-23 16:48:08 -0400950 cqueryResults := map[string]string{}
951 for _, outputLine := range strings.Split(cqueryOutput, "\n") {
952 if strings.Contains(outputLine, ">>") {
953 splitLine := strings.SplitN(outputLine, ">>", 2)
954 cqueryResults[splitLine[0]] = splitLine[1]
955 }
956 }
Usta Shrestha902fd172022-03-02 15:27:49 -0500957 for val := range context.requests {
Chris Parsons8d6e4332021-02-22 16:13:50 -0500958 if cqueryResult, ok := cqueryResults[getCqueryId(val)]; ok {
Usta Shrestha902fd172022-03-02 15:27:49 -0500959 context.results[val] = cqueryResult
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400960 } else {
Chris Parsons808d84c2021-03-09 20:43:32 -0500961 return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
Wei Licbd181c2022-11-16 08:59:23 -0800962 getCqueryId(val), cqueryOutput, cqueryErrorMessage)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400963 }
964 }
Sasha Smundak4975c822022-11-16 15:28:18 -0800965 return nil
966}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400967
Sasha Smundak4975c822022-11-16 15:28:18 -0800968func (context *bazelContext) runAquery(config Config, ctx *Context) error {
969 if ctx != nil {
970 ctx.EventHandler.Begin("aquery")
971 defer ctx.EventHandler.End("aquery")
972 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500973 // Issue an aquery command to retrieve action information about the bazel build tree.
974 //
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700975 // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
976 // proto sources, which would add a number of unnecessary dependencies.
Jason Wu118fd2b2022-10-27 18:41:15 +0000977 extraFlags := []string{"--output=proto", "--include_file_write_contents"}
Yu Liu8d82ac52022-05-17 15:13:28 -0700978 if Bool(config.productVariables.ClangCoverage) {
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700979 extraFlags = append(extraFlags, "--collect_code_coverage")
980 paths := make([]string, 0, 2)
981 if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
Sasha Smundak0e87b182022-12-01 11:46:11 -0800982 for i := range p {
Wei Licbd181c2022-11-16 08:59:23 -0800983 // TODO(b/259404593) convert path wildcard to regex values
984 if p[i] == "*" {
985 p[i] = ".*"
986 }
987 }
Sasha Smundakb43ae1e2022-07-03 15:57:36 -0700988 paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
989 }
990 if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
991 paths = append(paths, JoinWithPrefixAndSeparator(p, "-", ","))
992 }
993 if len(paths) > 0 {
994 extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
Yu Liu8d82ac52022-05-17 15:13:28 -0700995 }
996 }
Sasha Smundak4975c822022-11-16 15:28:18 -0800997 aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
998 extraFlags...))
999 if err != nil {
Chris Parsons4f069892021-01-15 12:22:41 -05001000 return err
1001 }
Sasha Smundak4975c822022-11-16 15:28:18 -08001002 context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
1003 return err
1004}
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001005
Sasha Smundak4975c822022-11-16 15:28:18 -08001006func (context *bazelContext) generateBazelSymlinks(ctx *Context) error {
1007 if ctx != nil {
1008 ctx.EventHandler.Begin("symlinks")
1009 defer ctx.EventHandler.End("symlinks")
1010 }
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001011 // Issue a build command of the phony root to generate symlink forests for dependencies of the
1012 // Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
1013 // but some of symlinks may be required to resolve source dependencies of the build.
Sasha Smundak4975c822022-11-16 15:28:18 -08001014 _, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd))
1015 return err
Chris Parsonsf3c96ef2020-09-29 02:23:17 -04001016}
Chris Parsonsa798d962020-10-12 23:44:08 -04001017
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001018func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
1019 return context.buildStatements
1020}
1021
Chris Parsons1a7aca02022-04-25 22:35:15 -04001022func (context *bazelContext) AqueryDepsets() []bazel.AqueryDepset {
1023 return context.depsets
1024}
1025
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001026func (context *bazelContext) OutputBase() string {
Liz Kammer8d62a4f2021-04-08 09:47:28 -04001027 return context.paths.outputBase
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001028}
1029
Chris Parsonsa798d962020-10-12 23:44:08 -04001030// Singleton used for registering BUILD file ninja dependencies (needed
1031// for correctness of builds which use Bazel.
1032func BazelSingleton() Singleton {
1033 return &bazelSingleton{}
1034}
1035
1036type bazelSingleton struct{}
1037
1038func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001039 // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled.
Chris Parsonsad876012022-08-20 14:48:32 -04001040 if !ctx.Config().IsMixedBuildsEnabled() {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001041 return
1042 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001043
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001044 // Add ninja file dependencies for files which all bazel invocations require.
1045 bazelBuildList := absolutePath(filepath.Join(
Lukacs T. Berkif9008072021-08-16 15:24:48 +02001046 filepath.Dir(ctx.Config().moduleListFile), "bazel.list"))
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001047 ctx.AddNinjaFileDeps(bazelBuildList)
1048
Sasha Smundak0e87b182022-12-01 11:46:11 -08001049 data, err := os.ReadFile(bazelBuildList)
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001050 if err != nil {
1051 ctx.Errorf(err.Error())
1052 }
1053 files := strings.Split(strings.TrimSpace(string(data)), "\n")
1054 for _, file := range files {
1055 ctx.AddNinjaFileDeps(file)
1056 }
1057
Chris Parsons1a7aca02022-04-25 22:35:15 -04001058 for _, depset := range ctx.Config().BazelContext.AqueryDepsets() {
1059 var outputs []Path
ustafdb3e342022-11-22 17:11:30 -05001060 var orderOnlies []Path
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001061 for _, depsetDepHash := range depset.TransitiveDepSetHashes {
1062 otherDepsetName := bazelDepsetName(depsetDepHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001063 outputs = append(outputs, PathForPhony(ctx, otherDepsetName))
1064 }
1065 for _, artifactPath := range depset.DirectArtifacts {
ustafdb3e342022-11-22 17:11:30 -05001066 pathInBazelOut := PathForBazelOut(ctx, artifactPath)
1067 if artifactPath == "bazel-out/volatile-status.txt" {
1068 // See https://bazel.build/docs/user-manual#workspace-status
1069 orderOnlies = append(orderOnlies, pathInBazelOut)
1070 } else {
1071 outputs = append(outputs, pathInBazelOut)
1072 }
Chris Parsons1a7aca02022-04-25 22:35:15 -04001073 }
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001074 thisDepsetName := bazelDepsetName(depset.ContentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001075 ctx.Build(pctx, BuildParams{
1076 Rule: blueprint.Phony,
1077 Outputs: []WritablePath{PathForPhony(ctx, thisDepsetName)},
1078 Implicits: outputs,
ustafdb3e342022-11-22 17:11:30 -05001079 OrderOnly: orderOnlies,
Chris Parsons1a7aca02022-04-25 22:35:15 -04001080 })
1081 }
1082
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001083 executionRoot := path.Join(ctx.Config().BazelContext.OutputBase(), "execroot", "__main__")
1084 bazelOutDir := path.Join(executionRoot, "bazel-out")
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001085 for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
Sasha Smundak1da064c2022-06-08 16:36:16 -07001086 if len(buildStatement.Command) > 0 {
1087 rule := NewRuleBuilder(pctx, ctx)
1088 createCommand(rule.Command(), buildStatement, executionRoot, bazelOutDir, ctx)
1089 desc := fmt.Sprintf("%s: %s", buildStatement.Mnemonic, buildStatement.OutputPaths)
1090 rule.Build(fmt.Sprintf("bazel %d", index), desc)
1091 continue
1092 }
1093 // Certain actions returned by aquery (for instance FileWrite) do not contain a command
1094 // and thus require special treatment. If BuildStatement were an interface implementing
1095 // buildRule(ctx) function, the code here would just call it.
1096 // Unfortunately, the BuildStatement is defined in
1097 // the 'bazel' package, which cannot depend on 'android' package where ctx is defined,
1098 // because this would cause circular dependency. So, until we move aquery processing
1099 // to the 'android' package, we need to handle special cases here.
1100 if buildStatement.Mnemonic == "FileWrite" || buildStatement.Mnemonic == "SourceSymlinkManifest" {
1101 // Pass file contents as the value of the rule's "content" argument.
1102 // Escape newlines and $ in the contents (the action "writeBazelFile" restores "\\n"
1103 // back to the newline, and Ninja reads $$ as $.
1104 escaped := strings.ReplaceAll(strings.ReplaceAll(buildStatement.FileContents, "\n", "\\n"),
1105 "$", "$$")
1106 ctx.Build(pctx, BuildParams{
1107 Rule: writeBazelFile,
1108 Output: PathForBazelOut(ctx, buildStatement.OutputPaths[0]),
1109 Description: fmt.Sprintf("%s %s", buildStatement.Mnemonic, buildStatement.OutputPaths[0]),
1110 Args: map[string]string{
1111 "content": escaped,
1112 },
1113 })
Sasha Smundakc180dbd2022-07-03 14:55:58 -07001114 } else if buildStatement.Mnemonic == "SymlinkTree" {
1115 // build-runfiles arguments are the manifest file and the target directory
1116 // where it creates the symlink tree according to this manifest (and then
1117 // writes the MANIFEST file to it).
1118 outManifest := PathForBazelOut(ctx, buildStatement.OutputPaths[0])
1119 outManifestPath := outManifest.String()
1120 if !strings.HasSuffix(outManifestPath, "MANIFEST") {
1121 panic("the base name of the symlink tree action should be MANIFEST, got " + outManifestPath)
1122 }
1123 outDir := filepath.Dir(outManifestPath)
1124 ctx.Build(pctx, BuildParams{
1125 Rule: buildRunfilesRule,
1126 Output: outManifest,
1127 Inputs: []Path{PathForBazelOut(ctx, buildStatement.InputPaths[0])},
1128 Description: "symlink tree for " + outDir,
1129 Args: map[string]string{
1130 "outDir": outDir,
1131 },
1132 })
Sasha Smundak1da064c2022-06-08 16:36:16 -07001133 } else {
Rupert Shuttlewortha29903f2021-04-06 16:17:33 +00001134 panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
Chris Parsons8d6e4332021-02-22 16:13:50 -05001135 }
Chris Parsonsa798d962020-10-12 23:44:08 -04001136 }
1137}
Chris Parsons8d6e4332021-02-22 16:13:50 -05001138
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001139// Register bazel-owned build statements (obtained from the aquery invocation).
1140func createCommand(cmd *RuleBuilderCommand, buildStatement bazel.BuildStatement, executionRoot string, bazelOutDir string, ctx PathContext) {
1141 // executionRoot is the action cwd.
1142 cmd.Text(fmt.Sprintf("cd '%s' &&", executionRoot))
1143
1144 // Remove old outputs, as some actions might not rerun if the outputs are detected.
1145 if len(buildStatement.OutputPaths) > 0 {
Jingwen Chenf3b1ec32022-11-07 15:02:48 +00001146 cmd.Text("rm -rf") // -r because outputs can be Bazel dir/tree artifacts.
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001147 for _, outputPath := range buildStatement.OutputPaths {
Usta Shresthaef922252022-06-02 14:23:02 -04001148 cmd.Text(fmt.Sprintf("'%s'", outputPath))
Usta Shresthaacd5a0c2022-06-22 11:20:50 -04001149 }
1150 cmd.Text("&&")
1151 }
1152
1153 for _, pair := range buildStatement.Env {
1154 // Set per-action env variables, if any.
1155 cmd.Flag(pair.Key + "=" + pair.Value)
1156 }
1157
1158 // The actual Bazel action.
1159 cmd.Text(buildStatement.Command)
1160
1161 for _, outputPath := range buildStatement.OutputPaths {
1162 cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath))
1163 }
1164 for _, inputPath := range buildStatement.InputPaths {
1165 cmd.Implicit(PathForBazelOut(ctx, inputPath))
1166 }
1167 for _, inputDepsetHash := range buildStatement.InputDepsetHashes {
1168 otherDepsetName := bazelDepsetName(inputDepsetHash)
1169 cmd.Implicit(PathForPhony(ctx, otherDepsetName))
1170 }
1171
1172 if depfile := buildStatement.Depfile; depfile != nil {
1173 // The paths in depfile are relative to `executionRoot`.
1174 // Hence, they need to be corrected by replacing "bazel-out"
1175 // with the full `bazelOutDir`.
1176 // Otherwise, implicit outputs and implicit inputs under "bazel-out/"
1177 // would be deemed missing.
1178 // (Note: The regexp uses a capture group because the version of sed
1179 // does not support a look-behind pattern.)
1180 replacement := fmt.Sprintf(`&& sed -i'' -E 's@(^|\s|")bazel-out/@\1%s/@g' '%s'`,
1181 bazelOutDir, *depfile)
1182 cmd.Text(replacement)
1183 cmd.ImplicitDepFile(PathForBazelOut(ctx, *depfile))
1184 }
1185
1186 for _, symlinkPath := range buildStatement.SymlinkPaths {
1187 cmd.ImplicitSymlinkOutput(PathForBazelOut(ctx, symlinkPath))
1188 }
1189}
1190
Chris Parsons8d6e4332021-02-22 16:13:50 -05001191func getCqueryId(key cqueryKey) string {
Chris Parsons787fb362021-10-14 18:43:51 -04001192 return key.label + "|" + getConfigString(key)
Chris Parsons8d6e4332021-02-22 16:13:50 -05001193}
1194
Chris Parsons787fb362021-10-14 18:43:51 -04001195func getConfigString(key cqueryKey) string {
Liz Kammer0940b892022-03-18 15:55:04 -04001196 arch := key.configKey.arch
Chris Parsons787fb362021-10-14 18:43:51 -04001197 if len(arch) == 0 || arch == "common" {
Sasha Smundak9d46dcf2022-06-08 12:10:36 -07001198 if key.configKey.osType.Class == Device {
1199 // For the generic Android, the expected result is "target|android", which
1200 // corresponds to the product_variable_config named "android_target" in
1201 // build/bazel/platforms/BUILD.bazel.
1202 arch = "target"
1203 } else {
1204 // Use host platform, which is currently hardcoded to be x86_64.
1205 arch = "x86_64"
1206 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001207 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001208 osName := key.configKey.osType.Name
1209 if len(osName) == 0 || osName == "common_os" || osName == "linux_glibc" {
Chris Parsons787fb362021-10-14 18:43:51 -04001210 // Use host OS, which is currently hardcoded to be linux.
Usta Shrestha16ac1352022-06-22 11:01:55 -04001211 osName = "linux"
Chris Parsons787fb362021-10-14 18:43:51 -04001212 }
Usta Shrestha16ac1352022-06-22 11:01:55 -04001213 return arch + "|" + osName
Chris Parsons787fb362021-10-14 18:43:51 -04001214}
1215
Chris Parsonsf874e462022-05-10 13:50:12 -04001216func GetConfigKey(ctx BaseModuleContext) configKey {
Liz Kammer0940b892022-03-18 15:55:04 -04001217 return configKey{
1218 // use string because Arch is not a valid key in go
1219 arch: ctx.Arch().String(),
1220 osType: ctx.Os(),
1221 }
Chris Parsons8d6e4332021-02-22 16:13:50 -05001222}
Chris Parsons1a7aca02022-04-25 22:35:15 -04001223
Chris Parsons0bfb1c02022-05-12 16:43:01 -04001224func bazelDepsetName(contentHash string) string {
1225 return fmt.Sprintf("bazel_depset_%s", contentHash)
Chris Parsons1a7aca02022-04-25 22:35:15 -04001226}