blob: 5961c4525563c156a342b347c4ec4d60671e3752 [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
Nan Zhang17f27672018-12-12 16:01:49 -080026 "android/soong/ui/metrics"
Dan Willemsenb82471a2018-05-17 16:37:09 -070027 "android/soong/ui/status"
Dan Willemsen1e704462016-08-21 15:17:17 -070028)
29
Jingwen Chen9d1cb492020-11-17 06:52:28 -050030// Constructs and runs the Ninja command line with a restricted set of
31// environment variables. It's important to restrict the environment Ninja runs
32// for hermeticity reasons, and to avoid spurious rebuilds.
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010033func runNinjaForBuild(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -080034 ctx.BeginTrace(metrics.PrimaryNinja, "ninja")
Dan Willemsend9f6fa22016-08-21 15:17:17 -070035 defer ctx.EndTrace()
36
Jingwen Chen9d1cb492020-11-17 06:52:28 -050037 // Sets up the FIFO status updater that reads the Ninja protobuf output, and
38 // translates it to the soong_ui status output, displaying real-time
39 // progress of the build.
Dan Willemsenb82471a2018-05-17 16:37:09 -070040 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -070041 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
42 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -070043
Dan Willemsenf173d592017-04-27 14:28:00 -070044 executable := config.PrebuiltBuildTool("ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -070045 args := []string{
46 "-d", "keepdepfile",
Dan Willemsen6d3cad92020-03-12 10:30:35 -070047 "-d", "keeprsp",
Dan Willemsen08218222020-05-18 14:02:02 -070048 "-d", "stats",
Dan Willemsen02736672018-07-17 17:54:31 -070049 "--frontend_file", fifo,
Dan Willemsen1e704462016-08-21 15:17:17 -070050 }
51
52 args = append(args, config.NinjaArgs()...)
53
54 var parallel int
Colin Cross9016b912019-11-11 14:57:42 -080055 if config.UseRemoteBuild() {
Dan Willemsen1e704462016-08-21 15:17:17 -070056 parallel = config.RemoteParallel()
57 } else {
58 parallel = config.Parallel()
59 }
60 args = append(args, "-j", strconv.Itoa(parallel))
61 if config.keepGoing != 1 {
62 args = append(args, "-k", strconv.Itoa(config.keepGoing))
63 }
64
65 args = append(args, "-f", config.CombinedNinjaFile())
66
Dan Willemsenf7939332019-01-05 19:31:32 -080067 args = append(args,
Dan Willemsen6587bed2020-04-18 20:25:59 -070068 "-o", "usesphonyoutputs=yes",
Dan Willemsenf7939332019-01-05 19:31:32 -080069 "-w", "dupbuild=err",
70 "-w", "missingdepfile=err")
Dan Willemsen1e704462016-08-21 15:17:17 -070071
Dan Willemsen269a8c72017-05-03 17:15:47 -070072 cmd := Command(ctx, config, "ninja", executable, args...)
Jingwen Chen9d1cb492020-11-17 06:52:28 -050073
74 // Set up the nsjail sandbox Ninja runs in.
Dan Willemsen63663c62019-01-02 12:24:44 -080075 cmd.Sandbox = ninjaSandbox
Dan Willemsene0879fc2017-08-04 15:06:27 -070076 if config.HasKatiSuffix() {
Jingwen Chen9d1cb492020-11-17 06:52:28 -050077 // Reads and executes a shell script from Kati that sets/unsets the
78 // environment Ninja runs in.
Dan Willemsene0879fc2017-08-04 15:06:27 -070079 cmd.Environment.AppendFromKati(config.KatiEnvFile())
80 }
Dan Willemsen1e704462016-08-21 15:17:17 -070081
82 // Allow both NINJA_ARGS and NINJA_EXTRA_ARGS, since both have been
83 // used in the past to specify extra ninja arguments.
Dan Willemsen269a8c72017-05-03 17:15:47 -070084 if extra, ok := cmd.Environment.Get("NINJA_ARGS"); ok {
85 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -070086 }
Dan Willemsen269a8c72017-05-03 17:15:47 -070087 if extra, ok := cmd.Environment.Get("NINJA_EXTRA_ARGS"); ok {
88 cmd.Args = append(cmd.Args, strings.Fields(extra)...)
Dan Willemsen1e704462016-08-21 15:17:17 -070089 }
90
Jeff Gaston809cc6f2017-05-25 15:44:36 -070091 ninjaHeartbeatDuration := time.Minute * 5
Jingwen Chen9d1cb492020-11-17 06:52:28 -050092 // Get the ninja heartbeat interval from the environment before it's filtered away later.
Jeff Gaston809cc6f2017-05-25 15:44:36 -070093 if overrideText, ok := cmd.Environment.Get("NINJA_HEARTBEAT_INTERVAL"); ok {
94 // For example, "1m"
95 overrideDuration, err := time.ParseDuration(overrideText)
96 if err == nil && overrideDuration.Seconds() > 0 {
97 ninjaHeartbeatDuration = overrideDuration
98 }
99 }
Dan Willemsene3336352020-01-02 19:10:38 -0800100
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500101 // Filter the environment, as ninja does not rebuild files when environment
102 // variables change.
Dan Willemsene3336352020-01-02 19:10:38 -0800103 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500104 // Anything listed here must not change the output of rules/actions when the
105 // value changes, otherwise incremental builds may be unsafe. Vars
106 // explicitly set to stable values elsewhere in soong_ui are fine.
Dan Willemsene3336352020-01-02 19:10:38 -0800107 //
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500108 // For the majority of cases, either Soong or the makefiles should be
109 // replicating any necessary environment variables in the command line of
110 // each action that needs it.
Dan Willemsen260db532020-01-02 20:12:09 -0800111 if cmd.Environment.IsEnvTrue("ALLOW_NINJA_ENV") {
112 ctx.Println("Allowing all environment variables during ninja; incremental builds may be unsafe.")
113 } else {
Dan Willemsene3336352020-01-02 19:10:38 -0800114 cmd.Environment.Allow(append([]string{
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500115 // Set the path to a symbolizer (e.g. llvm-symbolizer) so ASAN-based
116 // tools can symbolize crashes.
Dan Willemsene3336352020-01-02 19:10:38 -0800117 "ASAN_SYMBOLIZER_PATH",
118 "HOME",
119 "JAVA_HOME",
120 "LANG",
121 "LC_MESSAGES",
122 "OUT_DIR",
123 "PATH",
124 "PWD",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500125 // https://docs.python.org/3/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE
Dan Willemsene3336352020-01-02 19:10:38 -0800126 "PYTHONDONTWRITEBYTECODE",
127 "TMPDIR",
128 "USER",
129
130 // TODO: remove these carefully
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500131 // Options for the address sanitizer.
Dan Willemsen7da04292020-01-04 13:58:54 -0800132 "ASAN_OPTIONS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500133 // The list of Android app modules to be built in an unbundled manner.
Dan Willemsene3336352020-01-02 19:10:38 -0800134 "TARGET_BUILD_APPS",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500135 // The variant of the product being built. e.g. eng, userdebug, debug.
Dan Willemsene3336352020-01-02 19:10:38 -0800136 "TARGET_BUILD_VARIANT",
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500137 // The product name of the product being built, e.g. aosp_arm, aosp_flame.
Dan Willemsene3336352020-01-02 19:10:38 -0800138 "TARGET_PRODUCT",
Dan Willemsen5cacfe12020-01-06 12:25:40 -0800139 // b/147197813 - used by art-check-debug-apex-gen
140 "EMMA_INSTRUMENT_FRAMEWORK",
Dan Willemsene3336352020-01-02 19:10:38 -0800141
Dan Willemsene3336352020-01-02 19:10:38 -0800142 // RBE client
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400143 "RBE_compare",
144 "RBE_exec_root",
145 "RBE_exec_strategy",
146 "RBE_invocation_id",
147 "RBE_log_dir",
Kousik Kumarc3a22d82021-03-17 14:19:27 -0400148 "RBE_num_retries_if_mismatched",
Ola Rozenfeld3992e372020-03-19 20:04:13 -0400149 "RBE_platform",
150 "RBE_remote_accept_cache",
151 "RBE_remote_update_cache",
152 "RBE_server_address",
153 // TODO: remove old FLAG_ variables.
Kousik Kumarade12e72020-01-09 08:52:59 -0800154 "FLAG_compare",
Dan Willemsene3336352020-01-02 19:10:38 -0800155 "FLAG_exec_root",
156 "FLAG_exec_strategy",
157 "FLAG_invocation_id",
158 "FLAG_log_dir",
159 "FLAG_platform",
Kousik Kumar0f095e12020-01-28 10:48:46 -0800160 "FLAG_remote_accept_cache",
161 "FLAG_remote_update_cache",
Dan Willemsene3336352020-01-02 19:10:38 -0800162 "FLAG_server_address",
163
164 // ccache settings
165 "CCACHE_COMPILERCHECK",
166 "CCACHE_SLOPPINESS",
167 "CCACHE_BASEDIR",
168 "CCACHE_CPP2",
John Eckerdal974b0e82020-02-04 15:59:37 +0100169 "CCACHE_DIR",
Dan Willemsene3336352020-01-02 19:10:38 -0800170 }, config.BuildBrokenNinjaUsesEnvVars()...)...)
171 }
172
173 cmd.Environment.Set("DIST_DIR", config.DistDir())
174 cmd.Environment.Set("SHELL", "/bin/bash")
175
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500176 // Print the environment variables that Ninja is operating in.
Dan Willemsene3336352020-01-02 19:10:38 -0800177 ctx.Verboseln("Ninja environment: ")
178 envVars := cmd.Environment.Environ()
179 sort.Strings(envVars)
180 for _, envVar := range envVars {
181 ctx.Verbosef(" %s", envVar)
182 }
183
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500184 // Poll the Ninja log for updates regularly based on the heartbeat
185 // frequency. If it isn't updated enough, then we want to surface the
186 // possibility that Ninja is stuck, to the user.
Jeff Gastona6697e82017-06-13 12:51:50 -0700187 done := make(chan struct{})
188 defer close(done)
189 ticker := time.NewTicker(ninjaHeartbeatDuration)
190 defer ticker.Stop()
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500191 ninjaChecker := &ninjaStucknessChecker{
192 logPath: filepath.Join(config.OutDir(), ".ninja_log"),
193 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700194 go func() {
Jeff Gastona6697e82017-06-13 12:51:50 -0700195 for {
196 select {
197 case <-ticker.C:
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500198 ninjaChecker.check(ctx, config)
Jeff Gastona6697e82017-06-13 12:51:50 -0700199 case <-done:
200 return
201 }
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700202 }
203 }()
204
Dan Willemsen7f30c072019-01-02 12:50:49 -0800205 ctx.Status.Status("Starting ninja...")
Colin Cross7b97ecd2019-06-19 13:17:59 -0700206 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700207}
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700208
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500209// A simple struct for checking if Ninja gets stuck, using timestamps.
210type ninjaStucknessChecker struct {
211 logPath string
212 prevModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700213}
214
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500215// Check that a file has been modified since the last time it was checked. If
216// the mod time hasn't changed, then assume that Ninja got stuck, and print
217// diagnostics for debugging.
218func (c *ninjaStucknessChecker) check(ctx Context, config Config) {
219 info, err := os.Stat(c.logPath)
220 var newModTime time.Time
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700221 if err == nil {
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500222 newModTime = info.ModTime()
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700223 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500224 if newModTime == c.prevModTime {
225 // The Ninja file hasn't been modified since the last time it was
226 // checked, so Ninja could be stuck. Output some diagnostics.
227 ctx.Verbosef("ninja may be stuck; last update to %v was %v. dumping process tree...", c.logPath, newModTime)
228
229 // The "pstree" command doesn't exist on Mac, but "pstree" on Linux
230 // gives more convenient output than "ps" So, we try pstree first, and
231 // ps second
232 commandText := fmt.Sprintf("pstree -pal %v || ps -ef", os.Getpid())
233
234 cmd := Command(ctx, config, "dump process tree", "bash", "-c", commandText)
235 output := cmd.CombinedOutputOrFatal()
236 ctx.Verbose(string(output))
237
238 ctx.Verbosef("done\n")
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700239 }
Jingwen Chen9d1cb492020-11-17 06:52:28 -0500240 c.prevModTime = newModTime
Jeff Gaston809cc6f2017-05-25 15:44:36 -0700241}