Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 1 | // 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 | |
| 15 | package android |
| 16 | |
| 17 | import ( |
| 18 | "bytes" |
| 19 | "errors" |
| 20 | "fmt" |
Chris Parsons | a798d96 | 2020-10-12 23:44:08 -0400 | [diff] [blame] | 21 | "io/ioutil" |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 22 | "os" |
| 23 | "os/exec" |
Chris Parsons | a798d96 | 2020-10-12 23:44:08 -0400 | [diff] [blame] | 24 | "path/filepath" |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 25 | "runtime" |
| 26 | "strings" |
| 27 | "sync" |
Chris Parsons | a798d96 | 2020-10-12 23:44:08 -0400 | [diff] [blame] | 28 | |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 29 | "github.com/google/blueprint/bootstrap" |
| 30 | |
Patrice Arruda | 05ab2d0 | 2020-12-12 06:24:26 +0000 | [diff] [blame] | 31 | "android/soong/bazel" |
| 32 | "android/soong/shared" |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 33 | ) |
| 34 | |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 35 | type CqueryRequestType int |
| 36 | |
| 37 | const ( |
| 38 | getAllFiles CqueryRequestType = iota |
| 39 | ) |
| 40 | |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 41 | // Map key to describe bazel cquery requests. |
| 42 | type cqueryKey struct { |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 43 | label string |
| 44 | requestType CqueryRequestType |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 45 | } |
| 46 | |
| 47 | type BazelContext interface { |
| 48 | // The below methods involve queuing cquery requests to be later invoked |
| 49 | // by bazel. If any of these methods return (_, false), then the request |
| 50 | // has been queued to be run later. |
| 51 | |
| 52 | // Returns result files built by building the given bazel target label. |
| 53 | GetAllFiles(label string) ([]string, bool) |
| 54 | |
| 55 | // TODO(cparsons): Other cquery-related methods should be added here. |
| 56 | // ** End cquery methods |
| 57 | |
| 58 | // Issues commands to Bazel to receive results for all cquery requests |
| 59 | // queued in the BazelContext. |
| 60 | InvokeBazel() error |
| 61 | |
| 62 | // Returns true if bazel is enabled for the given configuration. |
| 63 | BazelEnabled() bool |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 64 | |
| 65 | // Returns the bazel output base (the root directory for all bazel intermediate outputs). |
| 66 | OutputBase() string |
| 67 | |
| 68 | // Returns build statements which should get registered to reflect Bazel's outputs. |
| 69 | BuildStatementsToRegister() []bazel.BuildStatement |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 70 | } |
| 71 | |
| 72 | // A context object which tracks queued requests that need to be made to Bazel, |
| 73 | // and their results after the requests have been made. |
| 74 | type bazelContext struct { |
| 75 | homeDir string |
| 76 | bazelPath string |
| 77 | outputBase string |
| 78 | workspaceDir string |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 79 | buildDir string |
Patrice Arruda | 05ab2d0 | 2020-12-12 06:24:26 +0000 | [diff] [blame] | 80 | metricsDir string |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 81 | |
| 82 | requests map[cqueryKey]bool // cquery requests that have not yet been issued to Bazel |
| 83 | requestMutex sync.Mutex // requests can be written in parallel |
| 84 | |
| 85 | results map[cqueryKey]string // Results of cquery requests after Bazel invocations |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 86 | |
| 87 | // Build statements which should get registered to reflect Bazel's outputs. |
| 88 | buildStatements []bazel.BuildStatement |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 89 | } |
| 90 | |
| 91 | var _ BazelContext = &bazelContext{} |
| 92 | |
| 93 | // A bazel context to use when Bazel is disabled. |
| 94 | type noopBazelContext struct{} |
| 95 | |
| 96 | var _ BazelContext = noopBazelContext{} |
| 97 | |
| 98 | // A bazel context to use for tests. |
| 99 | type MockBazelContext struct { |
| 100 | AllFiles map[string][]string |
| 101 | } |
| 102 | |
| 103 | func (m MockBazelContext) GetAllFiles(label string) ([]string, bool) { |
| 104 | result, ok := m.AllFiles[label] |
| 105 | return result, ok |
| 106 | } |
| 107 | |
| 108 | func (m MockBazelContext) InvokeBazel() error { |
| 109 | panic("unimplemented") |
| 110 | } |
| 111 | |
| 112 | func (m MockBazelContext) BazelEnabled() bool { |
| 113 | return true |
| 114 | } |
| 115 | |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 116 | func (m MockBazelContext) OutputBase() string { |
| 117 | return "outputbase" |
| 118 | } |
| 119 | |
| 120 | func (m MockBazelContext) BuildStatementsToRegister() []bazel.BuildStatement { |
| 121 | return []bazel.BuildStatement{} |
| 122 | } |
| 123 | |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 124 | var _ BazelContext = MockBazelContext{} |
| 125 | |
| 126 | func (bazelCtx *bazelContext) GetAllFiles(label string) ([]string, bool) { |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 127 | result, ok := bazelCtx.cquery(label, getAllFiles) |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 128 | if ok { |
| 129 | bazelOutput := strings.TrimSpace(result) |
| 130 | return strings.Split(bazelOutput, ", "), true |
| 131 | } else { |
| 132 | return nil, false |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | func (n noopBazelContext) GetAllFiles(label string) ([]string, bool) { |
| 137 | panic("unimplemented") |
| 138 | } |
| 139 | |
| 140 | func (n noopBazelContext) InvokeBazel() error { |
| 141 | panic("unimplemented") |
| 142 | } |
| 143 | |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 144 | func (m noopBazelContext) OutputBase() string { |
| 145 | return "" |
| 146 | } |
| 147 | |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 148 | func (n noopBazelContext) BazelEnabled() bool { |
| 149 | return false |
| 150 | } |
| 151 | |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 152 | func (m noopBazelContext) BuildStatementsToRegister() []bazel.BuildStatement { |
| 153 | return []bazel.BuildStatement{} |
| 154 | } |
| 155 | |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 156 | func NewBazelContext(c *config) (BazelContext, error) { |
Chris Parsons | 8b77a00 | 2020-10-27 18:59:25 -0400 | [diff] [blame] | 157 | // TODO(cparsons): Assess USE_BAZEL=1 instead once "mixed Soong/Bazel builds" |
| 158 | // are production ready. |
| 159 | if c.Getenv("USE_BAZEL_ANALYSIS") != "1" { |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 160 | return noopBazelContext{}, nil |
| 161 | } |
| 162 | |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 163 | bazelCtx := bazelContext{buildDir: c.buildDir, requests: make(map[cqueryKey]bool)} |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 164 | missingEnvVars := []string{} |
| 165 | if len(c.Getenv("BAZEL_HOME")) > 1 { |
| 166 | bazelCtx.homeDir = c.Getenv("BAZEL_HOME") |
| 167 | } else { |
| 168 | missingEnvVars = append(missingEnvVars, "BAZEL_HOME") |
| 169 | } |
| 170 | if len(c.Getenv("BAZEL_PATH")) > 1 { |
| 171 | bazelCtx.bazelPath = c.Getenv("BAZEL_PATH") |
| 172 | } else { |
| 173 | missingEnvVars = append(missingEnvVars, "BAZEL_PATH") |
| 174 | } |
| 175 | if len(c.Getenv("BAZEL_OUTPUT_BASE")) > 1 { |
| 176 | bazelCtx.outputBase = c.Getenv("BAZEL_OUTPUT_BASE") |
| 177 | } else { |
| 178 | missingEnvVars = append(missingEnvVars, "BAZEL_OUTPUT_BASE") |
| 179 | } |
| 180 | if len(c.Getenv("BAZEL_WORKSPACE")) > 1 { |
| 181 | bazelCtx.workspaceDir = c.Getenv("BAZEL_WORKSPACE") |
| 182 | } else { |
| 183 | missingEnvVars = append(missingEnvVars, "BAZEL_WORKSPACE") |
| 184 | } |
Patrice Arruda | 05ab2d0 | 2020-12-12 06:24:26 +0000 | [diff] [blame] | 185 | if len(c.Getenv("BAZEL_METRICS_DIR")) > 1 { |
| 186 | bazelCtx.metricsDir = c.Getenv("BAZEL_METRICS_DIR") |
| 187 | } else { |
| 188 | missingEnvVars = append(missingEnvVars, "BAZEL_METRICS_DIR") |
| 189 | } |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 190 | if len(missingEnvVars) > 0 { |
| 191 | return nil, errors.New(fmt.Sprintf("missing required env vars to use bazel: %s", missingEnvVars)) |
| 192 | } else { |
| 193 | return &bazelCtx, nil |
| 194 | } |
| 195 | } |
| 196 | |
Patrice Arruda | 05ab2d0 | 2020-12-12 06:24:26 +0000 | [diff] [blame] | 197 | func (context *bazelContext) BazelMetricsDir() string { |
| 198 | return context.metricsDir |
| 199 | } |
| 200 | |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 201 | func (context *bazelContext) BazelEnabled() bool { |
| 202 | return true |
| 203 | } |
| 204 | |
| 205 | // Adds a cquery request to the Bazel request queue, to be later invoked, or |
| 206 | // returns the result of the given request if the request was already made. |
| 207 | // If the given request was already made (and the results are available), then |
| 208 | // returns (result, true). If the request is queued but no results are available, |
| 209 | // then returns ("", false). |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 210 | func (context *bazelContext) cquery(label string, requestType CqueryRequestType) (string, bool) { |
| 211 | key := cqueryKey{label, requestType} |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 212 | if result, ok := context.results[key]; ok { |
| 213 | return result, true |
| 214 | } else { |
| 215 | context.requestMutex.Lock() |
| 216 | defer context.requestMutex.Unlock() |
| 217 | context.requests[key] = true |
| 218 | return "", false |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | func pwdPrefix() string { |
| 223 | // Darwin doesn't have /proc |
| 224 | if runtime.GOOS != "darwin" { |
| 225 | return "PWD=/proc/self/cwd" |
| 226 | } |
| 227 | return "" |
| 228 | } |
| 229 | |
Patrice Arruda | 05ab2d0 | 2020-12-12 06:24:26 +0000 | [diff] [blame] | 230 | func (context *bazelContext) issueBazelCommand(runName bazel.RunName, command string, labels []string, |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 231 | extraFlags ...string) (string, error) { |
| 232 | |
Jingwen Chen | 7c6089a | 2020-11-02 02:56:20 -0500 | [diff] [blame] | 233 | cmdFlags := []string{"--output_base=" + context.outputBase, command} |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 234 | cmdFlags = append(cmdFlags, labels...) |
Chris Parsons | 8ccdb63 | 2020-11-17 15:41:01 -0500 | [diff] [blame] | 235 | cmdFlags = append(cmdFlags, "--package_path=%workspace%/"+context.intermediatesDir()) |
Patrice Arruda | 05ab2d0 | 2020-12-12 06:24:26 +0000 | [diff] [blame] | 236 | cmdFlags = append(cmdFlags, "--profile="+shared.BazelMetricsFilename(context, runName)) |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 237 | cmdFlags = append(cmdFlags, extraFlags...) |
| 238 | |
| 239 | bazelCmd := exec.Command(context.bazelPath, cmdFlags...) |
| 240 | bazelCmd.Dir = context.workspaceDir |
| 241 | bazelCmd.Env = append(os.Environ(), "HOME="+context.homeDir, pwdPrefix()) |
| 242 | |
Colin Cross | ff0278b | 2020-10-09 19:24:15 -0700 | [diff] [blame] | 243 | stderr := &bytes.Buffer{} |
| 244 | bazelCmd.Stderr = stderr |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 245 | |
| 246 | if output, err := bazelCmd.Output(); err != nil { |
| 247 | return "", fmt.Errorf("bazel command failed. command: [%s], error [%s]", bazelCmd, stderr) |
| 248 | } else { |
| 249 | return string(output), nil |
| 250 | } |
| 251 | } |
| 252 | |
Chris Parsons | 8ccdb63 | 2020-11-17 15:41:01 -0500 | [diff] [blame] | 253 | // Returns the string contents of a workspace file that should be output |
| 254 | // adjacent to the main bzl file and build file. |
| 255 | // This workspace file allows, via local_repository rule, sourcetree-level |
| 256 | // BUILD targets to be referenced via @sourceroot. |
| 257 | func (context *bazelContext) workspaceFileContents() []byte { |
| 258 | formatString := ` |
| 259 | # This file is generated by soong_build. Do not edit. |
| 260 | local_repository( |
| 261 | name = "sourceroot", |
| 262 | path = "%s", |
| 263 | ) |
| 264 | ` |
| 265 | return []byte(fmt.Sprintf(formatString, context.workspaceDir)) |
| 266 | } |
| 267 | |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 268 | func (context *bazelContext) mainBzlFileContents() []byte { |
| 269 | contents := ` |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 270 | ##################################################### |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 271 | # This file is generated by soong_build. Do not edit. |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 272 | ##################################################### |
| 273 | |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 274 | def _mixed_build_root_impl(ctx): |
| 275 | return [DefaultInfo(files = depset(ctx.files.deps))] |
| 276 | |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 277 | # Rule representing the root of the build, to depend on all Bazel targets that |
| 278 | # are required for the build. Building this target will build the entire Bazel |
| 279 | # build tree. |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 280 | mixed_build_root = rule( |
| 281 | implementation = _mixed_build_root_impl, |
| 282 | attrs = {"deps" : attr.label_list()}, |
| 283 | ) |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 284 | |
| 285 | def _phony_root_impl(ctx): |
| 286 | return [] |
| 287 | |
| 288 | # Rule to depend on other targets but build nothing. |
| 289 | # This is useful as follows: building a target of this rule will generate |
| 290 | # symlink forests for all dependencies of the target, without executing any |
| 291 | # actions of the build. |
| 292 | phony_root = rule( |
| 293 | implementation = _phony_root_impl, |
| 294 | attrs = {"deps" : attr.label_list()}, |
| 295 | ) |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 296 | ` |
| 297 | return []byte(contents) |
| 298 | } |
| 299 | |
Chris Parsons | 8ccdb63 | 2020-11-17 15:41:01 -0500 | [diff] [blame] | 300 | // Returns a "canonicalized" corresponding to the given sourcetree-level label. |
| 301 | // This abstraction is required because a sourcetree label such as //foo/bar:baz |
| 302 | // must be referenced via the local repository prefix, such as |
| 303 | // @sourceroot//foo/bar:baz. |
| 304 | func canonicalizeLabel(label string) string { |
| 305 | if strings.HasPrefix(label, "//") { |
| 306 | return "@sourceroot" + label |
| 307 | } else { |
| 308 | return "@sourceroot//" + label |
| 309 | } |
| 310 | } |
| 311 | |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 312 | func (context *bazelContext) mainBuildFileContents() []byte { |
| 313 | formatString := ` |
| 314 | # This file is generated by soong_build. Do not edit. |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 315 | load(":main.bzl", "mixed_build_root", "phony_root") |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 316 | |
| 317 | mixed_build_root(name = "buildroot", |
| 318 | deps = [%s], |
| 319 | ) |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 320 | |
| 321 | phony_root(name = "phonyroot", |
| 322 | deps = [":buildroot"], |
| 323 | ) |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 324 | ` |
| 325 | var buildRootDeps []string = nil |
| 326 | for val, _ := range context.requests { |
Chris Parsons | 8ccdb63 | 2020-11-17 15:41:01 -0500 | [diff] [blame] | 327 | buildRootDeps = append(buildRootDeps, fmt.Sprintf("\"%s\"", canonicalizeLabel(val.label))) |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 328 | } |
| 329 | buildRootDepsString := strings.Join(buildRootDeps, ",\n ") |
| 330 | |
| 331 | return []byte(fmt.Sprintf(formatString, buildRootDepsString)) |
| 332 | } |
| 333 | |
| 334 | func (context *bazelContext) cqueryStarlarkFileContents() []byte { |
| 335 | formatString := ` |
| 336 | # This file is generated by soong_build. Do not edit. |
| 337 | getAllFilesLabels = { |
| 338 | %s |
| 339 | } |
| 340 | |
| 341 | def format(target): |
| 342 | if str(target.label) in getAllFilesLabels: |
| 343 | return str(target.label) + ">>" + ', '.join([f.path for f in target.files.to_list()]) |
| 344 | else: |
| 345 | # This target was not requested via cquery, and thus must be a dependency |
| 346 | # of a requested target. |
| 347 | return "" |
| 348 | ` |
| 349 | var buildRootDeps []string = nil |
| 350 | // TODO(cparsons): Sort by request type instead of assuming all requests |
| 351 | // are of GetAllFiles type. |
| 352 | for val, _ := range context.requests { |
Chris Parsons | 8ccdb63 | 2020-11-17 15:41:01 -0500 | [diff] [blame] | 353 | buildRootDeps = append(buildRootDeps, fmt.Sprintf("\"%s\" : True", canonicalizeLabel(val.label))) |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 354 | } |
| 355 | buildRootDepsString := strings.Join(buildRootDeps, ",\n ") |
| 356 | |
| 357 | return []byte(fmt.Sprintf(formatString, buildRootDepsString)) |
| 358 | } |
| 359 | |
Chris Parsons | 8ccdb63 | 2020-11-17 15:41:01 -0500 | [diff] [blame] | 360 | // Returns a workspace-relative path containing build-related metadata required |
| 361 | // for interfacing with Bazel. Example: out/soong/bazel. |
| 362 | func (context *bazelContext) intermediatesDir() string { |
| 363 | return filepath.Join(context.buildDir, "bazel") |
| 364 | } |
| 365 | |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 366 | // Issues commands to Bazel to receive results for all cquery requests |
| 367 | // queued in the BazelContext. |
| 368 | func (context *bazelContext) InvokeBazel() error { |
| 369 | context.results = make(map[cqueryKey]string) |
| 370 | |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 371 | var cqueryOutput string |
| 372 | var err error |
Chris Parsons | 8ccdb63 | 2020-11-17 15:41:01 -0500 | [diff] [blame] | 373 | |
| 374 | err = os.Mkdir(absolutePath(context.intermediatesDir()), 0777) |
| 375 | if err != nil { |
| 376 | return err |
| 377 | } |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 378 | err = ioutil.WriteFile( |
Chris Parsons | 8ccdb63 | 2020-11-17 15:41:01 -0500 | [diff] [blame] | 379 | absolutePath(filepath.Join(context.intermediatesDir(), "main.bzl")), |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 380 | context.mainBzlFileContents(), 0666) |
| 381 | if err != nil { |
| 382 | return err |
| 383 | } |
| 384 | err = ioutil.WriteFile( |
Chris Parsons | 8ccdb63 | 2020-11-17 15:41:01 -0500 | [diff] [blame] | 385 | absolutePath(filepath.Join(context.intermediatesDir(), "BUILD.bazel")), |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 386 | context.mainBuildFileContents(), 0666) |
| 387 | if err != nil { |
| 388 | return err |
| 389 | } |
Chris Parsons | 8ccdb63 | 2020-11-17 15:41:01 -0500 | [diff] [blame] | 390 | cquery_file_relpath := filepath.Join(context.intermediatesDir(), "buildroot.cquery") |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 391 | err = ioutil.WriteFile( |
| 392 | absolutePath(cquery_file_relpath), |
| 393 | context.cqueryStarlarkFileContents(), 0666) |
| 394 | if err != nil { |
| 395 | return err |
| 396 | } |
Chris Parsons | 8ccdb63 | 2020-11-17 15:41:01 -0500 | [diff] [blame] | 397 | workspace_file_relpath := filepath.Join(context.intermediatesDir(), "WORKSPACE.bazel") |
| 398 | err = ioutil.WriteFile( |
| 399 | absolutePath(workspace_file_relpath), |
| 400 | context.workspaceFileContents(), 0666) |
| 401 | if err != nil { |
| 402 | return err |
| 403 | } |
| 404 | buildroot_label := "//:buildroot" |
Patrice Arruda | 05ab2d0 | 2020-12-12 06:24:26 +0000 | [diff] [blame] | 405 | cqueryOutput, err = context.issueBazelCommand(bazel.CqueryBuildRootRunName, "cquery", |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 406 | []string{fmt.Sprintf("deps(%s)", buildroot_label)}, |
| 407 | "--output=starlark", |
| 408 | "--starlark:file="+cquery_file_relpath) |
| 409 | |
| 410 | if err != nil { |
| 411 | return err |
| 412 | } |
| 413 | |
| 414 | cqueryResults := map[string]string{} |
| 415 | for _, outputLine := range strings.Split(cqueryOutput, "\n") { |
| 416 | if strings.Contains(outputLine, ">>") { |
| 417 | splitLine := strings.SplitN(outputLine, ">>", 2) |
| 418 | cqueryResults[splitLine[0]] = splitLine[1] |
| 419 | } |
| 420 | } |
| 421 | |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 422 | for val, _ := range context.requests { |
Chris Parsons | 8ccdb63 | 2020-11-17 15:41:01 -0500 | [diff] [blame] | 423 | if cqueryResult, ok := cqueryResults[canonicalizeLabel(val.label)]; ok { |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 424 | context.results[val] = string(cqueryResult) |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 425 | } else { |
Chris Parsons | b0f8ac4 | 2020-10-23 16:48:08 -0400 | [diff] [blame] | 426 | return fmt.Errorf("missing result for bazel target %s", val.label) |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 427 | } |
| 428 | } |
| 429 | |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 430 | // Issue an aquery command to retrieve action information about the bazel build tree. |
| 431 | // |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 432 | // TODO(cparsons): Use --target_pattern_file to avoid command line limits. |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 433 | var aqueryOutput string |
| 434 | aqueryOutput, err = context.issueBazelCommand(bazel.AqueryBuildRootRunName, "aquery", |
| 435 | []string{fmt.Sprintf("deps(%s)", buildroot_label), |
| 436 | // Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's |
| 437 | // proto sources, which would add a number of unnecessary dependencies. |
| 438 | "--output=jsonproto"}) |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 439 | |
| 440 | if err != nil { |
| 441 | return err |
| 442 | } |
| 443 | |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 444 | context.buildStatements = bazel.AqueryBuildStatements([]byte(aqueryOutput)) |
| 445 | |
| 446 | // Issue a build command of the phony root to generate symlink forests for dependencies of the |
| 447 | // Bazel build. This is necessary because aquery invocations do not generate this symlink forest, |
| 448 | // but some of symlinks may be required to resolve source dependencies of the build. |
| 449 | _, err = context.issueBazelCommand(bazel.BazelBuildPhonyRootRunName, "build", |
| 450 | []string{"//:phonyroot"}) |
| 451 | |
| 452 | if err != nil { |
| 453 | return err |
| 454 | } |
| 455 | |
| 456 | fmt.Printf("Build statements %s", context.buildStatements) |
Chris Parsons | f3c96ef | 2020-09-29 02:23:17 -0400 | [diff] [blame] | 457 | // Clear requests. |
| 458 | context.requests = map[cqueryKey]bool{} |
| 459 | return nil |
| 460 | } |
Chris Parsons | a798d96 | 2020-10-12 23:44:08 -0400 | [diff] [blame] | 461 | |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 462 | func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement { |
| 463 | return context.buildStatements |
| 464 | } |
| 465 | |
| 466 | func (context *bazelContext) OutputBase() string { |
| 467 | return context.outputBase |
| 468 | } |
| 469 | |
Chris Parsons | a798d96 | 2020-10-12 23:44:08 -0400 | [diff] [blame] | 470 | // Singleton used for registering BUILD file ninja dependencies (needed |
| 471 | // for correctness of builds which use Bazel. |
| 472 | func BazelSingleton() Singleton { |
| 473 | return &bazelSingleton{} |
| 474 | } |
| 475 | |
| 476 | type bazelSingleton struct{} |
| 477 | |
| 478 | func (c *bazelSingleton) GenerateBuildActions(ctx SingletonContext) { |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 479 | // bazelSingleton is a no-op if mixed-soong-bazel-builds are disabled. |
| 480 | if !ctx.Config().BazelContext.BazelEnabled() { |
| 481 | return |
| 482 | } |
Chris Parsons | a798d96 | 2020-10-12 23:44:08 -0400 | [diff] [blame] | 483 | |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 484 | // Add ninja file dependencies for files which all bazel invocations require. |
| 485 | bazelBuildList := absolutePath(filepath.Join( |
| 486 | filepath.Dir(bootstrap.ModuleListFile), "bazel.list")) |
| 487 | ctx.AddNinjaFileDeps(bazelBuildList) |
| 488 | |
| 489 | data, err := ioutil.ReadFile(bazelBuildList) |
| 490 | if err != nil { |
| 491 | ctx.Errorf(err.Error()) |
| 492 | } |
| 493 | files := strings.Split(strings.TrimSpace(string(data)), "\n") |
| 494 | for _, file := range files { |
| 495 | ctx.AddNinjaFileDeps(file) |
| 496 | } |
| 497 | |
| 498 | // Register bazel-owned build statements (obtained from the aquery invocation). |
| 499 | for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() { |
| 500 | rule := NewRuleBuilder(pctx, ctx) |
| 501 | cmd := rule.Command() |
| 502 | cmd.Text(fmt.Sprintf("cd %s/execroot/__main__ && %s", |
| 503 | ctx.Config().BazelContext.OutputBase(), buildStatement.Command)) |
| 504 | |
| 505 | for _, outputPath := range buildStatement.OutputPaths { |
| 506 | cmd.ImplicitOutput(PathForBazelOut(ctx, outputPath)) |
Chris Parsons | a798d96 | 2020-10-12 23:44:08 -0400 | [diff] [blame] | 507 | } |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 508 | for _, inputPath := range buildStatement.InputPaths { |
| 509 | cmd.Implicit(PathForBazelOut(ctx, inputPath)) |
Chris Parsons | a798d96 | 2020-10-12 23:44:08 -0400 | [diff] [blame] | 510 | } |
Chris Parsons | dbcb1ff | 2020-12-10 17:19:18 -0500 | [diff] [blame] | 511 | |
| 512 | // This is required to silence warnings pertaining to unexpected timestamps. Particularly, |
| 513 | // some Bazel builtins (such as files in the bazel_tools directory) have far-future |
| 514 | // timestamps. Without restat, Ninja would emit warnings that the input files of a |
| 515 | // build statement have later timestamps than the outputs. |
| 516 | rule.Restat() |
| 517 | |
Liz Kammer | 13548d7 | 2020-12-16 11:13:30 -0800 | [diff] [blame^] | 518 | rule.Build(fmt.Sprintf("bazel %d", index), buildStatement.Mnemonic) |
Chris Parsons | a798d96 | 2020-10-12 23:44:08 -0400 | [diff] [blame] | 519 | } |
| 520 | } |