blob: 8ca62d3f13dc40697b21236c7e097c0f8b143943 [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
Spandan Das2db59da2023-02-16 18:31:43 +000026 "android/soong/shared"
Nan Zhang17f27672018-12-12 16:01:49 -080027 "android/soong/ui/metrics"
Dan Willemsenb82471a2018-05-17 16:37:09 -070028 "android/soong/ui/status"
Dan Willemsen1e704462016-08-21 15:17:17 -070029)
30
Spandan Das2db59da2023-02-16 18:31:43 +000031const (
32 // File containing the environment state when ninja is executed
Jeongik Cha518f3ea2023-03-19 00:12:39 +090033 ninjaEnvFileName = "ninja.environment"
34 ninjaLogFileName = ".ninja_log"
35 ninjaWeightListFileName = ".ninja_weight_list"
Spandan Das2db59da2023-02-16 18:31:43 +000036)
37
Jingwen Chen9d1cb492020-11-17 06:52:28 -050038// Constructs and runs the Ninja command line with a restricted set of
39// environment variables. It's important to restrict the environment Ninja runs
40// for hermeticity reasons, and to avoid spurious rebuilds.
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010041func runNinjaForBuild(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -080042 ctx.BeginTrace(metrics.PrimaryNinja, "ninja")
Dan Willemsend9f6fa22016-08-21 15:17:17 -070043 defer ctx.EndTrace()
44
Jingwen Chen9d1cb492020-11-17 06:52:28 -050045 // Sets up the FIFO status updater that reads the Ninja protobuf output, and
46 // translates it to the soong_ui status output, displaying real-time
47 // progress of the build.
Dan Willemsenb82471a2018-05-17 16:37:09 -070048 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -070049 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
50 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -070051
Taylor Santiago3c16e612024-05-30 14:41:31 -070052 executable := config.NinjaBin()
Dan Willemsen1e704462016-08-21 15:17:17 -070053 args := []string{
54 "-d", "keepdepfile",
Dan Willemsen6d3cad92020-03-12 10:30:35 -070055 "-d", "keeprsp",
Dan Willemsen08218222020-05-18 14:02:02 -070056 "-d", "stats",
Dan Willemsen02736672018-07-17 17:54:31 -070057 "--frontend_file", fifo,
Dan Willemsen1e704462016-08-21 15:17:17 -070058 }
Cole Faustbee030d2024-01-03 13:45:48 -080059 if config.useN2 {
60 executable = config.PrebuiltBuildTool("n2")
61 args = []string{
62 "-d", "trace",
63 // TODO: implement these features, or remove them.
64 //"-d", "keepdepfile",
65 //"-d", "keeprsp",
66 //"-d", "stats",
67 "--frontend-file", fifo,
68 }
69 }
Dan Willemsen1e704462016-08-21 15:17:17 -070070
71 args = append(args, config.NinjaArgs()...)
72
73 var parallel int
Colin Cross9016b912019-11-11 14:57:42 -080074 if config.UseRemoteBuild() {
Dan Willemsen1e704462016-08-21 15:17:17 -070075 parallel = config.RemoteParallel()
76 } else {
77 parallel = config.Parallel()
78 }
79 args = append(args, "-j", strconv.Itoa(parallel))
80 if config.keepGoing != 1 {
81 args = append(args, "-k", strconv.Itoa(config.keepGoing))
82 }
83
84 args = append(args, "-f", config.CombinedNinjaFile())
85
Cole Faustbee030d2024-01-03 13:45:48 -080086 if !config.useN2 {
87 args = append(args,
88 "-o", "usesphonyoutputs=yes",
89 "-w", "dupbuild=err",
90 "-w", "missingdepfile=err")
91 }
Dan Willemsen1e704462016-08-21 15:17:17 -070092
Spandan Das28a6f192024-07-01 21:00:25 +000093 if !config.BuildBrokenMissingOutputs() {
94 // Missing outputs will be treated as errors.
95 // BUILD_BROKEN_MISSING_OUTPUTS can be used to bypass this check.
Cole Faustbee030d2024-01-03 13:45:48 -080096 if !config.useN2 {
97 args = append(args,
98 "-w", "missingoutfile=err",
99 )
100 }
Spandan Das28a6f192024-07-01 21:00:25 +0000101 }
102
Dan Willemsen269a8c72017-05-03 17:15:47 -0700103 cmd := Command(ctx, config, "ninja", executable, args...)
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500104
105 // Set up the nsjail sandbox Ninja runs in.
Dan Willemsen63663c62019-01-02 12:24:44 -0800106 cmd.Sandbox = ninjaSandbox
Dan Willemsene0879fc2017-08-04 15:06:27 -0700107 if config.HasKatiSuffix() {
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500108 // Reads and executes a shell script from Kati that sets/unsets the
109 // environment Ninja runs in.
Dan Willemsene0879fc2017-08-04 15:06:27 -0700110 cmd.Environment.AppendFromKati(config.KatiEnvFile())
111 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700112
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900113 switch config.NinjaWeightListSource() {
114 case NINJA_LOG:
Cole Faustbee030d2024-01-03 13:45:48 -0800115 if !config.useN2 {
116 cmd.Args = append(cmd.Args, "-o", "usesninjalogasweightlist=yes")
117 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900118 case EVENLY_DISTRIBUTED:
119 // pass empty weight list means ninja considers every tasks's weight as 1(default value).
Cole Faustbee030d2024-01-03 13:45:48 -0800120 if !config.useN2 {
121 cmd.Args = append(cmd.Args, "-o", "usesweightlist=/dev/null")
122 }
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900123 case EXTERNAL_FILE:
Jeongik Chae114e602023-03-19 00:12:39 +0900124 fallthrough
125 case HINT_FROM_SOONG:
126 // The weight list is already copied/generated.
Cole Faustbee030d2024-01-03 13:45:48 -0800127 if !config.useN2 {
128 ninjaWeightListPath := filepath.Join(config.OutDir(), ninjaWeightListFileName)
129 cmd.Args = append(cmd.Args, "-o", "usesweightlist="+ninjaWeightListPath)
130 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900131 }
132
Dan Willemsen1e704462016-08-21 15:17:17 -0700133 // Allow both NINJA_ARGS and NINJA_EXTRA_ARGS, since both have been
134 // used in the past to specify extra ninja arguments.
Dan Willemsen269a8c72017-05-03 17:15:47 -0700135 if extra, ok := cmd.Environment.Get("NINJA_ARGS"); ok {
136 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -0700137 }
Dan Willemsen269a8c72017-05-03 17:15:47 -0700138 if extra, ok := cmd.Environment.Get("NINJA_EXTRA_ARGS"); ok {
139 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -0700140 }
141
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700142 ninjaHeartbeatDuration := time.Minute * 5
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500143 // Get the ninja heartbeat interval from the environment before it's filtered away later.
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700144 if overrideText, ok := cmd.Environment.Get("NINJA_HEARTBEAT_INTERVAL"); ok {
145 // For example, "1m"
146 overrideDuration, err := time.ParseDuration(overrideText)
147 if err == nil && overrideDuration.Seconds() > 0 {
148 ninjaHeartbeatDuration = overrideDuration
149 }
150 }
Dan Willemsene3336352020-01-02 19:10:38 -0800151
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500152 // Filter the environment, as ninja does not rebuild files when environment
153 // variables change.
Dan Willemsene3336352020-01-02 19:10:38 -0800154 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500155 // Anything listed here must not change the output of rules/actions when the
156 // value changes, otherwise incremental builds may be unsafe. Vars
157 // explicitly set to stable values elsewhere in soong_ui are fine.
Dan Willemsene3336352020-01-02 19:10:38 -0800158 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500159 // For the majority of cases, either Soong or the makefiles should be
160 // replicating any necessary environment variables in the command line of
161 // each action that needs it.
Dan Willemsen260db532020-01-02 20:12:09 -0800162 if cmd.Environment.IsEnvTrue("ALLOW_NINJA_ENV") {
163 ctx.Println("Allowing all environment variables during ninja; incremental builds may be unsafe.")
164 } else {
Dan Willemsene3336352020-01-02 19:10:38 -0800165 cmd.Environment.Allow(append([]string{
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500166 // Set the path to a symbolizer (e.g. llvm-symbolizer) so ASAN-based
167 // tools can symbolize crashes.
Dan Willemsene3336352020-01-02 19:10:38 -0800168 "ASAN_SYMBOLIZER_PATH",
169 "HOME",
170 "JAVA_HOME",
171 "LANG",
172 "LC_MESSAGES",
173 "OUT_DIR",
174 "PATH",
175 "PWD",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500176 // https://docs.python.org/3/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE
Dan Willemsene3336352020-01-02 19:10:38 -0800177 "PYTHONDONTWRITEBYTECODE",
178 "TMPDIR",
179 "USER",
180
181 // TODO: remove these carefully
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500182 // Options for the address sanitizer.
Dan Willemsen7da04292020-01-04 13:58:54 -0800183 "ASAN_OPTIONS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500184 // The list of Android app modules to be built in an unbundled manner.
Dan Willemsene3336352020-01-02 19:10:38 -0800185 "TARGET_BUILD_APPS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500186 // The variant of the product being built. e.g. eng, userdebug, debug.
Dan Willemsene3336352020-01-02 19:10:38 -0800187 "TARGET_BUILD_VARIANT",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500188 // The product name of the product being built, e.g. aosp_arm, aosp_flame.
Dan Willemsene3336352020-01-02 19:10:38 -0800189 "TARGET_PRODUCT",
Dan Willemsen5cacfe12020-01-06 12:25:40 -0800190 // b/147197813 - used by art-check-debug-apex-gen
191 "EMMA_INSTRUMENT_FRAMEWORK",
Dan Willemsene3336352020-01-02 19:10:38 -0800192
Dan Willemsene3336352020-01-02 19:10:38 -0800193 // RBE client
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400194 "RBE_compare",
andusyu240660d2022-01-20 14:00:58 -0500195 "RBE_num_local_reruns",
196 "RBE_num_remote_reruns",
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400197 "RBE_exec_root",
198 "RBE_exec_strategy",
199 "RBE_invocation_id",
200 "RBE_log_dir",
Kousik Kumarc3a22d82021-03-17 14:19:27 -0400201 "RBE_num_retries_if_mismatched",
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400202 "RBE_platform",
203 "RBE_remote_accept_cache",
204 "RBE_remote_update_cache",
205 "RBE_server_address",
206 // TODO: remove old FLAG_ variables.
Kousik Kumarade12e72020-01-09 08:52:59 -0800207 "FLAG_compare",
Dan Willemsene3336352020-01-02 19:10:38 -0800208 "FLAG_exec_root",
209 "FLAG_exec_strategy",
210 "FLAG_invocation_id",
211 "FLAG_log_dir",
212 "FLAG_platform",
Kousik Kumar0f095e12020-01-28 10:48:46 -0800213 "FLAG_remote_accept_cache",
214 "FLAG_remote_update_cache",
Dan Willemsene3336352020-01-02 19:10:38 -0800215 "FLAG_server_address",
216
217 // ccache settings
218 "CCACHE_COMPILERCHECK",
219 "CCACHE_SLOPPINESS",
220 "CCACHE_BASEDIR",
221 "CCACHE_CPP2",
John Eckerdal974b0e82020-02-04 15:59:37 +0100222 "CCACHE_DIR",
Yi Kong6adf2582022-04-17 15:01:06 +0800223
224 // LLVM compiler wrapper options
225 "TOOLCHAIN_RUSAGE_OUTPUT",
Cole Faustded79602023-09-05 17:48:11 -0700226
227 // We don't want this build broken flag to cause reanalysis, so allow it through to the
228 // actions.
229 "BUILD_BROKEN_INCORRECT_PARTITION_IMAGES",
Cole Faustbee030d2024-01-03 13:45:48 -0800230 "SOONG_USE_N2",
231 "RUST_BACKTRACE",
LaMont Jonesb2ab5272024-08-14 10:08:50 -0700232 "RUST_LOG",
Dan Willemsene3336352020-01-02 19:10:38 -0800233 }, config.BuildBrokenNinjaUsesEnvVars()...)...)
234 }
235
236 cmd.Environment.Set("DIST_DIR", config.DistDir())
237 cmd.Environment.Set("SHELL", "/bin/bash")
Cole Faustbee030d2024-01-03 13:45:48 -0800238 if config.useN2 {
239 cmd.Environment.Set("RUST_BACKTRACE", "1")
240 }
Dan Willemsene3336352020-01-02 19:10:38 -0800241
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500242 // Print the environment variables that Ninja is operating in.
Dan Willemsene3336352020-01-02 19:10:38 -0800243 ctx.Verboseln("Ninja environment: ")
244 envVars := cmd.Environment.Environ()
245 sort.Strings(envVars)
246 for _, envVar := range envVars {
247 ctx.Verbosef(" %s", envVar)
248 }
249
Spandan Das2db59da2023-02-16 18:31:43 +0000250 // Write the env vars available during ninja execution to a file
251 ninjaEnvVars := cmd.Environment.AsMap()
252 data, err := shared.EnvFileContents(ninjaEnvVars)
253 if err != nil {
254 ctx.Panicf("Could not parse environment variables for ninja run %s", err)
255 }
256 // Write the file in every single run. This is fine because
257 // 1. It is not a dep of Soong analysis, so will not retrigger Soong analysis.
258 // 2. Is is fairly lightweight (~1Kb)
259 ninjaEnvVarsFile := shared.JoinPath(config.SoongOutDir(), ninjaEnvFileName)
260 err = os.WriteFile(ninjaEnvVarsFile, data, 0666)
261 if err != nil {
262 ctx.Panicf("Could not write ninja environment file %s", err)
263 }
264
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500265 // Poll the Ninja log for updates regularly based on the heartbeat
266 // frequency. If it isn't updated enough, then we want to surface the
267 // possibility that Ninja is stuck, to the user.
Jeff Gastona6697e82017-06-13 12:51:50 -0700268 done := make(chan struct{})
269 defer close(done)
270 ticker := time.NewTicker(ninjaHeartbeatDuration)
271 defer ticker.Stop()
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500272 ninjaChecker := &ninjaStucknessChecker{
Jeongik Cha96d62272023-03-17 01:53:11 +0900273 logPath: filepath.Join(config.OutDir(), ninjaLogFileName),
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500274 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700275 go func() {
Jeff Gastona6697e82017-06-13 12:51:50 -0700276 for {
277 select {
278 case <-ticker.C:
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500279 ninjaChecker.check(ctx, config)
Jeff Gastona6697e82017-06-13 12:51:50 -0700280 case <-done:
281 return
282 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700283 }
284 }()
285
Dan Willemsen7f30c072019-01-02 12:50:49 -0800286 ctx.Status.Status("Starting ninja...")
Colin Cross7b97ecd2019-06-19 13:17:59 -0700287 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700288}
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700289
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500290// A simple struct for checking if Ninja gets stuck, using timestamps.
291type ninjaStucknessChecker struct {
292 logPath string
293 prevModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700294}
295
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500296// Check that a file has been modified since the last time it was checked. If
297// the mod time hasn't changed, then assume that Ninja got stuck, and print
298// diagnostics for debugging.
299func (c *ninjaStucknessChecker) check(ctx Context, config Config) {
300 info, err := os.Stat(c.logPath)
301 var newModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700302 if err == nil {
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500303 newModTime = info.ModTime()
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700304 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500305 if newModTime == c.prevModTime {
306 // The Ninja file hasn't been modified since the last time it was
307 // checked, so Ninja could be stuck. Output some diagnostics.
308 ctx.Verbosef("ninja may be stuck; last update to %v was %v. dumping process tree...", c.logPath, newModTime)
Colin Crossa9aa35c2024-01-05 14:03:27 -0800309 ctx.Printf("ninja may be stuck, check %v for list of running processes.",
310 filepath.Join(config.LogsDir(), config.logsPrefix+"soong.log"))
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500311
312 // The "pstree" command doesn't exist on Mac, but "pstree" on Linux
313 // gives more convenient output than "ps" So, we try pstree first, and
314 // ps second
Colin Crossa9aa35c2024-01-05 14:03:27 -0800315 commandText := fmt.Sprintf("pstree -palT %v || ps -ef", os.Getpid())
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500316
317 cmd := Command(ctx, config, "dump process tree", "bash", "-c", commandText)
318 output := cmd.CombinedOutputOrFatal()
319 ctx.Verbose(string(output))
320
321 ctx.Verbosef("done\n")
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700322 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500323 c.prevModTime = newModTime
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700324}