blob: a91cc3b68c737830b95ae2dea95785c21fb6e602 [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
Jeongik Cha0cf44d52023-03-15 00:10:45 +090036func useNinjaBuildLog(ctx Context, config Config, cmd *Cmd) {
37 ninjaLogFile := filepath.Join(config.OutDir(), ".ninja_log")
38 data, err := os.ReadFile(ninjaLogFile)
39 var outputBuilder strings.Builder
40 if err == nil {
41 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
42 // ninja log: <start> <end> <restat> <name> <cmdhash>
43 // ninja weight list: <name>,<end-start+1>
44 for _, line := range lines {
45 if strings.HasPrefix(line, "#") {
46 continue
47 }
48 fields := strings.Split(line, "\t")
49 path := fields[3]
50 start, err := strconv.Atoi(fields[0])
51 if err != nil {
52 continue
53 }
54 end, err := strconv.Atoi(fields[1])
55 if err != nil {
56 continue
57 }
58 outputBuilder.WriteString(path)
59 outputBuilder.WriteString(",")
60 outputBuilder.WriteString(strconv.Itoa(end-start+1) + "\n")
61 }
62 }
63 // If there is no ninja log file, just pass empty ninja weight list.
64 // Because it is still efficient with critical path calculation logic even without weight.
65
66 weightListFile := filepath.Join(config.OutDir(), ".ninja_weight_list")
67
68 err = os.WriteFile(weightListFile, []byte(outputBuilder.String()), 0644)
69 if err == nil {
70 cmd.Args = append(cmd.Args, "-o", "usesweightlist="+weightListFile)
71 } else {
72 ctx.Panicf("Could not write ninja weight list file %s", err)
73 }
74}
75
Jingwen Chen9d1cb492020-11-17 06:52:28 -050076// Constructs and runs the Ninja command line with a restricted set of
77// environment variables. It's important to restrict the environment Ninja runs
78// for hermeticity reasons, and to avoid spurious rebuilds.
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010079func runNinjaForBuild(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -080080 ctx.BeginTrace(metrics.PrimaryNinja, "ninja")
Dan Willemsend9f6fa22016-08-21 15:17:17 -070081 defer ctx.EndTrace()
82
Jingwen Chen9d1cb492020-11-17 06:52:28 -050083 // Sets up the FIFO status updater that reads the Ninja protobuf output, and
84 // translates it to the soong_ui status output, displaying real-time
85 // progress of the build.
Dan Willemsenb82471a2018-05-17 16:37:09 -070086 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -070087 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
88 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -070089
Dan Willemsenf173d592017-04-27 14:28:00 -070090 executable := config.PrebuiltBuildTool("ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -070091 args := []string{
92 "-d", "keepdepfile",
Dan Willemsen6d3cad92020-03-12 10:30:35 -070093 "-d", "keeprsp",
Dan Willemsen08218222020-05-18 14:02:02 -070094 "-d", "stats",
Dan Willemsen02736672018-07-17 17:54:31 -070095 "--frontend_file", fifo,
Dan Willemsen1e704462016-08-21 15:17:17 -070096 }
97
98 args = append(args, config.NinjaArgs()...)
99
100 var parallel int
Colin Cross9016b912019-11-11 14:57:42 -0800101 if config.UseRemoteBuild() {
Dan Willemsen1e704462016-08-21 15:17:17 -0700102 parallel = config.RemoteParallel()
103 } else {
104 parallel = config.Parallel()
105 }
106 args = append(args, "-j", strconv.Itoa(parallel))
107 if config.keepGoing != 1 {
108 args = append(args, "-k", strconv.Itoa(config.keepGoing))
109 }
110
111 args = append(args, "-f", config.CombinedNinjaFile())
112
Dan Willemsenf7939332019-01-05 19:31:32 -0800113 args = append(args,
Dan Willemsen6587bed2020-04-18 20:25:59 -0700114 "-o", "usesphonyoutputs=yes",
Dan Willemsenf7939332019-01-05 19:31:32 -0800115 "-w", "dupbuild=err",
Steven Moreland28d35a12022-10-18 00:13:59 +0000116 "-w", "missingdepfile=err")
Dan Willemsen1e704462016-08-21 15:17:17 -0700117
Dan Willemsen269a8c72017-05-03 17:15:47 -0700118 cmd := Command(ctx, config, "ninja", executable, args...)
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500119
120 // Set up the nsjail sandbox Ninja runs in.
Dan Willemsen63663c62019-01-02 12:24:44 -0800121 cmd.Sandbox = ninjaSandbox
Dan Willemsene0879fc2017-08-04 15:06:27 -0700122 if config.HasKatiSuffix() {
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500123 // Reads and executes a shell script from Kati that sets/unsets the
124 // environment Ninja runs in.
Dan Willemsene0879fc2017-08-04 15:06:27 -0700125 cmd.Environment.AppendFromKati(config.KatiEnvFile())
126 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700127
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900128 switch config.NinjaWeightListSource() {
129 case NINJA_LOG:
130 useNinjaBuildLog(ctx, config, cmd)
131 case EVENLY_DISTRIBUTED:
132 // pass empty weight list means ninja considers every tasks's weight as 1(default value).
133 cmd.Args = append(cmd.Args, "-o", "usesweightlist=/dev/null")
134 }
135
Dan Willemsen1e704462016-08-21 15:17:17 -0700136 // Allow both NINJA_ARGS and NINJA_EXTRA_ARGS, since both have been
137 // used in the past to specify extra ninja arguments.
Dan Willemsen269a8c72017-05-03 17:15:47 -0700138 if extra, ok := cmd.Environment.Get("NINJA_ARGS"); ok {
139 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -0700140 }
Dan Willemsen269a8c72017-05-03 17:15:47 -0700141 if extra, ok := cmd.Environment.Get("NINJA_EXTRA_ARGS"); ok {
142 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -0700143 }
144
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700145 ninjaHeartbeatDuration := time.Minute * 5
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500146 // Get the ninja heartbeat interval from the environment before it's filtered away later.
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700147 if overrideText, ok := cmd.Environment.Get("NINJA_HEARTBEAT_INTERVAL"); ok {
148 // For example, "1m"
149 overrideDuration, err := time.ParseDuration(overrideText)
150 if err == nil && overrideDuration.Seconds() > 0 {
151 ninjaHeartbeatDuration = overrideDuration
152 }
153 }
Dan Willemsene3336352020-01-02 19:10:38 -0800154
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500155 // Filter the environment, as ninja does not rebuild files when environment
156 // variables change.
Dan Willemsene3336352020-01-02 19:10:38 -0800157 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500158 // Anything listed here must not change the output of rules/actions when the
159 // value changes, otherwise incremental builds may be unsafe. Vars
160 // explicitly set to stable values elsewhere in soong_ui are fine.
Dan Willemsene3336352020-01-02 19:10:38 -0800161 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500162 // For the majority of cases, either Soong or the makefiles should be
163 // replicating any necessary environment variables in the command line of
164 // each action that needs it.
Dan Willemsen260db532020-01-02 20:12:09 -0800165 if cmd.Environment.IsEnvTrue("ALLOW_NINJA_ENV") {
166 ctx.Println("Allowing all environment variables during ninja; incremental builds may be unsafe.")
167 } else {
Dan Willemsene3336352020-01-02 19:10:38 -0800168 cmd.Environment.Allow(append([]string{
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500169 // Set the path to a symbolizer (e.g. llvm-symbolizer) so ASAN-based
170 // tools can symbolize crashes.
Dan Willemsene3336352020-01-02 19:10:38 -0800171 "ASAN_SYMBOLIZER_PATH",
172 "HOME",
173 "JAVA_HOME",
174 "LANG",
175 "LC_MESSAGES",
176 "OUT_DIR",
177 "PATH",
178 "PWD",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500179 // https://docs.python.org/3/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE
Dan Willemsene3336352020-01-02 19:10:38 -0800180 "PYTHONDONTWRITEBYTECODE",
181 "TMPDIR",
182 "USER",
183
184 // TODO: remove these carefully
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500185 // Options for the address sanitizer.
Dan Willemsen7da04292020-01-04 13:58:54 -0800186 "ASAN_OPTIONS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500187 // The list of Android app modules to be built in an unbundled manner.
Dan Willemsene3336352020-01-02 19:10:38 -0800188 "TARGET_BUILD_APPS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500189 // The variant of the product being built. e.g. eng, userdebug, debug.
Dan Willemsene3336352020-01-02 19:10:38 -0800190 "TARGET_BUILD_VARIANT",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500191 // The product name of the product being built, e.g. aosp_arm, aosp_flame.
Dan Willemsene3336352020-01-02 19:10:38 -0800192 "TARGET_PRODUCT",
Dan Willemsen5cacfe12020-01-06 12:25:40 -0800193 // b/147197813 - used by art-check-debug-apex-gen
194 "EMMA_INSTRUMENT_FRAMEWORK",
Dan Willemsene3336352020-01-02 19:10:38 -0800195
Dan Willemsene3336352020-01-02 19:10:38 -0800196 // RBE client
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400197 "RBE_compare",
andusyu240660d2022-01-20 14:00:58 -0500198 "RBE_num_local_reruns",
199 "RBE_num_remote_reruns",
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400200 "RBE_exec_root",
201 "RBE_exec_strategy",
202 "RBE_invocation_id",
203 "RBE_log_dir",
Kousik Kumarc3a22d82021-03-17 14:19:27 -0400204 "RBE_num_retries_if_mismatched",
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400205 "RBE_platform",
206 "RBE_remote_accept_cache",
207 "RBE_remote_update_cache",
208 "RBE_server_address",
209 // TODO: remove old FLAG_ variables.
Kousik Kumarade12e72020-01-09 08:52:59 -0800210 "FLAG_compare",
Dan Willemsene3336352020-01-02 19:10:38 -0800211 "FLAG_exec_root",
212 "FLAG_exec_strategy",
213 "FLAG_invocation_id",
214 "FLAG_log_dir",
215 "FLAG_platform",
Kousik Kumar0f095e12020-01-28 10:48:46 -0800216 "FLAG_remote_accept_cache",
217 "FLAG_remote_update_cache",
Dan Willemsene3336352020-01-02 19:10:38 -0800218 "FLAG_server_address",
219
220 // ccache settings
221 "CCACHE_COMPILERCHECK",
222 "CCACHE_SLOPPINESS",
223 "CCACHE_BASEDIR",
224 "CCACHE_CPP2",
John Eckerdal974b0e82020-02-04 15:59:37 +0100225 "CCACHE_DIR",
Yi Kong6adf2582022-04-17 15:01:06 +0800226
227 // LLVM compiler wrapper options
228 "TOOLCHAIN_RUSAGE_OUTPUT",
Dan Willemsene3336352020-01-02 19:10:38 -0800229 }, config.BuildBrokenNinjaUsesEnvVars()...)...)
230 }
231
232 cmd.Environment.Set("DIST_DIR", config.DistDir())
233 cmd.Environment.Set("SHELL", "/bin/bash")
234
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500235 // Print the environment variables that Ninja is operating in.
Dan Willemsene3336352020-01-02 19:10:38 -0800236 ctx.Verboseln("Ninja environment: ")
237 envVars := cmd.Environment.Environ()
238 sort.Strings(envVars)
239 for _, envVar := range envVars {
240 ctx.Verbosef(" %s", envVar)
241 }
242
Spandan Das2db59da2023-02-16 18:31:43 +0000243 // Write the env vars available during ninja execution to a file
244 ninjaEnvVars := cmd.Environment.AsMap()
245 data, err := shared.EnvFileContents(ninjaEnvVars)
246 if err != nil {
247 ctx.Panicf("Could not parse environment variables for ninja run %s", err)
248 }
249 // Write the file in every single run. This is fine because
250 // 1. It is not a dep of Soong analysis, so will not retrigger Soong analysis.
251 // 2. Is is fairly lightweight (~1Kb)
252 ninjaEnvVarsFile := shared.JoinPath(config.SoongOutDir(), ninjaEnvFileName)
253 err = os.WriteFile(ninjaEnvVarsFile, data, 0666)
254 if err != nil {
255 ctx.Panicf("Could not write ninja environment file %s", err)
256 }
257
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500258 // Poll the Ninja log for updates regularly based on the heartbeat
259 // frequency. If it isn't updated enough, then we want to surface the
260 // possibility that Ninja is stuck, to the user.
Jeff Gastona6697e82017-06-13 12:51:50 -0700261 done := make(chan struct{})
262 defer close(done)
263 ticker := time.NewTicker(ninjaHeartbeatDuration)
264 defer ticker.Stop()
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500265 ninjaChecker := &ninjaStucknessChecker{
266 logPath: filepath.Join(config.OutDir(), ".ninja_log"),
267 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700268 go func() {
Jeff Gastona6697e82017-06-13 12:51:50 -0700269 for {
270 select {
271 case <-ticker.C:
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500272 ninjaChecker.check(ctx, config)
Jeff Gastona6697e82017-06-13 12:51:50 -0700273 case <-done:
274 return
275 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700276 }
277 }()
278
Dan Willemsen7f30c072019-01-02 12:50:49 -0800279 ctx.Status.Status("Starting ninja...")
Colin Cross7b97ecd2019-06-19 13:17:59 -0700280 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700281}
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700282
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500283// A simple struct for checking if Ninja gets stuck, using timestamps.
284type ninjaStucknessChecker struct {
285 logPath string
286 prevModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700287}
288
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500289// Check that a file has been modified since the last time it was checked. If
290// the mod time hasn't changed, then assume that Ninja got stuck, and print
291// diagnostics for debugging.
292func (c *ninjaStucknessChecker) check(ctx Context, config Config) {
293 info, err := os.Stat(c.logPath)
294 var newModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700295 if err == nil {
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500296 newModTime = info.ModTime()
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700297 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500298 if newModTime == c.prevModTime {
299 // The Ninja file hasn't been modified since the last time it was
300 // checked, so Ninja could be stuck. Output some diagnostics.
301 ctx.Verbosef("ninja may be stuck; last update to %v was %v. dumping process tree...", c.logPath, newModTime)
302
303 // The "pstree" command doesn't exist on Mac, but "pstree" on Linux
304 // gives more convenient output than "ps" So, we try pstree first, and
305 // ps second
306 commandText := fmt.Sprintf("pstree -pal %v || ps -ef", os.Getpid())
307
308 cmd := Command(ctx, config, "dump process tree", "bash", "-c", commandText)
309 output := cmd.CombinedOutputOrFatal()
310 ctx.Verbose(string(output))
311
312 ctx.Verbosef("done\n")
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700313 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500314 c.prevModTime = newModTime
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700315}