blob: 28f3c3806dce09634ab26a998db8a3a3cf49dc00 [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
33 ninjaEnvFileName = "ninja.environment"
34)
35
Jingwen Chen9d1cb492020-11-17 06:52:28 -050036// Constructs and runs the Ninja command line with a restricted set of
37// environment variables. It's important to restrict the environment Ninja runs
38// for hermeticity reasons, and to avoid spurious rebuilds.
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010039func runNinjaForBuild(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -080040 ctx.BeginTrace(metrics.PrimaryNinja, "ninja")
Dan Willemsend9f6fa22016-08-21 15:17:17 -070041 defer ctx.EndTrace()
42
Jingwen Chen9d1cb492020-11-17 06:52:28 -050043 // Sets up the FIFO status updater that reads the Ninja protobuf output, and
44 // translates it to the soong_ui status output, displaying real-time
45 // progress of the build.
Dan Willemsenb82471a2018-05-17 16:37:09 -070046 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -070047 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
48 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -070049
Dan Willemsenf173d592017-04-27 14:28:00 -070050 executable := config.PrebuiltBuildTool("ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -070051 args := []string{
52 "-d", "keepdepfile",
Dan Willemsen6d3cad92020-03-12 10:30:35 -070053 "-d", "keeprsp",
Dan Willemsen08218222020-05-18 14:02:02 -070054 "-d", "stats",
Dan Willemsen02736672018-07-17 17:54:31 -070055 "--frontend_file", fifo,
Dan Willemsen1e704462016-08-21 15:17:17 -070056 }
57
58 args = append(args, config.NinjaArgs()...)
59
60 var parallel int
Colin Cross9016b912019-11-11 14:57:42 -080061 if config.UseRemoteBuild() {
Dan Willemsen1e704462016-08-21 15:17:17 -070062 parallel = config.RemoteParallel()
63 } else {
64 parallel = config.Parallel()
65 }
66 args = append(args, "-j", strconv.Itoa(parallel))
67 if config.keepGoing != 1 {
68 args = append(args, "-k", strconv.Itoa(config.keepGoing))
69 }
70
71 args = append(args, "-f", config.CombinedNinjaFile())
72
Dan Willemsenf7939332019-01-05 19:31:32 -080073 args = append(args,
Dan Willemsen6587bed2020-04-18 20:25:59 -070074 "-o", "usesphonyoutputs=yes",
Dan Willemsenf7939332019-01-05 19:31:32 -080075 "-w", "dupbuild=err",
Steven Moreland28d35a12022-10-18 00:13:59 +000076 "-w", "missingdepfile=err")
Dan Willemsen1e704462016-08-21 15:17:17 -070077
Dan Willemsen269a8c72017-05-03 17:15:47 -070078 cmd := Command(ctx, config, "ninja", executable, args...)
Jingwen Chen9d1cb492020-11-17 06:52:28 -050079
80 // Set up the nsjail sandbox Ninja runs in.
Dan Willemsen63663c62019-01-02 12:24:44 -080081 cmd.Sandbox = ninjaSandbox
Dan Willemsene0879fc2017-08-04 15:06:27 -070082 if config.HasKatiSuffix() {
Jingwen Chen9d1cb492020-11-17 06:52:28 -050083 // Reads and executes a shell script from Kati that sets/unsets the
84 // environment Ninja runs in.
Dan Willemsene0879fc2017-08-04 15:06:27 -070085 cmd.Environment.AppendFromKati(config.KatiEnvFile())
86 }
Dan Willemsen1e704462016-08-21 15:17:17 -070087
88 // Allow both NINJA_ARGS and NINJA_EXTRA_ARGS, since both have been
89 // used in the past to specify extra ninja arguments.
Dan Willemsen269a8c72017-05-03 17:15:47 -070090 if extra, ok := cmd.Environment.Get("NINJA_ARGS"); ok {
91 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -070092 }
Dan Willemsen269a8c72017-05-03 17:15:47 -070093 if extra, ok := cmd.Environment.Get("NINJA_EXTRA_ARGS"); ok {
94 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -070095 }
96
Jeff Gaston809cc6f2017-05-25 15:44:36 -070097 ninjaHeartbeatDuration := time.Minute * 5
Jingwen Chen9d1cb492020-11-17 06:52:28 -050098 // Get the ninja heartbeat interval from the environment before it's filtered away later.
Jeff Gaston809cc6f2017-05-25 15:44:36 -070099 if overrideText, ok := cmd.Environment.Get("NINJA_HEARTBEAT_INTERVAL"); ok {
100 // For example, "1m"
101 overrideDuration, err := time.ParseDuration(overrideText)
102 if err == nil && overrideDuration.Seconds() > 0 {
103 ninjaHeartbeatDuration = overrideDuration
104 }
105 }
Dan Willemsene3336352020-01-02 19:10:38 -0800106
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500107 // Filter the environment, as ninja does not rebuild files when environment
108 // variables change.
Dan Willemsene3336352020-01-02 19:10:38 -0800109 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500110 // Anything listed here must not change the output of rules/actions when the
111 // value changes, otherwise incremental builds may be unsafe. Vars
112 // explicitly set to stable values elsewhere in soong_ui are fine.
Dan Willemsene3336352020-01-02 19:10:38 -0800113 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500114 // For the majority of cases, either Soong or the makefiles should be
115 // replicating any necessary environment variables in the command line of
116 // each action that needs it.
Dan Willemsen260db532020-01-02 20:12:09 -0800117 if cmd.Environment.IsEnvTrue("ALLOW_NINJA_ENV") {
118 ctx.Println("Allowing all environment variables during ninja; incremental builds may be unsafe.")
119 } else {
Dan Willemsene3336352020-01-02 19:10:38 -0800120 cmd.Environment.Allow(append([]string{
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500121 // Set the path to a symbolizer (e.g. llvm-symbolizer) so ASAN-based
122 // tools can symbolize crashes.
Dan Willemsene3336352020-01-02 19:10:38 -0800123 "ASAN_SYMBOLIZER_PATH",
124 "HOME",
125 "JAVA_HOME",
126 "LANG",
127 "LC_MESSAGES",
128 "OUT_DIR",
129 "PATH",
130 "PWD",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500131 // https://docs.python.org/3/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE
Dan Willemsene3336352020-01-02 19:10:38 -0800132 "PYTHONDONTWRITEBYTECODE",
133 "TMPDIR",
134 "USER",
135
136 // TODO: remove these carefully
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500137 // Options for the address sanitizer.
Dan Willemsen7da04292020-01-04 13:58:54 -0800138 "ASAN_OPTIONS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500139 // The list of Android app modules to be built in an unbundled manner.
Dan Willemsene3336352020-01-02 19:10:38 -0800140 "TARGET_BUILD_APPS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500141 // The variant of the product being built. e.g. eng, userdebug, debug.
Dan Willemsene3336352020-01-02 19:10:38 -0800142 "TARGET_BUILD_VARIANT",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500143 // The product name of the product being built, e.g. aosp_arm, aosp_flame.
Dan Willemsene3336352020-01-02 19:10:38 -0800144 "TARGET_PRODUCT",
Dan Willemsen5cacfe12020-01-06 12:25:40 -0800145 // b/147197813 - used by art-check-debug-apex-gen
146 "EMMA_INSTRUMENT_FRAMEWORK",
Dan Willemsene3336352020-01-02 19:10:38 -0800147
Dan Willemsene3336352020-01-02 19:10:38 -0800148 // RBE client
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400149 "RBE_compare",
andusyu240660d2022-01-20 14:00:58 -0500150 "RBE_num_local_reruns",
151 "RBE_num_remote_reruns",
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400152 "RBE_exec_root",
153 "RBE_exec_strategy",
154 "RBE_invocation_id",
155 "RBE_log_dir",
Kousik Kumarc3a22d82021-03-17 14:19:27 -0400156 "RBE_num_retries_if_mismatched",
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400157 "RBE_platform",
158 "RBE_remote_accept_cache",
159 "RBE_remote_update_cache",
160 "RBE_server_address",
161 // TODO: remove old FLAG_ variables.
Kousik Kumarade12e72020-01-09 08:52:59 -0800162 "FLAG_compare",
Dan Willemsene3336352020-01-02 19:10:38 -0800163 "FLAG_exec_root",
164 "FLAG_exec_strategy",
165 "FLAG_invocation_id",
166 "FLAG_log_dir",
167 "FLAG_platform",
Kousik Kumar0f095e12020-01-28 10:48:46 -0800168 "FLAG_remote_accept_cache",
169 "FLAG_remote_update_cache",
Dan Willemsene3336352020-01-02 19:10:38 -0800170 "FLAG_server_address",
171
172 // ccache settings
173 "CCACHE_COMPILERCHECK",
174 "CCACHE_SLOPPINESS",
175 "CCACHE_BASEDIR",
176 "CCACHE_CPP2",
John Eckerdal974b0e82020-02-04 15:59:37 +0100177 "CCACHE_DIR",
Yi Kong6adf2582022-04-17 15:01:06 +0800178
179 // LLVM compiler wrapper options
180 "TOOLCHAIN_RUSAGE_OUTPUT",
Dan Willemsene3336352020-01-02 19:10:38 -0800181 }, config.BuildBrokenNinjaUsesEnvVars()...)...)
182 }
183
184 cmd.Environment.Set("DIST_DIR", config.DistDir())
185 cmd.Environment.Set("SHELL", "/bin/bash")
186
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500187 // Print the environment variables that Ninja is operating in.
Dan Willemsene3336352020-01-02 19:10:38 -0800188 ctx.Verboseln("Ninja environment: ")
189 envVars := cmd.Environment.Environ()
190 sort.Strings(envVars)
191 for _, envVar := range envVars {
192 ctx.Verbosef(" %s", envVar)
193 }
194
Spandan Das2db59da2023-02-16 18:31:43 +0000195 // Write the env vars available during ninja execution to a file
196 ninjaEnvVars := cmd.Environment.AsMap()
197 data, err := shared.EnvFileContents(ninjaEnvVars)
198 if err != nil {
199 ctx.Panicf("Could not parse environment variables for ninja run %s", err)
200 }
201 // Write the file in every single run. This is fine because
202 // 1. It is not a dep of Soong analysis, so will not retrigger Soong analysis.
203 // 2. Is is fairly lightweight (~1Kb)
204 ninjaEnvVarsFile := shared.JoinPath(config.SoongOutDir(), ninjaEnvFileName)
205 err = os.WriteFile(ninjaEnvVarsFile, data, 0666)
206 if err != nil {
207 ctx.Panicf("Could not write ninja environment file %s", err)
208 }
209
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500210 // Poll the Ninja log for updates regularly based on the heartbeat
211 // frequency. If it isn't updated enough, then we want to surface the
212 // possibility that Ninja is stuck, to the user.
Jeff Gastona6697e82017-06-13 12:51:50 -0700213 done := make(chan struct{})
214 defer close(done)
215 ticker := time.NewTicker(ninjaHeartbeatDuration)
216 defer ticker.Stop()
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500217 ninjaChecker := &ninjaStucknessChecker{
218 logPath: filepath.Join(config.OutDir(), ".ninja_log"),
219 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700220 go func() {
Jeff Gastona6697e82017-06-13 12:51:50 -0700221 for {
222 select {
223 case <-ticker.C:
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500224 ninjaChecker.check(ctx, config)
Jeff Gastona6697e82017-06-13 12:51:50 -0700225 case <-done:
226 return
227 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700228 }
229 }()
230
Dan Willemsen7f30c072019-01-02 12:50:49 -0800231 ctx.Status.Status("Starting ninja...")
Colin Cross7b97ecd2019-06-19 13:17:59 -0700232 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700233}
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700234
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500235// A simple struct for checking if Ninja gets stuck, using timestamps.
236type ninjaStucknessChecker struct {
237 logPath string
238 prevModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700239}
240
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500241// Check that a file has been modified since the last time it was checked. If
242// the mod time hasn't changed, then assume that Ninja got stuck, and print
243// diagnostics for debugging.
244func (c *ninjaStucknessChecker) check(ctx Context, config Config) {
245 info, err := os.Stat(c.logPath)
246 var newModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700247 if err == nil {
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500248 newModTime = info.ModTime()
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700249 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500250 if newModTime == c.prevModTime {
251 // The Ninja file hasn't been modified since the last time it was
252 // checked, so Ninja could be stuck. Output some diagnostics.
253 ctx.Verbosef("ninja may be stuck; last update to %v was %v. dumping process tree...", c.logPath, newModTime)
254
255 // The "pstree" command doesn't exist on Mac, but "pstree" on Linux
256 // gives more convenient output than "ps" So, we try pstree first, and
257 // ps second
258 commandText := fmt.Sprintf("pstree -pal %v || ps -ef", os.Getpid())
259
260 cmd := Command(ctx, config, "dump process tree", "bash", "-c", commandText)
261 output := cmd.CombinedOutputOrFatal()
262 ctx.Verbose(string(output))
263
264 ctx.Verbosef("done\n")
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700265 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500266 c.prevModTime = newModTime
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700267}