blob: ae27330a96e8b81702722e624583f8675215aa6e [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
Dan Willemsenf173d592017-04-27 14:28:00 -070052 executable := config.PrebuiltBuildTool("ninja")
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 }
59
60 args = append(args, config.NinjaArgs()...)
61
62 var parallel int
Colin Cross9016b912019-11-11 14:57:42 -080063 if config.UseRemoteBuild() {
Dan Willemsen1e704462016-08-21 15:17:17 -070064 parallel = config.RemoteParallel()
65 } else {
66 parallel = config.Parallel()
67 }
68 args = append(args, "-j", strconv.Itoa(parallel))
69 if config.keepGoing != 1 {
70 args = append(args, "-k", strconv.Itoa(config.keepGoing))
71 }
72
73 args = append(args, "-f", config.CombinedNinjaFile())
74
Dan Willemsenf7939332019-01-05 19:31:32 -080075 args = append(args,
Dan Willemsen6587bed2020-04-18 20:25:59 -070076 "-o", "usesphonyoutputs=yes",
Dan Willemsenf7939332019-01-05 19:31:32 -080077 "-w", "dupbuild=err",
Steven Moreland28d35a12022-10-18 00:13:59 +000078 "-w", "missingdepfile=err")
Dan Willemsen1e704462016-08-21 15:17:17 -070079
Spandan Das28a6f192024-07-01 21:00:25 +000080 if !config.BuildBrokenMissingOutputs() {
81 // Missing outputs will be treated as errors.
82 // BUILD_BROKEN_MISSING_OUTPUTS can be used to bypass this check.
83 args = append(args,
84 "-w", "missingoutfile=err",
85 )
86 }
87
Dan Willemsen269a8c72017-05-03 17:15:47 -070088 cmd := Command(ctx, config, "ninja", executable, args...)
Jingwen Chen9d1cb492020-11-17 06:52:28 -050089
90 // Set up the nsjail sandbox Ninja runs in.
Dan Willemsen63663c62019-01-02 12:24:44 -080091 cmd.Sandbox = ninjaSandbox
Dan Willemsene0879fc2017-08-04 15:06:27 -070092 if config.HasKatiSuffix() {
Jingwen Chen9d1cb492020-11-17 06:52:28 -050093 // Reads and executes a shell script from Kati that sets/unsets the
94 // environment Ninja runs in.
Dan Willemsene0879fc2017-08-04 15:06:27 -070095 cmd.Environment.AppendFromKati(config.KatiEnvFile())
96 }
Dan Willemsen1e704462016-08-21 15:17:17 -070097
Jeongik Cha0cf44d52023-03-15 00:10:45 +090098 switch config.NinjaWeightListSource() {
99 case NINJA_LOG:
Jeongik Chad5534712023-05-20 00:49:39 +0900100 cmd.Args = append(cmd.Args, "-o", "usesninjalogasweightlist=yes")
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900101 case EVENLY_DISTRIBUTED:
102 // pass empty weight list means ninja considers every tasks's weight as 1(default value).
103 cmd.Args = append(cmd.Args, "-o", "usesweightlist=/dev/null")
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900104 case EXTERNAL_FILE:
Jeongik Chae114e602023-03-19 00:12:39 +0900105 fallthrough
106 case HINT_FROM_SOONG:
107 // The weight list is already copied/generated.
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900108 ninjaWeightListPath := filepath.Join(config.OutDir(), ninjaWeightListFileName)
109 cmd.Args = append(cmd.Args, "-o", "usesweightlist="+ninjaWeightListPath)
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900110 }
111
Dan Willemsen1e704462016-08-21 15:17:17 -0700112 // Allow both NINJA_ARGS and NINJA_EXTRA_ARGS, since both have been
113 // used in the past to specify extra ninja arguments.
Dan Willemsen269a8c72017-05-03 17:15:47 -0700114 if extra, ok := cmd.Environment.Get("NINJA_ARGS"); ok {
115 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -0700116 }
Dan Willemsen269a8c72017-05-03 17:15:47 -0700117 if extra, ok := cmd.Environment.Get("NINJA_EXTRA_ARGS"); ok {
118 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -0700119 }
120
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700121 ninjaHeartbeatDuration := time.Minute * 5
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500122 // Get the ninja heartbeat interval from the environment before it's filtered away later.
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700123 if overrideText, ok := cmd.Environment.Get("NINJA_HEARTBEAT_INTERVAL"); ok {
124 // For example, "1m"
125 overrideDuration, err := time.ParseDuration(overrideText)
126 if err == nil && overrideDuration.Seconds() > 0 {
127 ninjaHeartbeatDuration = overrideDuration
128 }
129 }
Dan Willemsene3336352020-01-02 19:10:38 -0800130
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500131 // Filter the environment, as ninja does not rebuild files when environment
132 // variables change.
Dan Willemsene3336352020-01-02 19:10:38 -0800133 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500134 // Anything listed here must not change the output of rules/actions when the
135 // value changes, otherwise incremental builds may be unsafe. Vars
136 // explicitly set to stable values elsewhere in soong_ui are fine.
Dan Willemsene3336352020-01-02 19:10:38 -0800137 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500138 // For the majority of cases, either Soong or the makefiles should be
139 // replicating any necessary environment variables in the command line of
140 // each action that needs it.
Dan Willemsen260db532020-01-02 20:12:09 -0800141 if cmd.Environment.IsEnvTrue("ALLOW_NINJA_ENV") {
142 ctx.Println("Allowing all environment variables during ninja; incremental builds may be unsafe.")
143 } else {
Dan Willemsene3336352020-01-02 19:10:38 -0800144 cmd.Environment.Allow(append([]string{
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500145 // Set the path to a symbolizer (e.g. llvm-symbolizer) so ASAN-based
146 // tools can symbolize crashes.
Dan Willemsene3336352020-01-02 19:10:38 -0800147 "ASAN_SYMBOLIZER_PATH",
148 "HOME",
149 "JAVA_HOME",
150 "LANG",
151 "LC_MESSAGES",
152 "OUT_DIR",
153 "PATH",
154 "PWD",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500155 // https://docs.python.org/3/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE
Dan Willemsene3336352020-01-02 19:10:38 -0800156 "PYTHONDONTWRITEBYTECODE",
157 "TMPDIR",
158 "USER",
159
160 // TODO: remove these carefully
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500161 // Options for the address sanitizer.
Dan Willemsen7da04292020-01-04 13:58:54 -0800162 "ASAN_OPTIONS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500163 // The list of Android app modules to be built in an unbundled manner.
Dan Willemsene3336352020-01-02 19:10:38 -0800164 "TARGET_BUILD_APPS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500165 // The variant of the product being built. e.g. eng, userdebug, debug.
Dan Willemsene3336352020-01-02 19:10:38 -0800166 "TARGET_BUILD_VARIANT",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500167 // The product name of the product being built, e.g. aosp_arm, aosp_flame.
Dan Willemsene3336352020-01-02 19:10:38 -0800168 "TARGET_PRODUCT",
Dan Willemsen5cacfe12020-01-06 12:25:40 -0800169 // b/147197813 - used by art-check-debug-apex-gen
170 "EMMA_INSTRUMENT_FRAMEWORK",
Dan Willemsene3336352020-01-02 19:10:38 -0800171
Dan Willemsene3336352020-01-02 19:10:38 -0800172 // RBE client
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400173 "RBE_compare",
andusyu240660d2022-01-20 14:00:58 -0500174 "RBE_num_local_reruns",
175 "RBE_num_remote_reruns",
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400176 "RBE_exec_root",
177 "RBE_exec_strategy",
178 "RBE_invocation_id",
179 "RBE_log_dir",
Kousik Kumarc3a22d82021-03-17 14:19:27 -0400180 "RBE_num_retries_if_mismatched",
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400181 "RBE_platform",
182 "RBE_remote_accept_cache",
183 "RBE_remote_update_cache",
184 "RBE_server_address",
185 // TODO: remove old FLAG_ variables.
Kousik Kumarade12e72020-01-09 08:52:59 -0800186 "FLAG_compare",
Dan Willemsene3336352020-01-02 19:10:38 -0800187 "FLAG_exec_root",
188 "FLAG_exec_strategy",
189 "FLAG_invocation_id",
190 "FLAG_log_dir",
191 "FLAG_platform",
Kousik Kumar0f095e12020-01-28 10:48:46 -0800192 "FLAG_remote_accept_cache",
193 "FLAG_remote_update_cache",
Dan Willemsene3336352020-01-02 19:10:38 -0800194 "FLAG_server_address",
195
196 // ccache settings
197 "CCACHE_COMPILERCHECK",
198 "CCACHE_SLOPPINESS",
199 "CCACHE_BASEDIR",
200 "CCACHE_CPP2",
John Eckerdal974b0e82020-02-04 15:59:37 +0100201 "CCACHE_DIR",
Yi Kong6adf2582022-04-17 15:01:06 +0800202
203 // LLVM compiler wrapper options
204 "TOOLCHAIN_RUSAGE_OUTPUT",
Cole Faustded79602023-09-05 17:48:11 -0700205
206 // We don't want this build broken flag to cause reanalysis, so allow it through to the
207 // actions.
208 "BUILD_BROKEN_INCORRECT_PARTITION_IMAGES",
Dan Willemsene3336352020-01-02 19:10:38 -0800209 }, config.BuildBrokenNinjaUsesEnvVars()...)...)
210 }
211
212 cmd.Environment.Set("DIST_DIR", config.DistDir())
213 cmd.Environment.Set("SHELL", "/bin/bash")
214
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500215 // Print the environment variables that Ninja is operating in.
Dan Willemsene3336352020-01-02 19:10:38 -0800216 ctx.Verboseln("Ninja environment: ")
217 envVars := cmd.Environment.Environ()
218 sort.Strings(envVars)
219 for _, envVar := range envVars {
220 ctx.Verbosef(" %s", envVar)
221 }
222
Spandan Das2db59da2023-02-16 18:31:43 +0000223 // Write the env vars available during ninja execution to a file
224 ninjaEnvVars := cmd.Environment.AsMap()
225 data, err := shared.EnvFileContents(ninjaEnvVars)
226 if err != nil {
227 ctx.Panicf("Could not parse environment variables for ninja run %s", err)
228 }
229 // Write the file in every single run. This is fine because
230 // 1. It is not a dep of Soong analysis, so will not retrigger Soong analysis.
231 // 2. Is is fairly lightweight (~1Kb)
232 ninjaEnvVarsFile := shared.JoinPath(config.SoongOutDir(), ninjaEnvFileName)
233 err = os.WriteFile(ninjaEnvVarsFile, data, 0666)
234 if err != nil {
235 ctx.Panicf("Could not write ninja environment file %s", err)
236 }
237
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500238 // Poll the Ninja log for updates regularly based on the heartbeat
239 // frequency. If it isn't updated enough, then we want to surface the
240 // possibility that Ninja is stuck, to the user.
Jeff Gastona6697e82017-06-13 12:51:50 -0700241 done := make(chan struct{})
242 defer close(done)
243 ticker := time.NewTicker(ninjaHeartbeatDuration)
244 defer ticker.Stop()
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500245 ninjaChecker := &ninjaStucknessChecker{
Jeongik Cha96d62272023-03-17 01:53:11 +0900246 logPath: filepath.Join(config.OutDir(), ninjaLogFileName),
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500247 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700248 go func() {
Jeff Gastona6697e82017-06-13 12:51:50 -0700249 for {
250 select {
251 case <-ticker.C:
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500252 ninjaChecker.check(ctx, config)
Jeff Gastona6697e82017-06-13 12:51:50 -0700253 case <-done:
254 return
255 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700256 }
257 }()
258
Dan Willemsen7f30c072019-01-02 12:50:49 -0800259 ctx.Status.Status("Starting ninja...")
Colin Cross7b97ecd2019-06-19 13:17:59 -0700260 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700261}
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700262
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500263// A simple struct for checking if Ninja gets stuck, using timestamps.
264type ninjaStucknessChecker struct {
265 logPath string
266 prevModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700267}
268
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500269// Check that a file has been modified since the last time it was checked. If
270// the mod time hasn't changed, then assume that Ninja got stuck, and print
271// diagnostics for debugging.
272func (c *ninjaStucknessChecker) check(ctx Context, config Config) {
273 info, err := os.Stat(c.logPath)
274 var newModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700275 if err == nil {
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500276 newModTime = info.ModTime()
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700277 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500278 if newModTime == c.prevModTime {
279 // The Ninja file hasn't been modified since the last time it was
280 // checked, so Ninja could be stuck. Output some diagnostics.
281 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 -0800282 ctx.Printf("ninja may be stuck, check %v for list of running processes.",
283 filepath.Join(config.LogsDir(), config.logsPrefix+"soong.log"))
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500284
285 // The "pstree" command doesn't exist on Mac, but "pstree" on Linux
286 // gives more convenient output than "ps" So, we try pstree first, and
287 // ps second
Colin Crossa9aa35c2024-01-05 14:03:27 -0800288 commandText := fmt.Sprintf("pstree -palT %v || ps -ef", os.Getpid())
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500289
290 cmd := Command(ctx, config, "dump process tree", "bash", "-c", commandText)
291 output := cmd.CombinedOutputOrFatal()
292 ctx.Verbose(string(output))
293
294 ctx.Verbosef("done\n")
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700295 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500296 c.prevModTime = newModTime
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700297}