blob: 2d36f67a44de0f7ef8f5753e4bfde3be422bb8f1 [file] [log] [blame]
Rupert Shuttleworth680387b2020-10-25 12:31:27 +00001// 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 build
16
17import (
Chris Parsonsc09495b2020-11-04 20:45:50 -050018 "io/ioutil"
19 "os"
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000020 "path/filepath"
21 "strings"
Patrice Arruda18cb70d2020-11-13 11:37:06 -080022
23 "android/soong/shared"
Patrice Arrudab7cf9ba2020-11-13 13:04:17 -080024 "android/soong/ui/metrics"
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000025)
26
Jingwen Chen7a5391a2020-11-17 03:42:12 -050027// Main entry point to construct the Bazel build command line, environment
28// variables and post-processing steps (e.g. converge output directories)
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000029func runBazel(ctx Context, config Config) {
Patrice Arrudab7cf9ba2020-11-13 13:04:17 -080030 ctx.BeginTrace(metrics.RunBazel, "bazel")
31 defer ctx.EndTrace()
32
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000033 // "droid" is the default ninja target.
Jingwen Chen8024c952020-11-08 23:57:56 -050034 // TODO(b/160568333): stop hardcoding 'droid' to support building any
35 // Ninja target.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000036 outputGroups := "droid"
37 if len(config.ninjaArgs) > 0 {
38 // At this stage, the residue slice of args passed to ninja
39 // are the ninja targets to build, which can correspond directly
40 // to ninja_build's output_groups.
41 outputGroups = strings.Join(config.ninjaArgs, ",")
42 }
43
Jingwen Chen7a5391a2020-11-17 03:42:12 -050044 // Environment variables are the primary mechanism to pass information from
45 // soong_ui configuration or context to Bazel.
46 //
47 // Use *_NINJA variables to pass the root-relative path of the combined,
48 // kati-generated, soong-generated, and packaging Ninja files to Bazel.
49 // Bazel reads these from the lunch() repository rule.
Jingwen Chena26ac3c2020-11-10 08:17:59 -050050 config.environ.Set("COMBINED_NINJA", config.CombinedNinjaFile())
51 config.environ.Set("KATI_NINJA", config.KatiBuildNinjaFile())
52 config.environ.Set("PACKAGE_NINJA", config.KatiPackageNinjaFile())
53 config.environ.Set("SOONG_NINJA", config.SoongNinjaFile())
54
Jingwen Chen7a5391a2020-11-17 03:42:12 -050055 // `tools/bazel` is the default entry point for executing Bazel in the AOSP
56 // source tree.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000057 bazelExecutable := filepath.Join("tools", "bazel")
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +000058 cmd := Command(ctx, config, "bazel", bazelExecutable)
59
Jingwen Chen7a5391a2020-11-17 03:42:12 -050060 // Append custom startup flags to the Bazel command. Startup flags affect
61 // the Bazel server itself, and any changes to these flags would incur a
62 // restart of the server, losing much of the in-memory incrementality.
63 if extraStartupArgs, ok := cmd.Environment.Get("BAZEL_STARTUP_ARGS"); ok {
64 cmd.Args = append(cmd.Args, strings.Fields(extraStartupArgs)...)
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000065 }
66
Jingwen Chen7a5391a2020-11-17 03:42:12 -050067 // Start constructing the `build` command.
Patrice Arruda18cb70d2020-11-13 11:37:06 -080068 actionName := "build"
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +000069 cmd.Args = append(cmd.Args,
Patrice Arruda18cb70d2020-11-13 11:37:06 -080070 actionName,
Jingwen Chen7a5391a2020-11-17 03:42:12 -050071 // Use output_groups to select the set of outputs to produce from a
72 // ninja_build target.
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +000073 "--output_groups="+outputGroups,
Jingwen Chen7a5391a2020-11-17 03:42:12 -050074 // Generate a performance profile
Patrice Arruda18cb70d2020-11-13 11:37:06 -080075 "--profile="+filepath.Join(shared.BazelMetricsFilename(config.OutDir(), actionName)),
76 "--slim_profile=true",
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +000077 )
78
Jingwen Chen7a5391a2020-11-17 03:42:12 -050079 // Append custom build flags to the Bazel command. Changes to these flags
80 // may invalidate Bazel's analysis cache.
81 if extraBuildArgs, ok := cmd.Environment.Get("BAZEL_BUILD_ARGS"); ok {
82 cmd.Args = append(cmd.Args, strings.Fields(extraBuildArgs)...)
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +000083 }
84
Jingwen Chen7a5391a2020-11-17 03:42:12 -050085 // Append the label of the default ninja_build target.
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +000086 cmd.Args = append(cmd.Args,
87 "//:"+config.TargetProduct()+"-"+config.TargetBuildVariant(),
88 )
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000089
Jingwen Chen7a5391a2020-11-17 03:42:12 -050090 // Ensure that the PATH environment variable value used in the action
91 // environment is the restricted set computed from soong_ui, and not a
92 // user-provided one, for hermeticity reasons.
Jingwen Chen3a4b58d2020-11-16 04:19:35 -050093 if pathEnvValue, ok := config.environ.Get("PATH"); ok {
94 cmd.Environment.Set("PATH", pathEnvValue)
95 cmd.Args = append(cmd.Args, "--action_env=PATH="+pathEnvValue)
96 }
Jingwen Chen7a5391a2020-11-17 03:42:12 -050097
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000098 cmd.Environment.Set("DIST_DIR", config.DistDir())
99 cmd.Environment.Set("SHELL", "/bin/bash")
100
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500101 // Print the full command line for debugging purposes.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000102 ctx.Println(cmd.Cmd)
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500103
104 // Execute the command at the root of the directory.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000105 cmd.Dir = filepath.Join(config.OutDir(), "..")
106 ctx.Status.Status("Starting Bazel..")
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500107
108 // Execute the build command.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000109 cmd.RunAndStreamOrFatal()
Chris Parsonsc09495b2020-11-04 20:45:50 -0500110
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500111 // Post-processing steps start here. Once the Bazel build completes, the
112 // output files are still stored in the execution root, not in $OUT_DIR.
113 // Ensure that the $OUT_DIR contains the expected set of files by symlinking
114 // the files from the execution root's output direction into $OUT_DIR.
115
Chris Parsonsc09495b2020-11-04 20:45:50 -0500116 // Obtain the Bazel output directory for ninja_build.
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +0000117 infoCmd := Command(ctx, config, "bazel", bazelExecutable)
118
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500119 if extraStartupArgs, ok := infoCmd.Environment.Get("BAZEL_STARTUP_ARGS"); ok {
120 infoCmd.Args = append(infoCmd.Args, strings.Fields(extraStartupArgs)...)
Chris Parsonsc09495b2020-11-04 20:45:50 -0500121 }
122
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500123 // Obtain the output directory path in the execution root.
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +0000124 infoCmd.Args = append(infoCmd.Args,
125 "info",
126 "output_path",
127 )
Chris Parsonsc09495b2020-11-04 20:45:50 -0500128
129 infoCmd.Environment.Set("DIST_DIR", config.DistDir())
130 infoCmd.Environment.Set("SHELL", "/bin/bash")
131 infoCmd.Dir = filepath.Join(config.OutDir(), "..")
132 ctx.Status.Status("Getting Bazel Info..")
133 outputBasePath := string(infoCmd.OutputOrFatal())
134 // TODO: Don't hardcode out/ as the bazel output directory. This is
135 // currently hardcoded as ninja_build.output_root.
136 bazelNinjaBuildOutputRoot := filepath.Join(outputBasePath, "..", "out")
137
138 symlinkOutdir(ctx, config, bazelNinjaBuildOutputRoot, ".")
139}
140
141// For all files F recursively under rootPath/relativePath, creates symlinks
142// such that OutDir/F resolves to rootPath/F via symlinks.
143func symlinkOutdir(ctx Context, config Config, rootPath string, relativePath string) {
144 destDir := filepath.Join(rootPath, relativePath)
145 os.MkdirAll(destDir, 0755)
146 files, err := ioutil.ReadDir(destDir)
147 if err != nil {
148 ctx.Fatal(err)
149 }
150 for _, f := range files {
151 destPath := filepath.Join(destDir, f.Name())
152 srcPath := filepath.Join(config.OutDir(), relativePath, f.Name())
153 if statResult, err := os.Stat(srcPath); err == nil {
154 if statResult.Mode().IsDir() && f.IsDir() {
155 // Directory under OutDir already exists, so recurse on its contents.
156 symlinkOutdir(ctx, config, rootPath, filepath.Join(relativePath, f.Name()))
157 } else if !statResult.Mode().IsDir() && !f.IsDir() {
158 // File exists both in source and destination, and it's not a directory
159 // in either location. Do nothing.
160 // This can arise for files which are generated under OutDir outside of
161 // soong_build, such as .bootstrap files.
162 } else {
163 // File is a directory in one location but not the other. Raise an error.
164 ctx.Fatalf("Could not link %s to %s due to conflict", srcPath, destPath)
165 }
166 } else if os.IsNotExist(err) {
167 // Create symlink srcPath -> fullDestPath.
168 os.Symlink(destPath, srcPath)
169 } else {
170 ctx.Fatalf("Unable to stat %s: %s", srcPath, err)
171 }
172 }
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000173}