blob: 01500a0dfee68946b1f219b7f20485aab2ece4e0 [file] [log] [blame]
Dan Willemsen1e704462016-08-21 15:17:17 -07001// Copyright 2017 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 (
Jeff Gaston809cc6f2017-05-25 15:44:36 -070018 "fmt"
19 "os"
Dan Willemsend9f6fa22016-08-21 15:17:17 -070020 "path/filepath"
Dan Willemsene3336352020-01-02 19:10:38 -080021 "sort"
Dan Willemsen1e704462016-08-21 15:17:17 -070022 "strconv"
23 "strings"
Dan Willemsend9f6fa22016-08-21 15:17:17 -070024 "time"
Dan Willemsenb82471a2018-05-17 16:37:09 -070025
Nan Zhang17f27672018-12-12 16:01:49 -080026 "android/soong/ui/metrics"
Dan Willemsenb82471a2018-05-17 16:37:09 -070027 "android/soong/ui/status"
Dan Willemsen1e704462016-08-21 15:17:17 -070028)
29
Jingwen Chen9d1cb492020-11-17 06:52:28 -050030// Constructs and runs the Ninja command line with a restricted set of
31// environment variables. It's important to restrict the environment Ninja runs
32// for hermeticity reasons, and to avoid spurious rebuilds.
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010033func runNinjaForBuild(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -080034 ctx.BeginTrace(metrics.PrimaryNinja, "ninja")
Dan Willemsend9f6fa22016-08-21 15:17:17 -070035 defer ctx.EndTrace()
36
Jingwen Chen9d1cb492020-11-17 06:52:28 -050037 // Sets up the FIFO status updater that reads the Ninja protobuf output, and
38 // translates it to the soong_ui status output, displaying real-time
39 // progress of the build.
Dan Willemsenb82471a2018-05-17 16:37:09 -070040 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -070041 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
42 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -070043
Dan Willemsenf173d592017-04-27 14:28:00 -070044 executable := config.PrebuiltBuildTool("ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -070045 args := []string{
46 "-d", "keepdepfile",
Dan Willemsen6d3cad92020-03-12 10:30:35 -070047 "-d", "keeprsp",
Dan Willemsen08218222020-05-18 14:02:02 -070048 "-d", "stats",
Dan Willemsen02736672018-07-17 17:54:31 -070049 "--frontend_file", fifo,
Dan Willemsen1e704462016-08-21 15:17:17 -070050 }
51
52 args = append(args, config.NinjaArgs()...)
53
54 var parallel int
Colin Cross9016b912019-11-11 14:57:42 -080055 if config.UseRemoteBuild() {
Dan Willemsen1e704462016-08-21 15:17:17 -070056 parallel = config.RemoteParallel()
57 } else {
58 parallel = config.Parallel()
59 }
60 args = append(args, "-j", strconv.Itoa(parallel))
61 if config.keepGoing != 1 {
62 args = append(args, "-k", strconv.Itoa(config.keepGoing))
63 }
64
65 args = append(args, "-f", config.CombinedNinjaFile())
66
Dan Willemsenf7939332019-01-05 19:31:32 -080067 args = append(args,
Dan Willemsen6587bed2020-04-18 20:25:59 -070068 "-o", "usesphonyoutputs=yes",
Dan Willemsenf7939332019-01-05 19:31:32 -080069 "-w", "dupbuild=err",
Steven Moreland10ea6212022-10-14 20:42:40 +000070 "-w", "missingdepfile=err",
71 "-w", "missingoutfile=err")
Dan Willemsen1e704462016-08-21 15:17:17 -070072
Dan Willemsen269a8c72017-05-03 17:15:47 -070073 cmd := Command(ctx, config, "ninja", executable, args...)
Jingwen Chen9d1cb492020-11-17 06:52:28 -050074
75 // Set up the nsjail sandbox Ninja runs in.
Dan Willemsen63663c62019-01-02 12:24:44 -080076 cmd.Sandbox = ninjaSandbox
Dan Willemsene0879fc2017-08-04 15:06:27 -070077 if config.HasKatiSuffix() {
Jingwen Chen9d1cb492020-11-17 06:52:28 -050078 // Reads and executes a shell script from Kati that sets/unsets the
79 // environment Ninja runs in.
Dan Willemsene0879fc2017-08-04 15:06:27 -070080 cmd.Environment.AppendFromKati(config.KatiEnvFile())
81 }
Dan Willemsen1e704462016-08-21 15:17:17 -070082
83 // Allow both NINJA_ARGS and NINJA_EXTRA_ARGS, since both have been
84 // used in the past to specify extra ninja arguments.
Dan Willemsen269a8c72017-05-03 17:15:47 -070085 if extra, ok := cmd.Environment.Get("NINJA_ARGS"); ok {
86 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -070087 }
Dan Willemsen269a8c72017-05-03 17:15:47 -070088 if extra, ok := cmd.Environment.Get("NINJA_EXTRA_ARGS"); ok {
89 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -070090 }
91
Jeff Gaston809cc6f2017-05-25 15:44:36 -070092 ninjaHeartbeatDuration := time.Minute * 5
Jingwen Chen9d1cb492020-11-17 06:52:28 -050093 // Get the ninja heartbeat interval from the environment before it's filtered away later.
Jeff Gaston809cc6f2017-05-25 15:44:36 -070094 if overrideText, ok := cmd.Environment.Get("NINJA_HEARTBEAT_INTERVAL"); ok {
95 // For example, "1m"
96 overrideDuration, err := time.ParseDuration(overrideText)
97 if err == nil && overrideDuration.Seconds() > 0 {
98 ninjaHeartbeatDuration = overrideDuration
99 }
100 }
Dan Willemsene3336352020-01-02 19:10:38 -0800101
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500102 // Filter the environment, as ninja does not rebuild files when environment
103 // variables change.
Dan Willemsene3336352020-01-02 19:10:38 -0800104 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500105 // Anything listed here must not change the output of rules/actions when the
106 // value changes, otherwise incremental builds may be unsafe. Vars
107 // explicitly set to stable values elsewhere in soong_ui are fine.
Dan Willemsene3336352020-01-02 19:10:38 -0800108 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500109 // For the majority of cases, either Soong or the makefiles should be
110 // replicating any necessary environment variables in the command line of
111 // each action that needs it.
Dan Willemsen260db532020-01-02 20:12:09 -0800112 if cmd.Environment.IsEnvTrue("ALLOW_NINJA_ENV") {
113 ctx.Println("Allowing all environment variables during ninja; incremental builds may be unsafe.")
114 } else {
Dan Willemsene3336352020-01-02 19:10:38 -0800115 cmd.Environment.Allow(append([]string{
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500116 // Set the path to a symbolizer (e.g. llvm-symbolizer) so ASAN-based
117 // tools can symbolize crashes.
Dan Willemsene3336352020-01-02 19:10:38 -0800118 "ASAN_SYMBOLIZER_PATH",
119 "HOME",
120 "JAVA_HOME",
121 "LANG",
122 "LC_MESSAGES",
123 "OUT_DIR",
124 "PATH",
125 "PWD",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500126 // https://docs.python.org/3/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE
Dan Willemsene3336352020-01-02 19:10:38 -0800127 "PYTHONDONTWRITEBYTECODE",
128 "TMPDIR",
129 "USER",
130
131 // TODO: remove these carefully
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500132 // Options for the address sanitizer.
Dan Willemsen7da04292020-01-04 13:58:54 -0800133 "ASAN_OPTIONS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500134 // The list of Android app modules to be built in an unbundled manner.
Dan Willemsene3336352020-01-02 19:10:38 -0800135 "TARGET_BUILD_APPS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500136 // The variant of the product being built. e.g. eng, userdebug, debug.
Dan Willemsene3336352020-01-02 19:10:38 -0800137 "TARGET_BUILD_VARIANT",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500138 // The product name of the product being built, e.g. aosp_arm, aosp_flame.
Dan Willemsene3336352020-01-02 19:10:38 -0800139 "TARGET_PRODUCT",
Dan Willemsen5cacfe12020-01-06 12:25:40 -0800140 // b/147197813 - used by art-check-debug-apex-gen
141 "EMMA_INSTRUMENT_FRAMEWORK",
Dan Willemsene3336352020-01-02 19:10:38 -0800142
Dan Willemsene3336352020-01-02 19:10:38 -0800143 // RBE client
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400144 "RBE_compare",
andusyu240660d2022-01-20 14:00:58 -0500145 "RBE_num_local_reruns",
146 "RBE_num_remote_reruns",
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400147 "RBE_exec_root",
148 "RBE_exec_strategy",
149 "RBE_invocation_id",
150 "RBE_log_dir",
Kousik Kumarc3a22d82021-03-17 14:19:27 -0400151 "RBE_num_retries_if_mismatched",
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400152 "RBE_platform",
153 "RBE_remote_accept_cache",
154 "RBE_remote_update_cache",
155 "RBE_server_address",
156 // TODO: remove old FLAG_ variables.
Kousik Kumarade12e72020-01-09 08:52:59 -0800157 "FLAG_compare",
Dan Willemsene3336352020-01-02 19:10:38 -0800158 "FLAG_exec_root",
159 "FLAG_exec_strategy",
160 "FLAG_invocation_id",
161 "FLAG_log_dir",
162 "FLAG_platform",
Kousik Kumar0f095e12020-01-28 10:48:46 -0800163 "FLAG_remote_accept_cache",
164 "FLAG_remote_update_cache",
Dan Willemsene3336352020-01-02 19:10:38 -0800165 "FLAG_server_address",
166
167 // ccache settings
168 "CCACHE_COMPILERCHECK",
169 "CCACHE_SLOPPINESS",
170 "CCACHE_BASEDIR",
171 "CCACHE_CPP2",
John Eckerdal974b0e82020-02-04 15:59:37 +0100172 "CCACHE_DIR",
Yi Kong6adf2582022-04-17 15:01:06 +0800173
174 // LLVM compiler wrapper options
175 "TOOLCHAIN_RUSAGE_OUTPUT",
Dan Willemsene3336352020-01-02 19:10:38 -0800176 }, config.BuildBrokenNinjaUsesEnvVars()...)...)
177 }
178
179 cmd.Environment.Set("DIST_DIR", config.DistDir())
180 cmd.Environment.Set("SHELL", "/bin/bash")
181
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500182 // Print the environment variables that Ninja is operating in.
Dan Willemsene3336352020-01-02 19:10:38 -0800183 ctx.Verboseln("Ninja environment: ")
184 envVars := cmd.Environment.Environ()
185 sort.Strings(envVars)
186 for _, envVar := range envVars {
187 ctx.Verbosef(" %s", envVar)
188 }
189
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500190 // Poll the Ninja log for updates regularly based on the heartbeat
191 // frequency. If it isn't updated enough, then we want to surface the
192 // possibility that Ninja is stuck, to the user.
Jeff Gastona6697e82017-06-13 12:51:50 -0700193 done := make(chan struct{})
194 defer close(done)
195 ticker := time.NewTicker(ninjaHeartbeatDuration)
196 defer ticker.Stop()
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500197 ninjaChecker := &ninjaStucknessChecker{
198 logPath: filepath.Join(config.OutDir(), ".ninja_log"),
199 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700200 go func() {
Jeff Gastona6697e82017-06-13 12:51:50 -0700201 for {
202 select {
203 case <-ticker.C:
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500204 ninjaChecker.check(ctx, config)
Jeff Gastona6697e82017-06-13 12:51:50 -0700205 case <-done:
206 return
207 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700208 }
209 }()
210
Dan Willemsen7f30c072019-01-02 12:50:49 -0800211 ctx.Status.Status("Starting ninja...")
Colin Cross7b97ecd2019-06-19 13:17:59 -0700212 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700213}
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700214
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500215// A simple struct for checking if Ninja gets stuck, using timestamps.
216type ninjaStucknessChecker struct {
217 logPath string
218 prevModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700219}
220
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500221// Check that a file has been modified since the last time it was checked. If
222// the mod time hasn't changed, then assume that Ninja got stuck, and print
223// diagnostics for debugging.
224func (c *ninjaStucknessChecker) check(ctx Context, config Config) {
225 info, err := os.Stat(c.logPath)
226 var newModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700227 if err == nil {
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500228 newModTime = info.ModTime()
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700229 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500230 if newModTime == c.prevModTime {
231 // The Ninja file hasn't been modified since the last time it was
232 // checked, so Ninja could be stuck. Output some diagnostics.
233 ctx.Verbosef("ninja may be stuck; last update to %v was %v. dumping process tree...", c.logPath, newModTime)
234
235 // The "pstree" command doesn't exist on Mac, but "pstree" on Linux
236 // gives more convenient output than "ps" So, we try pstree first, and
237 // ps second
238 commandText := fmt.Sprintf("pstree -pal %v || ps -ef", os.Getpid())
239
240 cmd := Command(ctx, config, "dump process tree", "bash", "-c", commandText)
241 output := cmd.CombinedOutputOrFatal()
242 ctx.Verbose(string(output))
243
244 ctx.Verbosef("done\n")
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700245 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500246 c.prevModTime = newModTime
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700247}