blob: 5d56531b2986a23e08fa95b91fd544b925313c12 [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
Jeongik Cha0cf44d52023-03-15 00:10:45 +090038func useNinjaBuildLog(ctx Context, config Config, cmd *Cmd) {
Jeongik Cha96d62272023-03-17 01:53:11 +090039 ninjaLogFile := filepath.Join(config.OutDir(), ninjaLogFileName)
Jeongik Cha0cf44d52023-03-15 00:10:45 +090040 data, err := os.ReadFile(ninjaLogFile)
41 var outputBuilder strings.Builder
42 if err == nil {
43 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
44 // ninja log: <start> <end> <restat> <name> <cmdhash>
45 // ninja weight list: <name>,<end-start+1>
46 for _, line := range lines {
47 if strings.HasPrefix(line, "#") {
48 continue
49 }
50 fields := strings.Split(line, "\t")
51 path := fields[3]
52 start, err := strconv.Atoi(fields[0])
53 if err != nil {
54 continue
55 }
56 end, err := strconv.Atoi(fields[1])
57 if err != nil {
58 continue
59 }
60 outputBuilder.WriteString(path)
61 outputBuilder.WriteString(",")
62 outputBuilder.WriteString(strconv.Itoa(end-start+1) + "\n")
63 }
Jeongik Cha96d62272023-03-17 01:53:11 +090064 } else {
65 // If there is no ninja log file, just pass empty ninja weight list.
66 // Because it is still efficient with critical path calculation logic even without weight.
67 ctx.Verbosef("There is an error during reading ninja log, so ninja will use empty weight list: %s", err)
Jeongik Cha0cf44d52023-03-15 00:10:45 +090068 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +090069
Jeongik Cha518f3ea2023-03-19 00:12:39 +090070 weightListFile := filepath.Join(config.OutDir(), ninjaWeightListFileName)
Jeongik Cha0cf44d52023-03-15 00:10:45 +090071
72 err = os.WriteFile(weightListFile, []byte(outputBuilder.String()), 0644)
73 if err == nil {
74 cmd.Args = append(cmd.Args, "-o", "usesweightlist="+weightListFile)
75 } else {
76 ctx.Panicf("Could not write ninja weight list file %s", err)
77 }
78}
79
Jingwen Chen9d1cb492020-11-17 06:52:28 -050080// Constructs and runs the Ninja command line with a restricted set of
81// environment variables. It's important to restrict the environment Ninja runs
82// for hermeticity reasons, and to avoid spurious rebuilds.
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010083func runNinjaForBuild(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -080084 ctx.BeginTrace(metrics.PrimaryNinja, "ninja")
Dan Willemsend9f6fa22016-08-21 15:17:17 -070085 defer ctx.EndTrace()
86
Jingwen Chen9d1cb492020-11-17 06:52:28 -050087 // Sets up the FIFO status updater that reads the Ninja protobuf output, and
88 // translates it to the soong_ui status output, displaying real-time
89 // progress of the build.
Dan Willemsenb82471a2018-05-17 16:37:09 -070090 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -070091 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
92 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -070093
Dan Willemsenf173d592017-04-27 14:28:00 -070094 executable := config.PrebuiltBuildTool("ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -070095 args := []string{
96 "-d", "keepdepfile",
Dan Willemsen6d3cad92020-03-12 10:30:35 -070097 "-d", "keeprsp",
Dan Willemsen08218222020-05-18 14:02:02 -070098 "-d", "stats",
Dan Willemsen02736672018-07-17 17:54:31 -070099 "--frontend_file", fifo,
Dan Willemsen1e704462016-08-21 15:17:17 -0700100 }
101
102 args = append(args, config.NinjaArgs()...)
103
104 var parallel int
Colin Cross9016b912019-11-11 14:57:42 -0800105 if config.UseRemoteBuild() {
Dan Willemsen1e704462016-08-21 15:17:17 -0700106 parallel = config.RemoteParallel()
107 } else {
108 parallel = config.Parallel()
109 }
110 args = append(args, "-j", strconv.Itoa(parallel))
111 if config.keepGoing != 1 {
112 args = append(args, "-k", strconv.Itoa(config.keepGoing))
113 }
114
115 args = append(args, "-f", config.CombinedNinjaFile())
116
Dan Willemsenf7939332019-01-05 19:31:32 -0800117 args = append(args,
Dan Willemsen6587bed2020-04-18 20:25:59 -0700118 "-o", "usesphonyoutputs=yes",
Dan Willemsenf7939332019-01-05 19:31:32 -0800119 "-w", "dupbuild=err",
Steven Moreland28d35a12022-10-18 00:13:59 +0000120 "-w", "missingdepfile=err")
Dan Willemsen1e704462016-08-21 15:17:17 -0700121
Dan Willemsen269a8c72017-05-03 17:15:47 -0700122 cmd := Command(ctx, config, "ninja", executable, args...)
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500123
124 // Set up the nsjail sandbox Ninja runs in.
Dan Willemsen63663c62019-01-02 12:24:44 -0800125 cmd.Sandbox = ninjaSandbox
Dan Willemsene0879fc2017-08-04 15:06:27 -0700126 if config.HasKatiSuffix() {
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500127 // Reads and executes a shell script from Kati that sets/unsets the
128 // environment Ninja runs in.
Dan Willemsene0879fc2017-08-04 15:06:27 -0700129 cmd.Environment.AppendFromKati(config.KatiEnvFile())
130 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700131
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900132 switch config.NinjaWeightListSource() {
133 case NINJA_LOG:
134 useNinjaBuildLog(ctx, config, cmd)
135 case EVENLY_DISTRIBUTED:
136 // pass empty weight list means ninja considers every tasks's weight as 1(default value).
137 cmd.Args = append(cmd.Args, "-o", "usesweightlist=/dev/null")
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900138 case EXTERNAL_FILE:
Jeongik Chae114e602023-03-19 00:12:39 +0900139 fallthrough
140 case HINT_FROM_SOONG:
141 // The weight list is already copied/generated.
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900142 ninjaWeightListPath := filepath.Join(config.OutDir(), ninjaWeightListFileName)
143 cmd.Args = append(cmd.Args, "-o", "usesweightlist="+ninjaWeightListPath)
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900144 }
145
Dan Willemsen1e704462016-08-21 15:17:17 -0700146 // Allow both NINJA_ARGS and NINJA_EXTRA_ARGS, since both have been
147 // used in the past to specify extra ninja arguments.
Dan Willemsen269a8c72017-05-03 17:15:47 -0700148 if extra, ok := cmd.Environment.Get("NINJA_ARGS"); ok {
149 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -0700150 }
Dan Willemsen269a8c72017-05-03 17:15:47 -0700151 if extra, ok := cmd.Environment.Get("NINJA_EXTRA_ARGS"); ok {
152 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -0700153 }
154
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700155 ninjaHeartbeatDuration := time.Minute * 5
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500156 // Get the ninja heartbeat interval from the environment before it's filtered away later.
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700157 if overrideText, ok := cmd.Environment.Get("NINJA_HEARTBEAT_INTERVAL"); ok {
158 // For example, "1m"
159 overrideDuration, err := time.ParseDuration(overrideText)
160 if err == nil && overrideDuration.Seconds() > 0 {
161 ninjaHeartbeatDuration = overrideDuration
162 }
163 }
Dan Willemsene3336352020-01-02 19:10:38 -0800164
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500165 // Filter the environment, as ninja does not rebuild files when environment
166 // variables change.
Dan Willemsene3336352020-01-02 19:10:38 -0800167 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500168 // Anything listed here must not change the output of rules/actions when the
169 // value changes, otherwise incremental builds may be unsafe. Vars
170 // explicitly set to stable values elsewhere in soong_ui are fine.
Dan Willemsene3336352020-01-02 19:10:38 -0800171 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500172 // For the majority of cases, either Soong or the makefiles should be
173 // replicating any necessary environment variables in the command line of
174 // each action that needs it.
Dan Willemsen260db532020-01-02 20:12:09 -0800175 if cmd.Environment.IsEnvTrue("ALLOW_NINJA_ENV") {
176 ctx.Println("Allowing all environment variables during ninja; incremental builds may be unsafe.")
177 } else {
Dan Willemsene3336352020-01-02 19:10:38 -0800178 cmd.Environment.Allow(append([]string{
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500179 // Set the path to a symbolizer (e.g. llvm-symbolizer) so ASAN-based
180 // tools can symbolize crashes.
Dan Willemsene3336352020-01-02 19:10:38 -0800181 "ASAN_SYMBOLIZER_PATH",
182 "HOME",
183 "JAVA_HOME",
184 "LANG",
185 "LC_MESSAGES",
186 "OUT_DIR",
187 "PATH",
188 "PWD",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500189 // https://docs.python.org/3/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE
Dan Willemsene3336352020-01-02 19:10:38 -0800190 "PYTHONDONTWRITEBYTECODE",
191 "TMPDIR",
192 "USER",
193
194 // TODO: remove these carefully
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500195 // Options for the address sanitizer.
Dan Willemsen7da04292020-01-04 13:58:54 -0800196 "ASAN_OPTIONS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500197 // The list of Android app modules to be built in an unbundled manner.
Dan Willemsene3336352020-01-02 19:10:38 -0800198 "TARGET_BUILD_APPS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500199 // The variant of the product being built. e.g. eng, userdebug, debug.
Dan Willemsene3336352020-01-02 19:10:38 -0800200 "TARGET_BUILD_VARIANT",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500201 // The product name of the product being built, e.g. aosp_arm, aosp_flame.
Dan Willemsene3336352020-01-02 19:10:38 -0800202 "TARGET_PRODUCT",
Dan Willemsen5cacfe12020-01-06 12:25:40 -0800203 // b/147197813 - used by art-check-debug-apex-gen
204 "EMMA_INSTRUMENT_FRAMEWORK",
Dan Willemsene3336352020-01-02 19:10:38 -0800205
Dan Willemsene3336352020-01-02 19:10:38 -0800206 // RBE client
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400207 "RBE_compare",
andusyu240660d2022-01-20 14:00:58 -0500208 "RBE_num_local_reruns",
209 "RBE_num_remote_reruns",
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400210 "RBE_exec_root",
211 "RBE_exec_strategy",
212 "RBE_invocation_id",
213 "RBE_log_dir",
Kousik Kumarc3a22d82021-03-17 14:19:27 -0400214 "RBE_num_retries_if_mismatched",
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400215 "RBE_platform",
216 "RBE_remote_accept_cache",
217 "RBE_remote_update_cache",
218 "RBE_server_address",
219 // TODO: remove old FLAG_ variables.
Kousik Kumarade12e72020-01-09 08:52:59 -0800220 "FLAG_compare",
Dan Willemsene3336352020-01-02 19:10:38 -0800221 "FLAG_exec_root",
222 "FLAG_exec_strategy",
223 "FLAG_invocation_id",
224 "FLAG_log_dir",
225 "FLAG_platform",
Kousik Kumar0f095e12020-01-28 10:48:46 -0800226 "FLAG_remote_accept_cache",
227 "FLAG_remote_update_cache",
Dan Willemsene3336352020-01-02 19:10:38 -0800228 "FLAG_server_address",
229
230 // ccache settings
231 "CCACHE_COMPILERCHECK",
232 "CCACHE_SLOPPINESS",
233 "CCACHE_BASEDIR",
234 "CCACHE_CPP2",
John Eckerdal974b0e82020-02-04 15:59:37 +0100235 "CCACHE_DIR",
Yi Kong6adf2582022-04-17 15:01:06 +0800236
237 // LLVM compiler wrapper options
238 "TOOLCHAIN_RUSAGE_OUTPUT",
Dan Willemsene3336352020-01-02 19:10:38 -0800239 }, config.BuildBrokenNinjaUsesEnvVars()...)...)
240 }
241
242 cmd.Environment.Set("DIST_DIR", config.DistDir())
243 cmd.Environment.Set("SHELL", "/bin/bash")
244
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500245 // Print the environment variables that Ninja is operating in.
Dan Willemsene3336352020-01-02 19:10:38 -0800246 ctx.Verboseln("Ninja environment: ")
247 envVars := cmd.Environment.Environ()
248 sort.Strings(envVars)
249 for _, envVar := range envVars {
250 ctx.Verbosef(" %s", envVar)
251 }
252
Spandan Das2db59da2023-02-16 18:31:43 +0000253 // Write the env vars available during ninja execution to a file
254 ninjaEnvVars := cmd.Environment.AsMap()
255 data, err := shared.EnvFileContents(ninjaEnvVars)
256 if err != nil {
257 ctx.Panicf("Could not parse environment variables for ninja run %s", err)
258 }
259 // Write the file in every single run. This is fine because
260 // 1. It is not a dep of Soong analysis, so will not retrigger Soong analysis.
261 // 2. Is is fairly lightweight (~1Kb)
262 ninjaEnvVarsFile := shared.JoinPath(config.SoongOutDir(), ninjaEnvFileName)
263 err = os.WriteFile(ninjaEnvVarsFile, data, 0666)
264 if err != nil {
265 ctx.Panicf("Could not write ninja environment file %s", err)
266 }
267
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500268 // Poll the Ninja log for updates regularly based on the heartbeat
269 // frequency. If it isn't updated enough, then we want to surface the
270 // possibility that Ninja is stuck, to the user.
Jeff Gastona6697e82017-06-13 12:51:50 -0700271 done := make(chan struct{})
272 defer close(done)
273 ticker := time.NewTicker(ninjaHeartbeatDuration)
274 defer ticker.Stop()
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500275 ninjaChecker := &ninjaStucknessChecker{
Jeongik Cha96d62272023-03-17 01:53:11 +0900276 logPath: filepath.Join(config.OutDir(), ninjaLogFileName),
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500277 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700278 go func() {
Jeff Gastona6697e82017-06-13 12:51:50 -0700279 for {
280 select {
281 case <-ticker.C:
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500282 ninjaChecker.check(ctx, config)
Jeff Gastona6697e82017-06-13 12:51:50 -0700283 case <-done:
284 return
285 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700286 }
287 }()
288
Dan Willemsen7f30c072019-01-02 12:50:49 -0800289 ctx.Status.Status("Starting ninja...")
Colin Cross7b97ecd2019-06-19 13:17:59 -0700290 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700291}
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700292
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500293// A simple struct for checking if Ninja gets stuck, using timestamps.
294type ninjaStucknessChecker struct {
295 logPath string
296 prevModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700297}
298
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500299// Check that a file has been modified since the last time it was checked. If
300// the mod time hasn't changed, then assume that Ninja got stuck, and print
301// diagnostics for debugging.
302func (c *ninjaStucknessChecker) check(ctx Context, config Config) {
303 info, err := os.Stat(c.logPath)
304 var newModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700305 if err == nil {
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500306 newModTime = info.ModTime()
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700307 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500308 if newModTime == c.prevModTime {
309 // The Ninja file hasn't been modified since the last time it was
310 // checked, so Ninja could be stuck. Output some diagnostics.
311 ctx.Verbosef("ninja may be stuck; last update to %v was %v. dumping process tree...", c.logPath, newModTime)
312
313 // The "pstree" command doesn't exist on Mac, but "pstree" on Linux
314 // gives more convenient output than "ps" So, we try pstree first, and
315 // ps second
316 commandText := fmt.Sprintf("pstree -pal %v || ps -ef", os.Getpid())
317
318 cmd := Command(ctx, config, "dump process tree", "bash", "-c", commandText)
319 output := cmd.CombinedOutputOrFatal()
320 ctx.Verbose(string(output))
321
322 ctx.Verbosef("done\n")
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700323 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500324 c.prevModTime = newModTime
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700325}