blob: b0c9c07d900f10ebb9f589be1151541836726747 [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"
Joe Onoratod6a29992024-12-06 12:55:41 -080020 "os/exec"
Dan Willemsend9f6fa22016-08-21 15:17:17 -070021 "path/filepath"
Dan Willemsene3336352020-01-02 19:10:38 -080022 "sort"
Dan Willemsen1e704462016-08-21 15:17:17 -070023 "strconv"
24 "strings"
Dan Willemsend9f6fa22016-08-21 15:17:17 -070025 "time"
Dan Willemsenb82471a2018-05-17 16:37:09 -070026
Spandan Das2db59da2023-02-16 18:31:43 +000027 "android/soong/shared"
Nan Zhang17f27672018-12-12 16:01:49 -080028 "android/soong/ui/metrics"
Dan Willemsenb82471a2018-05-17 16:37:09 -070029 "android/soong/ui/status"
Dan Willemsen1e704462016-08-21 15:17:17 -070030)
31
Spandan Das2db59da2023-02-16 18:31:43 +000032const (
33 // File containing the environment state when ninja is executed
Jeongik Cha518f3ea2023-03-19 00:12:39 +090034 ninjaEnvFileName = "ninja.environment"
35 ninjaLogFileName = ".ninja_log"
36 ninjaWeightListFileName = ".ninja_weight_list"
Spandan Das2db59da2023-02-16 18:31:43 +000037)
38
Jingwen Chen9d1cb492020-11-17 06:52:28 -050039// Constructs and runs the Ninja command line with a restricted set of
40// environment variables. It's important to restrict the environment Ninja runs
41// for hermeticity reasons, and to avoid spurious rebuilds.
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010042func runNinjaForBuild(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -080043 ctx.BeginTrace(metrics.PrimaryNinja, "ninja")
Dan Willemsend9f6fa22016-08-21 15:17:17 -070044 defer ctx.EndTrace()
45
Jingwen Chen9d1cb492020-11-17 06:52:28 -050046 // Sets up the FIFO status updater that reads the Ninja protobuf output, and
47 // translates it to the soong_ui status output, displaying real-time
48 // progress of the build.
Dan Willemsenb82471a2018-05-17 16:37:09 -070049 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -070050 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
51 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -070052
LaMont Jonesece626c2024-09-03 11:19:31 -070053 var executable string
54 var args []string
55 switch config.ninjaCommand {
56 case NINJA_N2:
Cole Faust4e58bba2024-08-22 14:27:03 -070057 executable = config.N2Bin()
Cole Faustbee030d2024-01-03 13:45:48 -080058 args = []string{
59 "-d", "trace",
60 // TODO: implement these features, or remove them.
61 //"-d", "keepdepfile",
62 //"-d", "keeprsp",
63 //"-d", "stats",
64 "--frontend-file", fifo,
65 }
LaMont Jonesece626c2024-09-03 11:19:31 -070066 case NINJA_SISO:
67 executable = config.SisoBin()
68 args = []string{
69 "ninja",
70 "--log_dir", config.SoongOutDir(),
71 // TODO: implement these features, or remove them.
72 //"-d", "trace",
73 //"-d", "keepdepfile",
74 //"-d", "keeprsp",
75 //"-d", "stats",
76 //"--frontend-file", fifo,
77 }
78 default:
79 // NINJA_NINJA is the default.
80 executable = config.NinjaBin()
81 args = []string{
82 "-d", "keepdepfile",
83 "-d", "keeprsp",
84 "-d", "stats",
85 "--frontend_file", fifo,
86 "-o", "usesphonyoutputs=yes",
87 "-w", "dupbuild=err",
88 "-w", "missingdepfile=err",
89 }
Cole Faustbee030d2024-01-03 13:45:48 -080090 }
Dan Willemsen1e704462016-08-21 15:17:17 -070091 args = append(args, config.NinjaArgs()...)
92
93 var parallel int
Colin Cross9016b912019-11-11 14:57:42 -080094 if config.UseRemoteBuild() {
Dan Willemsen1e704462016-08-21 15:17:17 -070095 parallel = config.RemoteParallel()
96 } else {
97 parallel = config.Parallel()
98 }
99 args = append(args, "-j", strconv.Itoa(parallel))
100 if config.keepGoing != 1 {
101 args = append(args, "-k", strconv.Itoa(config.keepGoing))
102 }
103
104 args = append(args, "-f", config.CombinedNinjaFile())
105
Spandan Das28a6f192024-07-01 21:00:25 +0000106 if !config.BuildBrokenMissingOutputs() {
107 // Missing outputs will be treated as errors.
108 // BUILD_BROKEN_MISSING_OUTPUTS can be used to bypass this check.
LaMont Jonesece626c2024-09-03 11:19:31 -0700109 if config.ninjaCommand != NINJA_N2 {
Cole Faustbee030d2024-01-03 13:45:48 -0800110 args = append(args,
111 "-w", "missingoutfile=err",
112 )
113 }
Spandan Das28a6f192024-07-01 21:00:25 +0000114 }
115
Dan Willemsen269a8c72017-05-03 17:15:47 -0700116 cmd := Command(ctx, config, "ninja", executable, args...)
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500117
118 // Set up the nsjail sandbox Ninja runs in.
Dan Willemsen63663c62019-01-02 12:24:44 -0800119 cmd.Sandbox = ninjaSandbox
Dan Willemsene0879fc2017-08-04 15:06:27 -0700120 if config.HasKatiSuffix() {
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500121 // Reads and executes a shell script from Kati that sets/unsets the
122 // environment Ninja runs in.
Dan Willemsene0879fc2017-08-04 15:06:27 -0700123 cmd.Environment.AppendFromKati(config.KatiEnvFile())
124 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700125
LaMont Jonesece626c2024-09-03 11:19:31 -0700126 // TODO(b/346806126): implement this for the other ninjaCommand values.
127 if config.ninjaCommand == NINJA_NINJA {
128 switch config.NinjaWeightListSource() {
129 case NINJA_LOG:
Cole Faustbee030d2024-01-03 13:45:48 -0800130 cmd.Args = append(cmd.Args, "-o", "usesninjalogasweightlist=yes")
LaMont Jonesece626c2024-09-03 11:19:31 -0700131 case EVENLY_DISTRIBUTED:
132 // pass empty weight list means ninja considers every tasks's weight as 1(default value).
Cole Faustbee030d2024-01-03 13:45:48 -0800133 cmd.Args = append(cmd.Args, "-o", "usesweightlist=/dev/null")
LaMont Jonesece626c2024-09-03 11:19:31 -0700134 case EXTERNAL_FILE:
135 fallthrough
136 case HINT_FROM_SOONG:
137 // The weight list is already copied/generated.
Cole Faustbee030d2024-01-03 13:45:48 -0800138 ninjaWeightListPath := filepath.Join(config.OutDir(), ninjaWeightListFileName)
139 cmd.Args = append(cmd.Args, "-o", "usesweightlist="+ninjaWeightListPath)
140 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900141 }
142
Dan Willemsen1e704462016-08-21 15:17:17 -0700143 // Allow both NINJA_ARGS and NINJA_EXTRA_ARGS, since both have been
144 // used in the past to specify extra ninja arguments.
Dan Willemsen269a8c72017-05-03 17:15:47 -0700145 if extra, ok := cmd.Environment.Get("NINJA_ARGS"); ok {
146 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -0700147 }
Dan Willemsen269a8c72017-05-03 17:15:47 -0700148 if extra, ok := cmd.Environment.Get("NINJA_EXTRA_ARGS"); ok {
149 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -0700150 }
151
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700152 ninjaHeartbeatDuration := time.Minute * 5
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500153 // Get the ninja heartbeat interval from the environment before it's filtered away later.
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700154 if overrideText, ok := cmd.Environment.Get("NINJA_HEARTBEAT_INTERVAL"); ok {
155 // For example, "1m"
156 overrideDuration, err := time.ParseDuration(overrideText)
157 if err == nil && overrideDuration.Seconds() > 0 {
158 ninjaHeartbeatDuration = overrideDuration
159 }
160 }
Dan Willemsene3336352020-01-02 19:10:38 -0800161
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500162 // Filter the environment, as ninja does not rebuild files when environment
163 // variables change.
Dan Willemsene3336352020-01-02 19:10:38 -0800164 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500165 // Anything listed here must not change the output of rules/actions when the
166 // value changes, otherwise incremental builds may be unsafe. Vars
167 // explicitly set to stable values elsewhere in soong_ui are fine.
Dan Willemsene3336352020-01-02 19:10:38 -0800168 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500169 // For the majority of cases, either Soong or the makefiles should be
170 // replicating any necessary environment variables in the command line of
171 // each action that needs it.
Dan Willemsen260db532020-01-02 20:12:09 -0800172 if cmd.Environment.IsEnvTrue("ALLOW_NINJA_ENV") {
173 ctx.Println("Allowing all environment variables during ninja; incremental builds may be unsafe.")
174 } else {
Dan Willemsene3336352020-01-02 19:10:38 -0800175 cmd.Environment.Allow(append([]string{
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500176 // Set the path to a symbolizer (e.g. llvm-symbolizer) so ASAN-based
177 // tools can symbolize crashes.
Dan Willemsene3336352020-01-02 19:10:38 -0800178 "ASAN_SYMBOLIZER_PATH",
179 "HOME",
180 "JAVA_HOME",
181 "LANG",
182 "LC_MESSAGES",
183 "OUT_DIR",
184 "PATH",
185 "PWD",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500186 // https://docs.python.org/3/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE
Dan Willemsene3336352020-01-02 19:10:38 -0800187 "PYTHONDONTWRITEBYTECODE",
188 "TMPDIR",
189 "USER",
190
191 // TODO: remove these carefully
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500192 // Options for the address sanitizer.
Dan Willemsen7da04292020-01-04 13:58:54 -0800193 "ASAN_OPTIONS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500194 // The list of Android app modules to be built in an unbundled manner.
Dan Willemsene3336352020-01-02 19:10:38 -0800195 "TARGET_BUILD_APPS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500196 // The variant of the product being built. e.g. eng, userdebug, debug.
Dan Willemsene3336352020-01-02 19:10:38 -0800197 "TARGET_BUILD_VARIANT",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500198 // The product name of the product being built, e.g. aosp_arm, aosp_flame.
Dan Willemsene3336352020-01-02 19:10:38 -0800199 "TARGET_PRODUCT",
Dan Willemsen5cacfe12020-01-06 12:25:40 -0800200 // b/147197813 - used by art-check-debug-apex-gen
201 "EMMA_INSTRUMENT_FRAMEWORK",
Dan Willemsene3336352020-01-02 19:10:38 -0800202
Dan Willemsene3336352020-01-02 19:10:38 -0800203 // RBE client
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400204 "RBE_compare",
andusyu240660d2022-01-20 14:00:58 -0500205 "RBE_num_local_reruns",
206 "RBE_num_remote_reruns",
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400207 "RBE_exec_root",
208 "RBE_exec_strategy",
209 "RBE_invocation_id",
210 "RBE_log_dir",
Kousik Kumarc3a22d82021-03-17 14:19:27 -0400211 "RBE_num_retries_if_mismatched",
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400212 "RBE_platform",
213 "RBE_remote_accept_cache",
214 "RBE_remote_update_cache",
215 "RBE_server_address",
216 // TODO: remove old FLAG_ variables.
Kousik Kumarade12e72020-01-09 08:52:59 -0800217 "FLAG_compare",
Dan Willemsene3336352020-01-02 19:10:38 -0800218 "FLAG_exec_root",
219 "FLAG_exec_strategy",
220 "FLAG_invocation_id",
221 "FLAG_log_dir",
222 "FLAG_platform",
Kousik Kumar0f095e12020-01-28 10:48:46 -0800223 "FLAG_remote_accept_cache",
224 "FLAG_remote_update_cache",
Dan Willemsene3336352020-01-02 19:10:38 -0800225 "FLAG_server_address",
226
227 // ccache settings
228 "CCACHE_COMPILERCHECK",
229 "CCACHE_SLOPPINESS",
230 "CCACHE_BASEDIR",
231 "CCACHE_CPP2",
John Eckerdal974b0e82020-02-04 15:59:37 +0100232 "CCACHE_DIR",
Yi Kong6adf2582022-04-17 15:01:06 +0800233
234 // LLVM compiler wrapper options
235 "TOOLCHAIN_RUSAGE_OUTPUT",
Cole Faustded79602023-09-05 17:48:11 -0700236
237 // We don't want this build broken flag to cause reanalysis, so allow it through to the
238 // actions.
239 "BUILD_BROKEN_INCORRECT_PARTITION_IMAGES",
LaMont Jonesece626c2024-09-03 11:19:31 -0700240 // Do not do reanalysis just because we changed ninja commands.
241 "SOONG_NINJA",
Cole Faustbee030d2024-01-03 13:45:48 -0800242 "SOONG_USE_N2",
243 "RUST_BACKTRACE",
LaMont Jonesb2ab5272024-08-14 10:08:50 -0700244 "RUST_LOG",
LaMont Jones99f18962024-10-17 11:50:44 -0700245
246 // SOONG_USE_PARTIAL_COMPILE only determines which half of the rule we execute.
247 "SOONG_USE_PARTIAL_COMPILE",
LaMont Jones8490ffb2024-11-14 16:42:54 -0800248
249 // Directory for ExecutionMetrics
250 "SOONG_METRICS_AGGREGATION_DIR",
Dan Willemsene3336352020-01-02 19:10:38 -0800251 }, config.BuildBrokenNinjaUsesEnvVars()...)...)
252 }
253
254 cmd.Environment.Set("DIST_DIR", config.DistDir())
255 cmd.Environment.Set("SHELL", "/bin/bash")
LaMont Jonesece626c2024-09-03 11:19:31 -0700256 switch config.ninjaCommand {
257 case NINJA_N2:
Cole Faustbee030d2024-01-03 13:45:48 -0800258 cmd.Environment.Set("RUST_BACKTRACE", "1")
LaMont Jonesece626c2024-09-03 11:19:31 -0700259 default:
260 // Only set RUST_BACKTRACE for n2.
Cole Faustbee030d2024-01-03 13:45:48 -0800261 }
Dan Willemsene3336352020-01-02 19:10:38 -0800262
LaMont Jones8490ffb2024-11-14 16:42:54 -0800263 // Set up the metrics aggregation directory.
264 ctx.ExecutionMetrics.SetDir(filepath.Join(config.OutDir(), "soong", "metrics_aggregation"))
265 cmd.Environment.Set("SOONG_METRICS_AGGREGATION_DIR", ctx.ExecutionMetrics.MetricsAggregationDir)
266
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500267 // Print the environment variables that Ninja is operating in.
Dan Willemsene3336352020-01-02 19:10:38 -0800268 ctx.Verboseln("Ninja environment: ")
269 envVars := cmd.Environment.Environ()
270 sort.Strings(envVars)
271 for _, envVar := range envVars {
272 ctx.Verbosef(" %s", envVar)
273 }
274
Spandan Das2db59da2023-02-16 18:31:43 +0000275 // Write the env vars available during ninja execution to a file
276 ninjaEnvVars := cmd.Environment.AsMap()
277 data, err := shared.EnvFileContents(ninjaEnvVars)
278 if err != nil {
279 ctx.Panicf("Could not parse environment variables for ninja run %s", err)
280 }
281 // Write the file in every single run. This is fine because
282 // 1. It is not a dep of Soong analysis, so will not retrigger Soong analysis.
283 // 2. Is is fairly lightweight (~1Kb)
284 ninjaEnvVarsFile := shared.JoinPath(config.SoongOutDir(), ninjaEnvFileName)
285 err = os.WriteFile(ninjaEnvVarsFile, data, 0666)
286 if err != nil {
287 ctx.Panicf("Could not write ninja environment file %s", err)
288 }
289
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500290 // Poll the Ninja log for updates regularly based on the heartbeat
291 // frequency. If it isn't updated enough, then we want to surface the
292 // possibility that Ninja is stuck, to the user.
Jeff Gastona6697e82017-06-13 12:51:50 -0700293 done := make(chan struct{})
294 defer close(done)
295 ticker := time.NewTicker(ninjaHeartbeatDuration)
296 defer ticker.Stop()
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500297 ninjaChecker := &ninjaStucknessChecker{
Jeongik Cha96d62272023-03-17 01:53:11 +0900298 logPath: filepath.Join(config.OutDir(), ninjaLogFileName),
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500299 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700300 go func() {
Jeff Gastona6697e82017-06-13 12:51:50 -0700301 for {
302 select {
303 case <-ticker.C:
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500304 ninjaChecker.check(ctx, config)
Jeff Gastona6697e82017-06-13 12:51:50 -0700305 case <-done:
306 return
307 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700308 }
309 }()
310
LaMont Jones8490ffb2024-11-14 16:42:54 -0800311 ctx.ExecutionMetrics.Start()
312 defer ctx.ExecutionMetrics.Finish(ctx)
Dan Willemsen7f30c072019-01-02 12:50:49 -0800313 ctx.Status.Status("Starting ninja...")
Colin Cross7b97ecd2019-06-19 13:17:59 -0700314 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700315}
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700316
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500317// A simple struct for checking if Ninja gets stuck, using timestamps.
318type ninjaStucknessChecker struct {
319 logPath string
320 prevModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700321}
322
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500323// Check that a file has been modified since the last time it was checked. If
324// the mod time hasn't changed, then assume that Ninja got stuck, and print
325// diagnostics for debugging.
326func (c *ninjaStucknessChecker) check(ctx Context, config Config) {
327 info, err := os.Stat(c.logPath)
328 var newModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700329 if err == nil {
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500330 newModTime = info.ModTime()
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700331 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500332 if newModTime == c.prevModTime {
333 // The Ninja file hasn't been modified since the last time it was
334 // checked, so Ninja could be stuck. Output some diagnostics.
335 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 -0800336 ctx.Printf("ninja may be stuck, check %v for list of running processes.",
337 filepath.Join(config.LogsDir(), config.logsPrefix+"soong.log"))
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500338
339 // The "pstree" command doesn't exist on Mac, but "pstree" on Linux
340 // gives more convenient output than "ps" So, we try pstree first, and
341 // ps second
Colin Crossa9aa35c2024-01-05 14:03:27 -0800342 commandText := fmt.Sprintf("pstree -palT %v || ps -ef", os.Getpid())
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500343
344 cmd := Command(ctx, config, "dump process tree", "bash", "-c", commandText)
345 output := cmd.CombinedOutputOrFatal()
346 ctx.Verbose(string(output))
347
348 ctx.Verbosef("done\n")
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700349 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500350 c.prevModTime = newModTime
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700351}
Joe Onoratod6a29992024-12-06 12:55:41 -0800352
353// Constructs and runs the Ninja command line to get the inputs of a goal.
354// For now, this will always run ninja, because ninjago, n2 and siso don't have the
355// `-t inputs` command. This command will use the inputs command's -d option,
356// to use the dep file iff ninja was the executor. For other executors, the
357// results will be wrong.
358func runNinjaInputs(ctx Context, config Config, goal string) ([]string, error) {
359 executable := config.PrebuiltBuildTool("ninja")
360
361 args := []string{
362 "-f",
363 config.CombinedNinjaFile(),
364 "-t",
365 "inputs",
366 }
367 // Add deps file arg for ninja
368 // TODO: Update as inputs command is implemented
369 if config.ninjaCommand == NINJA_NINJA && !config.UseABFS() {
370 args = append(args, "-d")
371 }
372 args = append(args, goal)
373
374 // This is just ninja -t inputs, so we won't bother running it in the sandbox,
375 // so use exec.Command, not soong_ui's command.
376 cmd := exec.Command(executable, args...)
377
378 cmd.Stdin = os.Stdin
379 cmd.Stderr = os.Stderr
380
381 out, err := cmd.Output()
382 if err != nil {
383 fmt.Printf("Error getting goal inputs for %s: %s\n", goal, err)
384 return nil, err
385 }
386
387 return strings.Split(strings.TrimSpace(string(out)), "\n"), nil
388}