blob: 4c26d3ea5accefa87107b731ae26183771f66d7f [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 (
Ramy Medhat0fc67eb2020-08-12 01:26:23 -040018 "fmt"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080019 "os"
Dan Willemsen1e704462016-08-21 15:17:17 -070020 "path/filepath"
21 "runtime"
22 "strconv"
23 "strings"
Nan Zhang2e6a4ff2018-02-14 13:27:26 -080024 "time"
Jeff Gastonefc1b412017-03-29 17:29:06 -070025
26 "android/soong/shared"
Kousik Kumarec478642020-09-21 13:39:24 -040027
Dan Willemsen4591b642021-05-24 14:24:12 -070028 "google.golang.org/protobuf/proto"
Patrice Arruda96850362020-08-11 20:41:11 +000029
30 smpb "android/soong/ui/metrics/metrics_proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070031)
32
33type Config struct{ *configImpl }
34
35type configImpl struct {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020036 // Some targets that are implemented in soong_build
37 // (bp2build, json-module-graph) are not here and have their own bits below.
Colin Cross28f527c2019-11-26 16:19:04 -080038 arguments []string
39 goma bool
40 environ *Environment
41 distDir string
42 buildDateTime string
Dan Willemsen1e704462016-08-21 15:17:17 -070043
44 // From the arguments
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020045 parallel int
46 keepGoing int
47 verbose bool
48 checkbuild bool
49 dist bool
50 jsonModuleGraph bool
51 bp2build bool
Lukacs T. Berki3a821692021-09-06 17:08:02 +020052 queryview bool
Lukacs T. Berkic6012f32021-09-06 18:31:46 +020053 soongDocs bool
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020054 skipConfig bool
55 skipKati bool
56 skipKatiNinja bool
57 skipSoong bool
58 skipNinja bool
59 skipSoongTests bool
Dan Willemsen1e704462016-08-21 15:17:17 -070060
61 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070062 katiArgs []string
63 ninjaArgs []string
64 katiSuffix string
65 targetDevice string
66 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +000067 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -070068
Dan Willemsen2bb82d02019-12-27 09:35:42 -080069 // Autodetected
70 totalRAM uint64
71
Dan Willemsene3336352020-01-02 19:10:38 -080072 brokenDupRules bool
73 brokenUsesNetwork bool
74 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -070075
76 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +000077
78 useBazel bool
79
80 // During Bazel execution, Bazel cannot write outside OUT_DIR.
81 // So if DIST_DIR is set to an external dir (outside of OUT_DIR), we need to rig it temporarily and then migrate files at the end of the build.
82 riggedDistDirForBazel string
Colin Crossf3bdbcb2021-06-01 11:43:55 -070083
84 // Set by multiproduct_kati
85 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -070086
87 metricsUploader string
Dan Willemsen1e704462016-08-21 15:17:17 -070088}
89
Dan Willemsenc2af0be2017-01-20 14:10:01 -080090const srcDirFileCheck = "build/soong/root.bp"
91
Patrice Arruda9450d0b2019-07-08 11:06:46 -070092var buildFiles = []string{"Android.mk", "Android.bp"}
93
Patrice Arruda13848222019-04-22 17:12:02 -070094type BuildAction uint
95
96const (
97 // Builds all of the modules and their dependencies of a specified directory, relative to the root
98 // directory of the source tree.
99 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
100
101 // Builds all of the modules and their dependencies of a list of specified directories. All specified
102 // directories are relative to the root directory of the source tree.
103 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700104
105 // Build a list of specified modules. If none was specified, simply build the whole source tree.
106 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700107)
108
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400109type bazelBuildMode int
110
111// Bazel-related build modes.
112const (
113 // Don't use bazel at all.
114 noBazel bazelBuildMode = iota
115
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400116 // Generate synthetic build files and incorporate these files into a build which
117 // partially uses Bazel. Build metadata may come from Android.bp or BUILD files.
118 mixedBuild
119)
120
Patrice Arruda13848222019-04-22 17:12:02 -0700121// checkTopDir validates that the current directory is at the root directory of the source tree.
122func checkTopDir(ctx Context) {
123 if _, err := os.Stat(srcDirFileCheck); err != nil {
124 if os.IsNotExist(err) {
125 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
126 }
127 ctx.Fatalln("Error verifying tree state:", err)
128 }
129}
130
Dan Willemsen1e704462016-08-21 15:17:17 -0700131func NewConfig(ctx Context, args ...string) Config {
132 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000133 environ: OsEnvironment(),
134 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700135 }
136
Patrice Arruda90109172020-07-28 18:07:27 +0000137 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700138 ret.parallel = runtime.NumCPU() + 2
139 ret.keepGoing = 1
140
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800141 ret.totalRAM = detectTotalRAM(ctx)
142
Dan Willemsen9b587492017-07-10 22:13:00 -0700143 ret.parseArgs(ctx, args)
144
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800145 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700146 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
147 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
148 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800149 outDir := "out"
150 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
151 if wd, err := os.Getwd(); err != nil {
152 ctx.Fatalln("Failed to get working directory:", err)
153 } else {
154 outDir = filepath.Join(baseDir, filepath.Base(wd))
155 }
156 }
157 ret.environ.Set("OUT_DIR", outDir)
158 }
159
Dan Willemsen2d31a442018-10-20 21:33:41 -0700160 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
161 ret.distDir = filepath.Clean(distDir)
162 } else {
163 ret.distDir = filepath.Join(ret.OutDir(), "dist")
164 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700165
Spandan Das05063612021-06-25 01:39:04 +0000166 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
167 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
168 }
169
Dan Willemsen1e704462016-08-21 15:17:17 -0700170 ret.environ.Unset(
171 // We're already using it
172 "USE_SOONG_UI",
173
174 // We should never use GOROOT/GOPATH from the shell environment
175 "GOROOT",
176 "GOPATH",
177
178 // These should only come from Soong, not the environment.
179 "CLANG",
180 "CLANG_CXX",
181 "CCC_CC",
182 "CCC_CXX",
183
184 // Used by the goma compiler wrapper, but should only be set by
185 // gomacc
186 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800187
188 // We handle this above
189 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700190
Dan Willemsen2d31a442018-10-20 21:33:41 -0700191 // This is handled above too, and set for individual commands later
192 "DIST_DIR",
193
Dan Willemsen68a09852017-04-18 13:56:57 -0700194 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000195 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700196 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700197 "DISPLAY",
198 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700199 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700200 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700201
202 // Drop make flags
203 "MAKEFLAGS",
204 "MAKELEVEL",
205 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700206
207 // Set in envsetup.sh, reset in makefiles
208 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700209
210 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
211 "ANDROID_BUILD_TOP",
212 "ANDROID_HOST_OUT",
213 "ANDROID_PRODUCT_OUT",
214 "ANDROID_HOST_OUT_TESTCASES",
215 "ANDROID_TARGET_OUT_TESTCASES",
216 "ANDROID_TOOLCHAIN",
217 "ANDROID_TOOLCHAIN_2ND_ARCH",
218 "ANDROID_DEV_SCRIPTS",
219 "ANDROID_EMULATOR_PREBUILTS",
220 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700221 )
222
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400223 if ret.UseGoma() || ret.ForceUseGoma() {
224 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
225 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400226 }
227
Dan Willemsen1e704462016-08-21 15:17:17 -0700228 // Tell python not to spam the source tree with .pyc files.
229 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
230
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400231 tmpDir := absPath(ctx, ret.TempDir())
232 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800233
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700234 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
235 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
236 "llvm-binutils-stable/llvm-symbolizer")
237 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
238
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800239 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700240 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800241
Yu Liu6e13b402021-07-27 14:29:06 -0700242 srcDir := absPath(ctx, ".")
243 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700244 ctx.Println("You are building in a directory whose absolute path contains a space character:")
245 ctx.Println()
246 ctx.Printf("%q\n", srcDir)
247 ctx.Println()
248 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700249 }
250
Yu Liu6e13b402021-07-27 14:29:06 -0700251 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
252
Dan Willemsendb8457c2017-05-12 16:38:17 -0700253 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700254 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
255 ctx.Println()
256 ctx.Printf("%q\n", outDir)
257 ctx.Println()
258 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700259 }
260
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000261 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700262 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
263 ctx.Println()
264 ctx.Printf("%q\n", distDir)
265 ctx.Println()
266 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700267 }
268
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700269 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000270 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
271 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100272 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700273 javaHome := func() string {
274 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
275 return override
276 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000277 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
278 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN is no longer supported. An OpenJDK 11 toolchain is now the global default.")
Pete Gillin1f52e932019-10-09 17:10:08 +0100279 }
Pete Gillinabbcdda2019-10-28 16:15:33 +0000280 return java11Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700281 }()
282 absJavaHome := absPath(ctx, javaHome)
283
Dan Willemsened869522018-01-08 14:58:46 -0800284 ret.configureLocale(ctx)
285
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700286 newPath := []string{filepath.Join(absJavaHome, "bin")}
287 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
288 newPath = append(newPath, path)
289 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100290
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700291 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
292 ret.environ.Set("JAVA_HOME", absJavaHome)
293 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000294 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
295 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100296 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700297 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
298
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800299 outDir := ret.OutDir()
300 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800301 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800302 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800303 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800304 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800305 }
Colin Cross28f527c2019-11-26 16:19:04 -0800306
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800307 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
308
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400309 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400310 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400311 ret.environ.Set(k, v)
312 }
313 }
314
Patrice Arruda83842d72020-12-08 19:42:08 +0000315 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800316 if err := os.RemoveAll(bpd); err != nil {
317 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
318 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000319
320 ret.useBazel = ret.environ.IsEnvTrue("USE_BAZEL")
321
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800322 if ret.UseBazel() {
323 if err := os.MkdirAll(bpd, 0777); err != nil {
324 ctx.Fatalf("Failed to create bazel profile directory %q: %v", bpd, err)
325 }
326 }
327
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000328 if ret.UseBazel() {
329 ret.riggedDistDirForBazel = filepath.Join(ret.OutDir(), "dist")
330 } else {
331 // Not rigged
332 ret.riggedDistDirForBazel = ret.distDir
333 }
334
Patrice Arruda96850362020-08-11 20:41:11 +0000335 c := Config{ret}
336 storeConfigMetrics(ctx, c)
337 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700338}
339
Patrice Arruda13848222019-04-22 17:12:02 -0700340// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
341// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700342func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
343 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700344}
345
Patrice Arruda96850362020-08-11 20:41:11 +0000346// storeConfigMetrics selects a set of configuration information and store in
347// the metrics system for further analysis.
348func storeConfigMetrics(ctx Context, config Config) {
349 if ctx.Metrics == nil {
350 return
351 }
352
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400353 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000354
355 s := &smpb.SystemResourceInfo{
356 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
357 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
358 }
359 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000360}
361
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400362func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700363 c := &smpb.BuildConfig{
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400364 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
365 UseGoma: proto.Bool(config.UseGoma()),
366 UseRbe: proto.Bool(config.UseRBE()),
367 BazelAsNinja: proto.Bool(config.UseBazel()),
368 BazelMixedBuild: proto.Bool(config.bazelBuildMode() == mixedBuild),
369 }
Yu Liue737a992021-10-04 13:21:41 -0700370 c.Targets = append(c.Targets, config.arguments...)
371
372 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400373}
374
Patrice Arruda13848222019-04-22 17:12:02 -0700375// getConfigArgs processes the command arguments based on the build action and creates a set of new
376// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700377func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700378 // The next block of code verifies that the current directory is the root directory of the source
379 // tree. It then finds the relative path of dir based on the root directory of the source tree
380 // and verify that dir is inside of the source tree.
381 checkTopDir(ctx)
382 topDir, err := os.Getwd()
383 if err != nil {
384 ctx.Fatalf("Error retrieving top directory: %v", err)
385 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700386 dir, err = filepath.EvalSymlinks(dir)
387 if err != nil {
388 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
389 }
Patrice Arruda13848222019-04-22 17:12:02 -0700390 dir, err = filepath.Abs(dir)
391 if err != nil {
392 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
393 }
394 relDir, err := filepath.Rel(topDir, dir)
395 if err != nil {
396 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
397 }
398 // If there are ".." in the path, it's not in the source tree.
399 if strings.Contains(relDir, "..") {
400 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
401 }
402
403 configArgs := args[:]
404
405 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
406 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
407 targetNamePrefix := "MODULES-IN-"
408 if inList("GET-INSTALL-PATH", configArgs) {
409 targetNamePrefix = "GET-INSTALL-PATH-IN-"
410 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
411 }
412
Patrice Arruda13848222019-04-22 17:12:02 -0700413 var targets []string
414
415 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700416 case BUILD_MODULES:
417 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700418 case BUILD_MODULES_IN_A_DIRECTORY:
419 // If dir is the root source tree, all the modules are built of the source tree are built so
420 // no need to find the build file.
421 if topDir == dir {
422 break
423 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700424
Patrice Arruda13848222019-04-22 17:12:02 -0700425 buildFile := findBuildFile(ctx, relDir)
426 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700427 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700428 }
Patrice Arruda13848222019-04-22 17:12:02 -0700429 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
430 case BUILD_MODULES_IN_DIRECTORIES:
431 newConfigArgs, dirs := splitArgs(configArgs)
432 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700433 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700434 }
435
436 // Tidy only override all other specified targets.
437 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
438 if tidyOnly == "true" || tidyOnly == "1" {
439 configArgs = append(configArgs, "tidy_only")
440 } else {
441 configArgs = append(configArgs, targets...)
442 }
443
444 return configArgs
445}
446
447// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
448func convertToTarget(dir string, targetNamePrefix string) string {
449 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
450}
451
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700452// hasBuildFile returns true if dir contains an Android build file.
453func hasBuildFile(ctx Context, dir string) bool {
454 for _, buildFile := range buildFiles {
455 _, err := os.Stat(filepath.Join(dir, buildFile))
456 if err == nil {
457 return true
458 }
459 if !os.IsNotExist(err) {
460 ctx.Fatalf("Error retrieving the build file stats: %v", err)
461 }
462 }
463 return false
464}
465
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700466// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
467// in the current and any sub directory of dir. If a build file is not found, traverse the path
468// up by one directory and repeat again until either a build file is found or reached to the root
469// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
470// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700471func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700472 // If the string is empty or ".", assume it is top directory of the source tree.
473 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700474 return ""
475 }
476
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700477 found := false
478 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
479 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
480 if err != nil {
481 return err
482 }
483 if found {
484 return filepath.SkipDir
485 }
486 if info.IsDir() {
487 return nil
488 }
489 for _, buildFile := range buildFiles {
490 if info.Name() == buildFile {
491 found = true
492 return filepath.SkipDir
493 }
494 }
495 return nil
496 })
497 if err != nil {
498 ctx.Fatalf("Error finding Android build file: %v", err)
499 }
500
501 if found {
502 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700503 }
504 }
505
506 return ""
507}
508
509// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
510func splitArgs(args []string) (newArgs []string, dirs []string) {
511 specialArgs := map[string]bool{
512 "showcommands": true,
513 "snod": true,
514 "dist": true,
515 "checkbuild": true,
516 }
517
518 newArgs = []string{}
519 dirs = []string{}
520
521 for _, arg := range args {
522 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
523 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
524 newArgs = append(newArgs, arg)
525 continue
526 }
527
528 if _, ok := specialArgs[arg]; ok {
529 newArgs = append(newArgs, arg)
530 continue
531 }
532
533 dirs = append(dirs, arg)
534 }
535
536 return newArgs, dirs
537}
538
539// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
540// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
541// source root tree where the build action command was invoked. Each directory is validated if the
542// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700543func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700544 for _, dir := range dirs {
545 // The directory may have specified specific modules to build. ":" is the separator to separate
546 // the directory and the list of modules.
547 s := strings.Split(dir, ":")
548 l := len(s)
549 if l > 2 { // more than one ":" was specified.
550 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
551 }
552
553 dir = filepath.Join(relDir, s[0])
554 if _, err := os.Stat(dir); err != nil {
555 ctx.Fatalf("couldn't find directory %s", dir)
556 }
557
558 // Verify that if there are any targets specified after ":". Each target is separated by ",".
559 var newTargets []string
560 if l == 2 && s[1] != "" {
561 newTargets = strings.Split(s[1], ",")
562 if inList("", newTargets) {
563 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
564 }
565 }
566
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700567 // If there are specified targets to build in dir, an android build file must exist for the one
568 // shot build. For the non-targets case, find the appropriate build file and build all the
569 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700570 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700571 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700572 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
573 }
574 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700575 buildFile := findBuildFile(ctx, dir)
576 if buildFile == "" {
577 ctx.Fatalf("Build file not found for %s directory", dir)
578 }
579 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700580 }
581
Patrice Arruda13848222019-04-22 17:12:02 -0700582 targets = append(targets, newTargets...)
583 }
584
Dan Willemsence41e942019-07-29 23:39:30 -0700585 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700586}
587
Dan Willemsen9b587492017-07-10 22:13:00 -0700588func (c *configImpl) parseArgs(ctx Context, args []string) {
589 for i := 0; i < len(args); i++ {
590 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100591 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700592 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200593 } else if arg == "--empty-ninja-file" {
594 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100595 } else if arg == "--skip-ninja" {
596 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700597 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700598 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
599 // but it does run a Kati ninja file if the .kati_enabled marker file was created
600 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000601 c.skipConfig = true
602 c.skipKati = true
603 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100604 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000605 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100606 } else if arg == "--soong-only" {
607 c.skipKati = true
608 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200609 } else if arg == "--config-only" {
610 c.skipKati = true
611 c.skipKatiNinja = true
612 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700613 } else if arg == "--skip-config" {
614 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700615 } else if arg == "--skip-soong-tests" {
616 c.skipSoongTests = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700617 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700618 parseArgNum := func(def int) int {
619 if len(arg) > 2 {
620 p, err := strconv.ParseUint(arg[2:], 10, 31)
621 if err != nil {
622 ctx.Fatalf("Failed to parse %q: %v", arg, err)
623 }
624 return int(p)
625 } else if i+1 < len(args) {
626 p, err := strconv.ParseUint(args[i+1], 10, 31)
627 if err == nil {
628 i++
629 return int(p)
630 }
631 }
632 return def
633 }
634
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700635 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700636 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700637 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700638 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700639 } else {
640 ctx.Fatalln("Unknown option:", arg)
641 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700642 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700643 if k == "OUT_DIR" {
644 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
645 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700646 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700647 } else if arg == "dist" {
648 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200649 } else if arg == "json-module-graph" {
650 c.jsonModuleGraph = true
651 } else if arg == "bp2build" {
652 c.bp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200653 } else if arg == "queryview" {
654 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200655 } else if arg == "soong_docs" {
656 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700657 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700658 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800659 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700660 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700661 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700662 }
663 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700664}
665
Dan Willemsened869522018-01-08 14:58:46 -0800666func (c *configImpl) configureLocale(ctx Context) {
667 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
668 output, err := cmd.Output()
669
670 var locales []string
671 if err == nil {
672 locales = strings.Split(string(output), "\n")
673 } else {
674 // If we're unable to list the locales, let's assume en_US.UTF-8
675 locales = []string{"en_US.UTF-8"}
676 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
677 }
678
679 // gettext uses LANGUAGE, which is passed directly through
680
681 // For LANG and LC_*, only preserve the evaluated version of
682 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800683 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800684 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800685 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800686 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800687 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800688 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800689 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800690 }
691
692 c.environ.UnsetWithPrefix("LC_")
693
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800694 if userLang != "" {
695 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800696 }
697
698 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
699 // for others)
700 if inList("C.UTF-8", locales) {
701 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500702 } else if inList("C.utf8", locales) {
703 // These normalize to the same thing
704 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800705 } else if inList("en_US.UTF-8", locales) {
706 c.environ.Set("LANG", "en_US.UTF-8")
707 } else if inList("en_US.utf8", locales) {
708 // These normalize to the same thing
709 c.environ.Set("LANG", "en_US.UTF-8")
710 } else {
711 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
712 }
713}
714
Dan Willemsen1e704462016-08-21 15:17:17 -0700715func (c *configImpl) Environment() *Environment {
716 return c.environ
717}
718
719func (c *configImpl) Arguments() []string {
720 return c.arguments
721}
722
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200723func (c *configImpl) SoongBuildInvocationNeeded() bool {
724 if c.Dist() {
725 return true
726 }
727
728 if len(c.Arguments()) > 0 {
729 // Explicit targets requested that are not special targets like b2pbuild
730 // or the JSON module graph
731 return true
732 }
733
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200734 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200735 // Command line was empty, the default Ninja target is built
736 return true
737 }
738
739 // build.ninja doesn't need to be generated
740 return false
741}
742
Dan Willemsen1e704462016-08-21 15:17:17 -0700743func (c *configImpl) OutDir() string {
744 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700745 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700746 }
747 return "out"
748}
749
Dan Willemsen8a073a82017-02-04 17:30:44 -0800750func (c *configImpl) DistDir() string {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000751 if c.UseBazel() {
752 return c.riggedDistDirForBazel
753 } else {
754 return c.distDir
755 }
756}
757
758func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700759 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800760}
761
Dan Willemsen1e704462016-08-21 15:17:17 -0700762func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000763 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700764 return c.arguments
765 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700766 return c.ninjaArgs
767}
768
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500769func (c *configImpl) BazelOutDir() string {
770 return filepath.Join(c.OutDir(), "bazel")
771}
772
Dan Willemsen1e704462016-08-21 15:17:17 -0700773func (c *configImpl) SoongOutDir() string {
774 return filepath.Join(c.OutDir(), "soong")
775}
776
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200777func (c *configImpl) PrebuiltOS() string {
778 switch runtime.GOOS {
779 case "linux":
780 return "linux-x86"
781 case "darwin":
782 return "darwin-x86"
783 default:
784 panic("Unknown GOOS")
785 }
786}
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100787
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200788func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -0700789 if c.SkipKatiNinja() {
790 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
791 } else {
792 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
793 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200794}
795
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200796func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100797 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200798}
799
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200800func (c *configImpl) UsedEnvFile(tag string) string {
801 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
802}
803
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200804func (c *configImpl) Bp2BuildMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100805 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200806}
807
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200808func (c *configImpl) SoongDocsHtml() string {
809 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
810}
811
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200812func (c *configImpl) QueryviewMarkerFile() string {
813 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
814}
815
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200816func (c *configImpl) ModuleGraphFile() string {
817 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
818}
819
Jeff Gastonefc1b412017-03-29 17:29:06 -0700820func (c *configImpl) TempDir() string {
821 return shared.TempDirForOutDir(c.SoongOutDir())
822}
823
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700824func (c *configImpl) FileListDir() string {
825 return filepath.Join(c.OutDir(), ".module_paths")
826}
827
Dan Willemsen1e704462016-08-21 15:17:17 -0700828func (c *configImpl) KatiSuffix() string {
829 if c.katiSuffix != "" {
830 return c.katiSuffix
831 }
832 panic("SetKatiSuffix has not been called")
833}
834
Colin Cross37193492017-11-16 17:55:00 -0800835// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
836// user is interested in additional checks at the expense of build time.
837func (c *configImpl) Checkbuild() bool {
838 return c.checkbuild
839}
840
Dan Willemsen8a073a82017-02-04 17:30:44 -0800841func (c *configImpl) Dist() bool {
842 return c.dist
843}
844
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200845func (c *configImpl) JsonModuleGraph() bool {
846 return c.jsonModuleGraph
847}
848
849func (c *configImpl) Bp2Build() bool {
850 return c.bp2build
851}
852
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200853func (c *configImpl) Queryview() bool {
854 return c.queryview
855}
856
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200857func (c *configImpl) SoongDocs() bool {
858 return c.soongDocs
859}
860
Dan Willemsen1e704462016-08-21 15:17:17 -0700861func (c *configImpl) IsVerbose() bool {
862 return c.verbose
863}
864
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000865func (c *configImpl) SkipKati() bool {
866 return c.skipKati
867}
868
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100869func (c *configImpl) SkipKatiNinja() bool {
870 return c.skipKatiNinja
871}
872
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200873func (c *configImpl) SkipSoong() bool {
874 return c.skipSoong
875}
876
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100877func (c *configImpl) SkipNinja() bool {
878 return c.skipNinja
879}
880
Anton Hansson5a7861a2021-06-04 10:09:01 +0100881func (c *configImpl) SetSkipNinja(v bool) {
882 c.skipNinja = v
883}
884
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000885func (c *configImpl) SkipConfig() bool {
886 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -0700887}
888
Dan Willemsen1e704462016-08-21 15:17:17 -0700889func (c *configImpl) TargetProduct() string {
890 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
891 return v
892 }
893 panic("TARGET_PRODUCT is not defined")
894}
895
Dan Willemsen02781d52017-05-12 19:28:13 -0700896func (c *configImpl) TargetDevice() string {
897 return c.targetDevice
898}
899
900func (c *configImpl) SetTargetDevice(device string) {
901 c.targetDevice = device
902}
903
904func (c *configImpl) TargetBuildVariant() string {
905 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
906 return v
907 }
908 panic("TARGET_BUILD_VARIANT is not defined")
909}
910
Dan Willemsen1e704462016-08-21 15:17:17 -0700911func (c *configImpl) KatiArgs() []string {
912 return c.katiArgs
913}
914
915func (c *configImpl) Parallel() int {
916 return c.parallel
917}
918
Colin Cross8b8bec32019-11-15 13:18:43 -0800919func (c *configImpl) HighmemParallel() int {
920 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
921 return i
922 }
923
924 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
925 parallel := c.Parallel()
926 if c.UseRemoteBuild() {
927 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
928 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
929 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
930 // Return 1/16th of the size of the local pool, rounding up.
931 return (parallel + 15) / 16
932 } else if c.totalRAM == 0 {
933 // Couldn't detect the total RAM, don't restrict highmem processes.
934 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -0700935 } else if c.totalRAM <= 16*1024*1024*1024 {
936 // Less than 16GB of ram, restrict to 1 highmem processes
937 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -0800938 } else if c.totalRAM <= 32*1024*1024*1024 {
939 // Less than 32GB of ram, restrict to 2 highmem processes
940 return 2
941 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
942 // If less than 8GB total RAM per process, reduce the number of highmem processes
943 return p
944 }
945 // No restriction on highmem processes
946 return parallel
947}
948
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800949func (c *configImpl) TotalRAM() uint64 {
950 return c.totalRAM
951}
952
Kousik Kumarec478642020-09-21 13:39:24 -0400953// ForceUseGoma determines whether we should override Goma deprecation
954// and use Goma for the current build or not.
955func (c *configImpl) ForceUseGoma() bool {
956 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
957 v = strings.TrimSpace(v)
958 if v != "" && v != "false" {
959 return true
960 }
961 }
962 return false
963}
964
Dan Willemsen1e704462016-08-21 15:17:17 -0700965func (c *configImpl) UseGoma() bool {
966 if v, ok := c.environ.Get("USE_GOMA"); ok {
967 v = strings.TrimSpace(v)
968 if v != "" && v != "false" {
969 return true
970 }
971 }
972 return false
973}
974
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +0900975func (c *configImpl) StartGoma() bool {
976 if !c.UseGoma() {
977 return false
978 }
979
980 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
981 v = strings.TrimSpace(v)
982 if v != "" && v != "false" {
983 return false
984 }
985 }
986 return true
987}
988
Ramy Medhatbbf25672019-07-17 12:30:04 +0000989func (c *configImpl) UseRBE() bool {
990 if v, ok := c.environ.Get("USE_RBE"); ok {
991 v = strings.TrimSpace(v)
992 if v != "" && v != "false" {
993 return true
994 }
995 }
996 return false
997}
998
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800999func (c *configImpl) UseBazel() bool {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001000 return c.useBazel
Patrice Arruda0c1c4562020-11-11 13:01:25 -08001001}
1002
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001003func (c *configImpl) bazelBuildMode() bazelBuildMode {
1004 if c.Environment().IsEnvTrue("USE_BAZEL_ANALYSIS") {
1005 return mixedBuild
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001006 } else {
1007 return noBazel
1008 }
1009}
1010
Ramy Medhatbbf25672019-07-17 12:30:04 +00001011func (c *configImpl) StartRBE() bool {
1012 if !c.UseRBE() {
1013 return false
1014 }
1015
1016 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1017 v = strings.TrimSpace(v)
1018 if v != "" && v != "false" {
1019 return false
1020 }
1021 }
1022 return true
1023}
1024
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001025func (c *configImpl) rbeLogDir() string {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001026 for _, f := range []string{"RBE_log_dir", "FLAG_log_dir"} {
1027 if v, ok := c.environ.Get(f); ok {
1028 return v
1029 }
1030 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001031 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001032 return c.LogsDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001033 }
1034 return c.OutDir()
1035}
1036
1037func (c *configImpl) rbeStatsOutputDir() string {
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001038 for _, f := range []string{"RBE_output_dir", "FLAG_output_dir"} {
1039 if v, ok := c.environ.Get(f); ok {
1040 return v
1041 }
1042 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001043 return c.rbeLogDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001044}
1045
1046func (c *configImpl) rbeLogPath() string {
1047 for _, f := range []string{"RBE_log_path", "FLAG_log_path"} {
1048 if v, ok := c.environ.Get(f); ok {
1049 return v
1050 }
1051 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001052 return fmt.Sprintf("text://%v/reproxy_log.txt", c.rbeLogDir())
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001053}
1054
1055func (c *configImpl) rbeExecRoot() string {
1056 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1057 if v, ok := c.environ.Get(f); ok {
1058 return v
1059 }
1060 }
1061 wd, err := os.Getwd()
1062 if err != nil {
1063 return ""
1064 }
1065 return wd
1066}
1067
1068func (c *configImpl) rbeDir() string {
1069 if v, ok := c.environ.Get("RBE_DIR"); ok {
1070 return v
1071 }
1072 return "prebuilts/remoteexecution-client/live/"
1073}
1074
1075func (c *configImpl) rbeReproxy() string {
1076 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1077 if v, ok := c.environ.Get(f); ok {
1078 return v
1079 }
1080 }
1081 return filepath.Join(c.rbeDir(), "reproxy")
1082}
1083
1084func (c *configImpl) rbeAuth() (string, string) {
1085 credFlags := []string{"use_application_default_credentials", "use_gce_credentials", "credential_file"}
1086 for _, cf := range credFlags {
1087 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1088 if v, ok := c.environ.Get(f); ok {
1089 v = strings.TrimSpace(v)
1090 if v != "" && v != "false" && v != "0" {
1091 return "RBE_" + cf, v
1092 }
1093 }
1094 }
1095 }
1096 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001097}
1098
Colin Cross9016b912019-11-11 14:57:42 -08001099func (c *configImpl) UseRemoteBuild() bool {
1100 return c.UseGoma() || c.UseRBE()
1101}
1102
Dan Willemsen1e704462016-08-21 15:17:17 -07001103// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001104// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001105// still limited by Parallel()
1106func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001107 if !c.UseRemoteBuild() {
1108 return 0
1109 }
1110 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1111 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001112 }
1113 return 500
1114}
1115
1116func (c *configImpl) SetKatiArgs(args []string) {
1117 c.katiArgs = args
1118}
1119
1120func (c *configImpl) SetNinjaArgs(args []string) {
1121 c.ninjaArgs = args
1122}
1123
1124func (c *configImpl) SetKatiSuffix(suffix string) {
1125 c.katiSuffix = suffix
1126}
1127
Dan Willemsene0879fc2017-08-04 15:06:27 -07001128func (c *configImpl) LastKatiSuffixFile() string {
1129 return filepath.Join(c.OutDir(), "last_kati_suffix")
1130}
1131
1132func (c *configImpl) HasKatiSuffix() bool {
1133 return c.katiSuffix != ""
1134}
1135
Dan Willemsen1e704462016-08-21 15:17:17 -07001136func (c *configImpl) KatiEnvFile() string {
1137 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1138}
1139
Dan Willemsen29971232018-09-26 14:58:30 -07001140func (c *configImpl) KatiBuildNinjaFile() string {
1141 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001142}
1143
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001144func (c *configImpl) KatiPackageNinjaFile() string {
1145 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1146}
1147
Dan Willemsen1e704462016-08-21 15:17:17 -07001148func (c *configImpl) SoongNinjaFile() string {
1149 return filepath.Join(c.SoongOutDir(), "build.ninja")
1150}
1151
1152func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001153 if c.katiSuffix == "" {
1154 return filepath.Join(c.OutDir(), "combined.ninja")
1155 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001156 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1157}
1158
1159func (c *configImpl) SoongAndroidMk() string {
1160 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1161}
1162
1163func (c *configImpl) SoongMakeVarsMk() string {
1164 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1165}
1166
Dan Willemsenf052f782017-05-18 15:29:04 -07001167func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001168 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001169}
1170
Dan Willemsen02781d52017-05-12 19:28:13 -07001171func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001172 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1173}
1174
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001175func (c *configImpl) KatiPackageMkDir() string {
1176 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1177}
1178
Dan Willemsenf052f782017-05-18 15:29:04 -07001179func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001180 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001181}
1182
1183func (c *configImpl) HostOut() string {
1184 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1185}
1186
1187// This probably needs to be multi-valued, so not exporting it for now
1188func (c *configImpl) hostCrossOut() string {
1189 if runtime.GOOS == "linux" {
1190 return filepath.Join(c.hostOutRoot(), "windows-x86")
1191 } else {
1192 return ""
1193 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001194}
1195
Dan Willemsen1e704462016-08-21 15:17:17 -07001196func (c *configImpl) HostPrebuiltTag() string {
1197 if runtime.GOOS == "linux" {
1198 return "linux-x86"
1199 } else if runtime.GOOS == "darwin" {
1200 return "darwin-x86"
1201 } else {
1202 panic("Unsupported OS")
1203 }
1204}
Dan Willemsenf173d592017-04-27 14:28:00 -07001205
Dan Willemsen8122bd52017-10-12 20:20:41 -07001206func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001207 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1208 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001209 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1210 if _, err := os.Stat(asan); err == nil {
1211 return asan
1212 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001213 }
1214 }
1215 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1216}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001217
1218func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1219 c.brokenDupRules = val
1220}
1221
1222func (c *configImpl) BuildBrokenDupRules() bool {
1223 return c.brokenDupRules
1224}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001225
Dan Willemsen25e6f092019-04-09 10:22:43 -07001226func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1227 c.brokenUsesNetwork = val
1228}
1229
1230func (c *configImpl) BuildBrokenUsesNetwork() bool {
1231 return c.brokenUsesNetwork
1232}
1233
Dan Willemsene3336352020-01-02 19:10:38 -08001234func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1235 c.brokenNinjaEnvVars = val
1236}
1237
1238func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1239 return c.brokenNinjaEnvVars
1240}
1241
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001242func (c *configImpl) SetTargetDeviceDir(dir string) {
1243 c.targetDeviceDir = dir
1244}
1245
1246func (c *configImpl) TargetDeviceDir() string {
1247 return c.targetDeviceDir
1248}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001249
Patrice Arruda219eef32020-06-01 17:29:30 +00001250func (c *configImpl) BuildDateTime() string {
1251 return c.buildDateTime
1252}
1253
1254func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001255 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001256}
Patrice Arruda83842d72020-12-08 19:42:08 +00001257
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001258// LogsDir returns the absolute path to the logs directory where build log and
1259// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001260// directory. If the argument dist is specified, the logs directory
1261// is <dist_dir>/logs.
1262func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001263 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001264 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001265 // Always write logs to the real dist dir, even if Bazel is using a rigged dist dir for other files
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001266 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001267 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001268 absDir, err := filepath.Abs(dir)
1269 if err != nil {
1270 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1271 os.Exit(1)
1272 }
1273 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001274}
1275
1276// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1277// where the bazel profiles are located.
1278func (c *configImpl) BazelMetricsDir() string {
1279 return filepath.Join(c.LogsDir(), "bazel_metrics")
1280}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001281
1282func (c *configImpl) SetEmptyNinjaFile(v bool) {
1283 c.emptyNinjaFile = v
1284}
1285
1286func (c *configImpl) EmptyNinjaFile() bool {
1287 return c.emptyNinjaFile
1288}
Yu Liu6e13b402021-07-27 14:29:06 -07001289
1290func GetMetricsUploader(topDir string, env *Environment) string {
1291 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1292 metricsUploader := filepath.Join(topDir, p)
1293 if _, err := os.Stat(metricsUploader); err == nil {
1294 return metricsUploader
1295 }
1296 }
1297
1298 return ""
1299}