blob: def0783a2f28b4fee729c11ee7d282b9f29609f1 [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
LaMont Jonesece626c2024-09-03 11:19:31 -070052 var executable string
53 var args []string
54 switch config.ninjaCommand {
55 case NINJA_N2:
Cole Faust4e58bba2024-08-22 14:27:03 -070056 executable = config.N2Bin()
Cole Faustbee030d2024-01-03 13:45:48 -080057 args = []string{
58 "-d", "trace",
59 // TODO: implement these features, or remove them.
60 //"-d", "keepdepfile",
61 //"-d", "keeprsp",
62 //"-d", "stats",
63 "--frontend-file", fifo,
64 }
LaMont Jonesece626c2024-09-03 11:19:31 -070065 case NINJA_SISO:
66 executable = config.SisoBin()
67 args = []string{
68 "ninja",
69 "--log_dir", config.SoongOutDir(),
70 // TODO: implement these features, or remove them.
71 //"-d", "trace",
72 //"-d", "keepdepfile",
73 //"-d", "keeprsp",
74 //"-d", "stats",
75 //"--frontend-file", fifo,
76 }
77 default:
78 // NINJA_NINJA is the default.
79 executable = config.NinjaBin()
80 args = []string{
81 "-d", "keepdepfile",
82 "-d", "keeprsp",
83 "-d", "stats",
84 "--frontend_file", fifo,
85 "-o", "usesphonyoutputs=yes",
86 "-w", "dupbuild=err",
87 "-w", "missingdepfile=err",
88 }
Cole Faustbee030d2024-01-03 13:45:48 -080089 }
Dan Willemsen1e704462016-08-21 15:17:17 -070090 args = append(args, config.NinjaArgs()...)
91
92 var parallel int
Colin Cross9016b912019-11-11 14:57:42 -080093 if config.UseRemoteBuild() {
Dan Willemsen1e704462016-08-21 15:17:17 -070094 parallel = config.RemoteParallel()
95 } else {
96 parallel = config.Parallel()
97 }
98 args = append(args, "-j", strconv.Itoa(parallel))
99 if config.keepGoing != 1 {
100 args = append(args, "-k", strconv.Itoa(config.keepGoing))
101 }
102
103 args = append(args, "-f", config.CombinedNinjaFile())
104
Spandan Das28a6f192024-07-01 21:00:25 +0000105 if !config.BuildBrokenMissingOutputs() {
106 // Missing outputs will be treated as errors.
107 // BUILD_BROKEN_MISSING_OUTPUTS can be used to bypass this check.
LaMont Jonesece626c2024-09-03 11:19:31 -0700108 if config.ninjaCommand != NINJA_N2 {
Cole Faustbee030d2024-01-03 13:45:48 -0800109 args = append(args,
110 "-w", "missingoutfile=err",
111 )
112 }
Spandan Das28a6f192024-07-01 21:00:25 +0000113 }
114
Dan Willemsen269a8c72017-05-03 17:15:47 -0700115 cmd := Command(ctx, config, "ninja", executable, args...)
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500116
117 // Set up the nsjail sandbox Ninja runs in.
Dan Willemsen63663c62019-01-02 12:24:44 -0800118 cmd.Sandbox = ninjaSandbox
Dan Willemsene0879fc2017-08-04 15:06:27 -0700119 if config.HasKatiSuffix() {
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500120 // Reads and executes a shell script from Kati that sets/unsets the
121 // environment Ninja runs in.
Dan Willemsene0879fc2017-08-04 15:06:27 -0700122 cmd.Environment.AppendFromKati(config.KatiEnvFile())
123 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700124
LaMont Jonesece626c2024-09-03 11:19:31 -0700125 // TODO(b/346806126): implement this for the other ninjaCommand values.
126 if config.ninjaCommand == NINJA_NINJA {
127 switch config.NinjaWeightListSource() {
128 case NINJA_LOG:
Cole Faustbee030d2024-01-03 13:45:48 -0800129 cmd.Args = append(cmd.Args, "-o", "usesninjalogasweightlist=yes")
LaMont Jonesece626c2024-09-03 11:19:31 -0700130 case EVENLY_DISTRIBUTED:
131 // pass empty weight list means ninja considers every tasks's weight as 1(default value).
Cole Faustbee030d2024-01-03 13:45:48 -0800132 cmd.Args = append(cmd.Args, "-o", "usesweightlist=/dev/null")
LaMont Jonesece626c2024-09-03 11:19:31 -0700133 case EXTERNAL_FILE:
134 fallthrough
135 case HINT_FROM_SOONG:
136 // The weight list is already copied/generated.
Cole Faustbee030d2024-01-03 13:45:48 -0800137 ninjaWeightListPath := filepath.Join(config.OutDir(), ninjaWeightListFileName)
138 cmd.Args = append(cmd.Args, "-o", "usesweightlist="+ninjaWeightListPath)
139 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900140 }
141
Dan Willemsen1e704462016-08-21 15:17:17 -0700142 // Allow both NINJA_ARGS and NINJA_EXTRA_ARGS, since both have been
143 // used in the past to specify extra ninja arguments.
Dan Willemsen269a8c72017-05-03 17:15:47 -0700144 if extra, ok := cmd.Environment.Get("NINJA_ARGS"); ok {
145 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -0700146 }
Dan Willemsen269a8c72017-05-03 17:15:47 -0700147 if extra, ok := cmd.Environment.Get("NINJA_EXTRA_ARGS"); ok {
148 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -0700149 }
150
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700151 ninjaHeartbeatDuration := time.Minute * 5
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500152 // Get the ninja heartbeat interval from the environment before it's filtered away later.
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700153 if overrideText, ok := cmd.Environment.Get("NINJA_HEARTBEAT_INTERVAL"); ok {
154 // For example, "1m"
155 overrideDuration, err := time.ParseDuration(overrideText)
156 if err == nil && overrideDuration.Seconds() > 0 {
157 ninjaHeartbeatDuration = overrideDuration
158 }
159 }
Dan Willemsene3336352020-01-02 19:10:38 -0800160
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500161 // Filter the environment, as ninja does not rebuild files when environment
162 // variables change.
Dan Willemsene3336352020-01-02 19:10:38 -0800163 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500164 // Anything listed here must not change the output of rules/actions when the
165 // value changes, otherwise incremental builds may be unsafe. Vars
166 // explicitly set to stable values elsewhere in soong_ui are fine.
Dan Willemsene3336352020-01-02 19:10:38 -0800167 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500168 // For the majority of cases, either Soong or the makefiles should be
169 // replicating any necessary environment variables in the command line of
170 // each action that needs it.
Dan Willemsen260db532020-01-02 20:12:09 -0800171 if cmd.Environment.IsEnvTrue("ALLOW_NINJA_ENV") {
172 ctx.Println("Allowing all environment variables during ninja; incremental builds may be unsafe.")
173 } else {
Dan Willemsene3336352020-01-02 19:10:38 -0800174 cmd.Environment.Allow(append([]string{
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500175 // Set the path to a symbolizer (e.g. llvm-symbolizer) so ASAN-based
176 // tools can symbolize crashes.
Dan Willemsene3336352020-01-02 19:10:38 -0800177 "ASAN_SYMBOLIZER_PATH",
178 "HOME",
179 "JAVA_HOME",
180 "LANG",
181 "LC_MESSAGES",
182 "OUT_DIR",
183 "PATH",
184 "PWD",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500185 // https://docs.python.org/3/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE
Dan Willemsene3336352020-01-02 19:10:38 -0800186 "PYTHONDONTWRITEBYTECODE",
187 "TMPDIR",
188 "USER",
189
190 // TODO: remove these carefully
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500191 // Options for the address sanitizer.
Dan Willemsen7da04292020-01-04 13:58:54 -0800192 "ASAN_OPTIONS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500193 // The list of Android app modules to be built in an unbundled manner.
Dan Willemsene3336352020-01-02 19:10:38 -0800194 "TARGET_BUILD_APPS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500195 // The variant of the product being built. e.g. eng, userdebug, debug.
Dan Willemsene3336352020-01-02 19:10:38 -0800196 "TARGET_BUILD_VARIANT",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500197 // The product name of the product being built, e.g. aosp_arm, aosp_flame.
Dan Willemsene3336352020-01-02 19:10:38 -0800198 "TARGET_PRODUCT",
Dan Willemsen5cacfe12020-01-06 12:25:40 -0800199 // b/147197813 - used by art-check-debug-apex-gen
200 "EMMA_INSTRUMENT_FRAMEWORK",
Dan Willemsene3336352020-01-02 19:10:38 -0800201
Dan Willemsene3336352020-01-02 19:10:38 -0800202 // RBE client
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400203 "RBE_compare",
andusyu240660d2022-01-20 14:00:58 -0500204 "RBE_num_local_reruns",
205 "RBE_num_remote_reruns",
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400206 "RBE_exec_root",
207 "RBE_exec_strategy",
208 "RBE_invocation_id",
209 "RBE_log_dir",
Kousik Kumarc3a22d82021-03-17 14:19:27 -0400210 "RBE_num_retries_if_mismatched",
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400211 "RBE_platform",
212 "RBE_remote_accept_cache",
213 "RBE_remote_update_cache",
214 "RBE_server_address",
215 // TODO: remove old FLAG_ variables.
Kousik Kumarade12e72020-01-09 08:52:59 -0800216 "FLAG_compare",
Dan Willemsene3336352020-01-02 19:10:38 -0800217 "FLAG_exec_root",
218 "FLAG_exec_strategy",
219 "FLAG_invocation_id",
220 "FLAG_log_dir",
221 "FLAG_platform",
Kousik Kumar0f095e12020-01-28 10:48:46 -0800222 "FLAG_remote_accept_cache",
223 "FLAG_remote_update_cache",
Dan Willemsene3336352020-01-02 19:10:38 -0800224 "FLAG_server_address",
225
226 // ccache settings
227 "CCACHE_COMPILERCHECK",
228 "CCACHE_SLOPPINESS",
229 "CCACHE_BASEDIR",
230 "CCACHE_CPP2",
John Eckerdal974b0e82020-02-04 15:59:37 +0100231 "CCACHE_DIR",
Yi Kong6adf2582022-04-17 15:01:06 +0800232
233 // LLVM compiler wrapper options
234 "TOOLCHAIN_RUSAGE_OUTPUT",
Cole Faustded79602023-09-05 17:48:11 -0700235
236 // We don't want this build broken flag to cause reanalysis, so allow it through to the
237 // actions.
238 "BUILD_BROKEN_INCORRECT_PARTITION_IMAGES",
LaMont Jonesece626c2024-09-03 11:19:31 -0700239 // Do not do reanalysis just because we changed ninja commands.
240 "SOONG_NINJA",
Cole Faustbee030d2024-01-03 13:45:48 -0800241 "SOONG_USE_N2",
242 "RUST_BACKTRACE",
LaMont Jonesb2ab5272024-08-14 10:08:50 -0700243 "RUST_LOG",
Dan Willemsene3336352020-01-02 19:10:38 -0800244 }, config.BuildBrokenNinjaUsesEnvVars()...)...)
245 }
246
247 cmd.Environment.Set("DIST_DIR", config.DistDir())
248 cmd.Environment.Set("SHELL", "/bin/bash")
LaMont Jonesece626c2024-09-03 11:19:31 -0700249 switch config.ninjaCommand {
250 case NINJA_N2:
Cole Faustbee030d2024-01-03 13:45:48 -0800251 cmd.Environment.Set("RUST_BACKTRACE", "1")
LaMont Jonesece626c2024-09-03 11:19:31 -0700252 default:
253 // Only set RUST_BACKTRACE for n2.
Cole Faustbee030d2024-01-03 13:45:48 -0800254 }
Dan Willemsene3336352020-01-02 19:10:38 -0800255
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500256 // Print the environment variables that Ninja is operating in.
Dan Willemsene3336352020-01-02 19:10:38 -0800257 ctx.Verboseln("Ninja environment: ")
258 envVars := cmd.Environment.Environ()
259 sort.Strings(envVars)
260 for _, envVar := range envVars {
261 ctx.Verbosef(" %s", envVar)
262 }
263
Spandan Das2db59da2023-02-16 18:31:43 +0000264 // Write the env vars available during ninja execution to a file
265 ninjaEnvVars := cmd.Environment.AsMap()
266 data, err := shared.EnvFileContents(ninjaEnvVars)
267 if err != nil {
268 ctx.Panicf("Could not parse environment variables for ninja run %s", err)
269 }
270 // Write the file in every single run. This is fine because
271 // 1. It is not a dep of Soong analysis, so will not retrigger Soong analysis.
272 // 2. Is is fairly lightweight (~1Kb)
273 ninjaEnvVarsFile := shared.JoinPath(config.SoongOutDir(), ninjaEnvFileName)
274 err = os.WriteFile(ninjaEnvVarsFile, data, 0666)
275 if err != nil {
276 ctx.Panicf("Could not write ninja environment file %s", err)
277 }
278
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500279 // Poll the Ninja log for updates regularly based on the heartbeat
280 // frequency. If it isn't updated enough, then we want to surface the
281 // possibility that Ninja is stuck, to the user.
Jeff Gastona6697e82017-06-13 12:51:50 -0700282 done := make(chan struct{})
283 defer close(done)
284 ticker := time.NewTicker(ninjaHeartbeatDuration)
285 defer ticker.Stop()
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500286 ninjaChecker := &ninjaStucknessChecker{
Jeongik Cha96d62272023-03-17 01:53:11 +0900287 logPath: filepath.Join(config.OutDir(), ninjaLogFileName),
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500288 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700289 go func() {
Jeff Gastona6697e82017-06-13 12:51:50 -0700290 for {
291 select {
292 case <-ticker.C:
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500293 ninjaChecker.check(ctx, config)
Jeff Gastona6697e82017-06-13 12:51:50 -0700294 case <-done:
295 return
296 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700297 }
298 }()
299
Dan Willemsen7f30c072019-01-02 12:50:49 -0800300 ctx.Status.Status("Starting ninja...")
Colin Cross7b97ecd2019-06-19 13:17:59 -0700301 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700302}
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700303
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500304// A simple struct for checking if Ninja gets stuck, using timestamps.
305type ninjaStucknessChecker struct {
306 logPath string
307 prevModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700308}
309
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500310// Check that a file has been modified since the last time it was checked. If
311// the mod time hasn't changed, then assume that Ninja got stuck, and print
312// diagnostics for debugging.
313func (c *ninjaStucknessChecker) check(ctx Context, config Config) {
314 info, err := os.Stat(c.logPath)
315 var newModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700316 if err == nil {
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500317 newModTime = info.ModTime()
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700318 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500319 if newModTime == c.prevModTime {
320 // The Ninja file hasn't been modified since the last time it was
321 // checked, so Ninja could be stuck. Output some diagnostics.
322 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 -0800323 ctx.Printf("ninja may be stuck, check %v for list of running processes.",
324 filepath.Join(config.LogsDir(), config.logsPrefix+"soong.log"))
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500325
326 // The "pstree" command doesn't exist on Mac, but "pstree" on Linux
327 // gives more convenient output than "ps" So, we try pstree first, and
328 // ps second
Colin Crossa9aa35c2024-01-05 14:03:27 -0800329 commandText := fmt.Sprintf("pstree -palT %v || ps -ef", os.Getpid())
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500330
331 cmd := Command(ctx, config, "dump process tree", "bash", "-c", commandText)
332 output := cmd.CombinedOutputOrFatal()
333 ctx.Verbose(string(output))
334
335 ctx.Verbosef("done\n")
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700336 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500337 c.prevModTime = newModTime
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700338}