blob: 1152cd790e654c1d5ae70f276a24ee010ab28789 [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
Patrice Arruda96850362020-08-11 20:41:11 +000028 "github.com/golang/protobuf/proto"
29
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 {
36 // From the environment
Colin Cross28f527c2019-11-26 16:19:04 -080037 arguments []string
38 goma bool
39 environ *Environment
40 distDir string
41 buildDateTime string
Dan Willemsen1e704462016-08-21 15:17:17 -070042
43 // From the arguments
Colin Cross00a8a3f2020-10-29 14:08:31 -070044 parallel int
45 keepGoing int
46 verbose bool
47 checkbuild bool
48 dist bool
Anton Hansson5e5c48b2020-11-27 12:35:20 +000049 skipConfig bool
50 skipKati bool
Colin Cross00a8a3f2020-10-29 14:08:31 -070051 skipSoongTests bool
Dan Willemsen1e704462016-08-21 15:17:17 -070052
53 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070054 katiArgs []string
55 ninjaArgs []string
56 katiSuffix string
57 targetDevice string
58 targetDeviceDir string
Dan Willemsen3d60b112018-04-04 22:25:56 -070059
Dan Willemsen2bb82d02019-12-27 09:35:42 -080060 // Autodetected
61 totalRAM uint64
62
Dan Willemsene3336352020-01-02 19:10:38 -080063 brokenDupRules bool
64 brokenUsesNetwork bool
65 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -070066
67 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +000068
69 useBazel bool
70
71 // During Bazel execution, Bazel cannot write outside OUT_DIR.
72 // 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.
73 riggedDistDirForBazel string
Dan Willemsen1e704462016-08-21 15:17:17 -070074}
75
Dan Willemsenc2af0be2017-01-20 14:10:01 -080076const srcDirFileCheck = "build/soong/root.bp"
77
Patrice Arruda9450d0b2019-07-08 11:06:46 -070078var buildFiles = []string{"Android.mk", "Android.bp"}
79
Patrice Arruda13848222019-04-22 17:12:02 -070080type BuildAction uint
81
82const (
83 // Builds all of the modules and their dependencies of a specified directory, relative to the root
84 // directory of the source tree.
85 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
86
87 // Builds all of the modules and their dependencies of a list of specified directories. All specified
88 // directories are relative to the root directory of the source tree.
89 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -070090
91 // Build a list of specified modules. If none was specified, simply build the whole source tree.
92 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -070093)
94
95// checkTopDir validates that the current directory is at the root directory of the source tree.
96func checkTopDir(ctx Context) {
97 if _, err := os.Stat(srcDirFileCheck); err != nil {
98 if os.IsNotExist(err) {
99 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
100 }
101 ctx.Fatalln("Error verifying tree state:", err)
102 }
103}
104
Dan Willemsen1e704462016-08-21 15:17:17 -0700105func NewConfig(ctx Context, args ...string) Config {
106 ret := &configImpl{
107 environ: OsEnvironment(),
108 }
109
Patrice Arruda90109172020-07-28 18:07:27 +0000110 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700111 ret.parallel = runtime.NumCPU() + 2
112 ret.keepGoing = 1
113
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800114 ret.totalRAM = detectTotalRAM(ctx)
115
Dan Willemsen9b587492017-07-10 22:13:00 -0700116 ret.parseArgs(ctx, args)
117
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800118 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700119 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
120 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
121 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800122 outDir := "out"
123 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
124 if wd, err := os.Getwd(); err != nil {
125 ctx.Fatalln("Failed to get working directory:", err)
126 } else {
127 outDir = filepath.Join(baseDir, filepath.Base(wd))
128 }
129 }
130 ret.environ.Set("OUT_DIR", outDir)
131 }
132
Dan Willemsen2d31a442018-10-20 21:33:41 -0700133 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
134 ret.distDir = filepath.Clean(distDir)
135 } else {
136 ret.distDir = filepath.Join(ret.OutDir(), "dist")
137 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700138
Dan Willemsen1e704462016-08-21 15:17:17 -0700139 ret.environ.Unset(
140 // We're already using it
141 "USE_SOONG_UI",
142
143 // We should never use GOROOT/GOPATH from the shell environment
144 "GOROOT",
145 "GOPATH",
146
147 // These should only come from Soong, not the environment.
148 "CLANG",
149 "CLANG_CXX",
150 "CCC_CC",
151 "CCC_CXX",
152
153 // Used by the goma compiler wrapper, but should only be set by
154 // gomacc
155 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800156
157 // We handle this above
158 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700159
Dan Willemsen2d31a442018-10-20 21:33:41 -0700160 // This is handled above too, and set for individual commands later
161 "DIST_DIR",
162
Dan Willemsen68a09852017-04-18 13:56:57 -0700163 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000164 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700165 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700166 "DISPLAY",
167 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700168 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700169 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700170
171 // Drop make flags
172 "MAKEFLAGS",
173 "MAKELEVEL",
174 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700175
176 // Set in envsetup.sh, reset in makefiles
177 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700178
179 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
180 "ANDROID_BUILD_TOP",
181 "ANDROID_HOST_OUT",
182 "ANDROID_PRODUCT_OUT",
183 "ANDROID_HOST_OUT_TESTCASES",
184 "ANDROID_TARGET_OUT_TESTCASES",
185 "ANDROID_TOOLCHAIN",
186 "ANDROID_TOOLCHAIN_2ND_ARCH",
187 "ANDROID_DEV_SCRIPTS",
188 "ANDROID_EMULATOR_PREBUILTS",
189 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsenf99915f2018-10-25 22:04:42 -0700190
191 // Only set in multiproduct_kati after config generation
192 "EMPTY_NINJA_FILE",
Dan Willemsen1e704462016-08-21 15:17:17 -0700193 )
194
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400195 if ret.UseGoma() || ret.ForceUseGoma() {
196 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
197 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400198 }
199
Dan Willemsen1e704462016-08-21 15:17:17 -0700200 // Tell python not to spam the source tree with .pyc files.
201 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
202
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400203 tmpDir := absPath(ctx, ret.TempDir())
204 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800205
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700206 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
207 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
208 "llvm-binutils-stable/llvm-symbolizer")
209 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
210
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800211 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700212 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800213
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700214 if srcDir := absPath(ctx, "."); strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700215 ctx.Println("You are building in a directory whose absolute path contains a space character:")
216 ctx.Println()
217 ctx.Printf("%q\n", srcDir)
218 ctx.Println()
219 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700220 }
221
222 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700223 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
224 ctx.Println()
225 ctx.Printf("%q\n", outDir)
226 ctx.Println()
227 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700228 }
229
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000230 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700231 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
232 ctx.Println()
233 ctx.Printf("%q\n", distDir)
234 ctx.Println()
235 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700236 }
237
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700238 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000239 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
240 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100241 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700242 javaHome := func() string {
243 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
244 return override
245 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000246 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
247 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 +0100248 }
Pete Gillinabbcdda2019-10-28 16:15:33 +0000249 return java11Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700250 }()
251 absJavaHome := absPath(ctx, javaHome)
252
Dan Willemsened869522018-01-08 14:58:46 -0800253 ret.configureLocale(ctx)
254
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700255 newPath := []string{filepath.Join(absJavaHome, "bin")}
256 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
257 newPath = append(newPath, path)
258 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100259
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700260 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
261 ret.environ.Set("JAVA_HOME", absJavaHome)
262 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000263 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
264 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100265 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700266 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
267
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800268 outDir := ret.OutDir()
269 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800270 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800271 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800272 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800273 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800274 }
Colin Cross28f527c2019-11-26 16:19:04 -0800275
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800276 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
277
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400278 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400279 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400280 ret.environ.Set(k, v)
281 }
282 }
283
Patrice Arruda83842d72020-12-08 19:42:08 +0000284 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800285 if err := os.RemoveAll(bpd); err != nil {
286 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
287 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000288
289 ret.useBazel = ret.environ.IsEnvTrue("USE_BAZEL")
290
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800291 if ret.UseBazel() {
292 if err := os.MkdirAll(bpd, 0777); err != nil {
293 ctx.Fatalf("Failed to create bazel profile directory %q: %v", bpd, err)
294 }
295 }
296
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000297 if ret.UseBazel() {
298 ret.riggedDistDirForBazel = filepath.Join(ret.OutDir(), "dist")
299 } else {
300 // Not rigged
301 ret.riggedDistDirForBazel = ret.distDir
302 }
303
Patrice Arruda96850362020-08-11 20:41:11 +0000304 c := Config{ret}
305 storeConfigMetrics(ctx, c)
306 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700307}
308
Patrice Arruda13848222019-04-22 17:12:02 -0700309// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
310// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700311func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
312 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700313}
314
Patrice Arruda96850362020-08-11 20:41:11 +0000315// storeConfigMetrics selects a set of configuration information and store in
316// the metrics system for further analysis.
317func storeConfigMetrics(ctx Context, config Config) {
318 if ctx.Metrics == nil {
319 return
320 }
321
322 b := &smpb.BuildConfig{
Patrice Arrudac97d6dc2020-09-28 18:22:07 +0000323 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
324 UseGoma: proto.Bool(config.UseGoma()),
325 UseRbe: proto.Bool(config.UseRBE()),
Patrice Arruda96850362020-08-11 20:41:11 +0000326 }
327 ctx.Metrics.BuildConfig(b)
Patrice Arruda3edfd482020-10-13 23:58:41 +0000328
329 s := &smpb.SystemResourceInfo{
330 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
331 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
332 }
333 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000334}
335
Patrice Arruda13848222019-04-22 17:12:02 -0700336// getConfigArgs processes the command arguments based on the build action and creates a set of new
337// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700338func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700339 // The next block of code verifies that the current directory is the root directory of the source
340 // tree. It then finds the relative path of dir based on the root directory of the source tree
341 // and verify that dir is inside of the source tree.
342 checkTopDir(ctx)
343 topDir, err := os.Getwd()
344 if err != nil {
345 ctx.Fatalf("Error retrieving top directory: %v", err)
346 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700347 dir, err = filepath.EvalSymlinks(dir)
348 if err != nil {
349 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
350 }
Patrice Arruda13848222019-04-22 17:12:02 -0700351 dir, err = filepath.Abs(dir)
352 if err != nil {
353 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
354 }
355 relDir, err := filepath.Rel(topDir, dir)
356 if err != nil {
357 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
358 }
359 // If there are ".." in the path, it's not in the source tree.
360 if strings.Contains(relDir, "..") {
361 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
362 }
363
364 configArgs := args[:]
365
366 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
367 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
368 targetNamePrefix := "MODULES-IN-"
369 if inList("GET-INSTALL-PATH", configArgs) {
370 targetNamePrefix = "GET-INSTALL-PATH-IN-"
371 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
372 }
373
Patrice Arruda13848222019-04-22 17:12:02 -0700374 var targets []string
375
376 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700377 case BUILD_MODULES:
378 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700379 case BUILD_MODULES_IN_A_DIRECTORY:
380 // If dir is the root source tree, all the modules are built of the source tree are built so
381 // no need to find the build file.
382 if topDir == dir {
383 break
384 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700385
Patrice Arruda13848222019-04-22 17:12:02 -0700386 buildFile := findBuildFile(ctx, relDir)
387 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700388 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700389 }
Patrice Arruda13848222019-04-22 17:12:02 -0700390 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
391 case BUILD_MODULES_IN_DIRECTORIES:
392 newConfigArgs, dirs := splitArgs(configArgs)
393 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700394 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700395 }
396
397 // Tidy only override all other specified targets.
398 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
399 if tidyOnly == "true" || tidyOnly == "1" {
400 configArgs = append(configArgs, "tidy_only")
401 } else {
402 configArgs = append(configArgs, targets...)
403 }
404
405 return configArgs
406}
407
408// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
409func convertToTarget(dir string, targetNamePrefix string) string {
410 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
411}
412
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700413// hasBuildFile returns true if dir contains an Android build file.
414func hasBuildFile(ctx Context, dir string) bool {
415 for _, buildFile := range buildFiles {
416 _, err := os.Stat(filepath.Join(dir, buildFile))
417 if err == nil {
418 return true
419 }
420 if !os.IsNotExist(err) {
421 ctx.Fatalf("Error retrieving the build file stats: %v", err)
422 }
423 }
424 return false
425}
426
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700427// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
428// in the current and any sub directory of dir. If a build file is not found, traverse the path
429// up by one directory and repeat again until either a build file is found or reached to the root
430// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
431// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700432func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700433 // If the string is empty or ".", assume it is top directory of the source tree.
434 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700435 return ""
436 }
437
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700438 found := false
439 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
440 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
441 if err != nil {
442 return err
443 }
444 if found {
445 return filepath.SkipDir
446 }
447 if info.IsDir() {
448 return nil
449 }
450 for _, buildFile := range buildFiles {
451 if info.Name() == buildFile {
452 found = true
453 return filepath.SkipDir
454 }
455 }
456 return nil
457 })
458 if err != nil {
459 ctx.Fatalf("Error finding Android build file: %v", err)
460 }
461
462 if found {
463 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700464 }
465 }
466
467 return ""
468}
469
470// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
471func splitArgs(args []string) (newArgs []string, dirs []string) {
472 specialArgs := map[string]bool{
473 "showcommands": true,
474 "snod": true,
475 "dist": true,
476 "checkbuild": true,
477 }
478
479 newArgs = []string{}
480 dirs = []string{}
481
482 for _, arg := range args {
483 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
484 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
485 newArgs = append(newArgs, arg)
486 continue
487 }
488
489 if _, ok := specialArgs[arg]; ok {
490 newArgs = append(newArgs, arg)
491 continue
492 }
493
494 dirs = append(dirs, arg)
495 }
496
497 return newArgs, dirs
498}
499
500// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
501// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
502// source root tree where the build action command was invoked. Each directory is validated if the
503// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700504func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700505 for _, dir := range dirs {
506 // The directory may have specified specific modules to build. ":" is the separator to separate
507 // the directory and the list of modules.
508 s := strings.Split(dir, ":")
509 l := len(s)
510 if l > 2 { // more than one ":" was specified.
511 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
512 }
513
514 dir = filepath.Join(relDir, s[0])
515 if _, err := os.Stat(dir); err != nil {
516 ctx.Fatalf("couldn't find directory %s", dir)
517 }
518
519 // Verify that if there are any targets specified after ":". Each target is separated by ",".
520 var newTargets []string
521 if l == 2 && s[1] != "" {
522 newTargets = strings.Split(s[1], ",")
523 if inList("", newTargets) {
524 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
525 }
526 }
527
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700528 // If there are specified targets to build in dir, an android build file must exist for the one
529 // shot build. For the non-targets case, find the appropriate build file and build all the
530 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700531 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700532 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700533 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
534 }
535 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700536 buildFile := findBuildFile(ctx, dir)
537 if buildFile == "" {
538 ctx.Fatalf("Build file not found for %s directory", dir)
539 }
540 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700541 }
542
Patrice Arruda13848222019-04-22 17:12:02 -0700543 targets = append(targets, newTargets...)
544 }
545
Dan Willemsence41e942019-07-29 23:39:30 -0700546 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700547}
548
Dan Willemsen9b587492017-07-10 22:13:00 -0700549func (c *configImpl) parseArgs(ctx Context, args []string) {
550 for i := 0; i < len(args); i++ {
551 arg := strings.TrimSpace(args[i])
Dan Willemsen1e704462016-08-21 15:17:17 -0700552 if arg == "--make-mode" {
Dan Willemsen1e704462016-08-21 15:17:17 -0700553 } else if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700554 c.verbose = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700555 } else if arg == "--skip-make" {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000556 c.skipConfig = true
557 c.skipKati = true
558 } else if arg == "--skip-kati" {
559 c.skipKati = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700560 } else if arg == "--skip-soong-tests" {
561 c.skipSoongTests = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700562 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700563 parseArgNum := func(def int) int {
564 if len(arg) > 2 {
565 p, err := strconv.ParseUint(arg[2:], 10, 31)
566 if err != nil {
567 ctx.Fatalf("Failed to parse %q: %v", arg, err)
568 }
569 return int(p)
570 } else if i+1 < len(args) {
571 p, err := strconv.ParseUint(args[i+1], 10, 31)
572 if err == nil {
573 i++
574 return int(p)
575 }
576 }
577 return def
578 }
579
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700580 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700581 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700582 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700583 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700584 } else {
585 ctx.Fatalln("Unknown option:", arg)
586 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700587 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700588 if k == "OUT_DIR" {
589 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
590 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700591 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700592 } else if arg == "dist" {
593 c.dist = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700594 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700595 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800596 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700597 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700598 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700599 }
600 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700601}
602
Dan Willemsened869522018-01-08 14:58:46 -0800603func (c *configImpl) configureLocale(ctx Context) {
604 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
605 output, err := cmd.Output()
606
607 var locales []string
608 if err == nil {
609 locales = strings.Split(string(output), "\n")
610 } else {
611 // If we're unable to list the locales, let's assume en_US.UTF-8
612 locales = []string{"en_US.UTF-8"}
613 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
614 }
615
616 // gettext uses LANGUAGE, which is passed directly through
617
618 // For LANG and LC_*, only preserve the evaluated version of
619 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800620 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800621 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800622 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800623 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800624 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800625 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800626 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800627 }
628
629 c.environ.UnsetWithPrefix("LC_")
630
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800631 if userLang != "" {
632 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800633 }
634
635 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
636 // for others)
637 if inList("C.UTF-8", locales) {
638 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500639 } else if inList("C.utf8", locales) {
640 // These normalize to the same thing
641 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800642 } else if inList("en_US.UTF-8", locales) {
643 c.environ.Set("LANG", "en_US.UTF-8")
644 } else if inList("en_US.utf8", locales) {
645 // These normalize to the same thing
646 c.environ.Set("LANG", "en_US.UTF-8")
647 } else {
648 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
649 }
650}
651
Dan Willemsen1e704462016-08-21 15:17:17 -0700652// Lunch configures the environment for a specific product similarly to the
653// `lunch` bash function.
654func (c *configImpl) Lunch(ctx Context, product, variant string) {
655 if variant != "eng" && variant != "userdebug" && variant != "user" {
656 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
657 }
658
659 c.environ.Set("TARGET_PRODUCT", product)
660 c.environ.Set("TARGET_BUILD_VARIANT", variant)
661 c.environ.Set("TARGET_BUILD_TYPE", "release")
662 c.environ.Unset("TARGET_BUILD_APPS")
Martin Stjernholm08802332020-06-04 17:00:01 +0100663 c.environ.Unset("TARGET_BUILD_UNBUNDLED")
Dan Willemsen1e704462016-08-21 15:17:17 -0700664}
665
666// Tapas configures the environment to build one or more unbundled apps,
667// similarly to the `tapas` bash function.
668func (c *configImpl) Tapas(ctx Context, apps []string, arch, variant string) {
669 if len(apps) == 0 {
670 apps = []string{"all"}
671 }
672 if variant == "" {
673 variant = "eng"
674 }
675
676 if variant != "eng" && variant != "userdebug" && variant != "user" {
677 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
678 }
679
680 var product string
681 switch arch {
Dan Willemsen1e704462016-08-21 15:17:17 -0700682 case "arm", "":
683 product = "aosp_arm"
684 case "arm64":
685 product = "aosm_arm64"
Dan Willemsen1e704462016-08-21 15:17:17 -0700686 case "x86":
687 product = "aosp_x86"
688 case "x86_64":
689 product = "aosp_x86_64"
690 default:
691 ctx.Fatalf("Invalid architecture: %q", arch)
692 }
693
694 c.environ.Set("TARGET_PRODUCT", product)
695 c.environ.Set("TARGET_BUILD_VARIANT", variant)
696 c.environ.Set("TARGET_BUILD_TYPE", "release")
697 c.environ.Set("TARGET_BUILD_APPS", strings.Join(apps, " "))
698}
699
700func (c *configImpl) Environment() *Environment {
701 return c.environ
702}
703
704func (c *configImpl) Arguments() []string {
705 return c.arguments
706}
707
708func (c *configImpl) OutDir() string {
709 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700710 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700711 }
712 return "out"
713}
714
Dan Willemsen8a073a82017-02-04 17:30:44 -0800715func (c *configImpl) DistDir() string {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000716 if c.UseBazel() {
717 return c.riggedDistDirForBazel
718 } else {
719 return c.distDir
720 }
721}
722
723func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700724 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800725}
726
Dan Willemsen1e704462016-08-21 15:17:17 -0700727func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000728 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700729 return c.arguments
730 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700731 return c.ninjaArgs
732}
733
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500734func (c *configImpl) BazelOutDir() string {
735 return filepath.Join(c.OutDir(), "bazel")
736}
737
Dan Willemsen1e704462016-08-21 15:17:17 -0700738func (c *configImpl) SoongOutDir() string {
739 return filepath.Join(c.OutDir(), "soong")
740}
741
Jeff Gastonefc1b412017-03-29 17:29:06 -0700742func (c *configImpl) TempDir() string {
743 return shared.TempDirForOutDir(c.SoongOutDir())
744}
745
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700746func (c *configImpl) FileListDir() string {
747 return filepath.Join(c.OutDir(), ".module_paths")
748}
749
Dan Willemsen1e704462016-08-21 15:17:17 -0700750func (c *configImpl) KatiSuffix() string {
751 if c.katiSuffix != "" {
752 return c.katiSuffix
753 }
754 panic("SetKatiSuffix has not been called")
755}
756
Colin Cross37193492017-11-16 17:55:00 -0800757// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
758// user is interested in additional checks at the expense of build time.
759func (c *configImpl) Checkbuild() bool {
760 return c.checkbuild
761}
762
Dan Willemsen8a073a82017-02-04 17:30:44 -0800763func (c *configImpl) Dist() bool {
764 return c.dist
765}
766
Dan Willemsen1e704462016-08-21 15:17:17 -0700767func (c *configImpl) IsVerbose() bool {
768 return c.verbose
769}
770
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000771func (c *configImpl) SkipKati() bool {
772 return c.skipKati
773}
774
775func (c *configImpl) SkipConfig() bool {
776 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -0700777}
778
Dan Willemsen1e704462016-08-21 15:17:17 -0700779func (c *configImpl) TargetProduct() string {
780 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
781 return v
782 }
783 panic("TARGET_PRODUCT is not defined")
784}
785
Dan Willemsen02781d52017-05-12 19:28:13 -0700786func (c *configImpl) TargetDevice() string {
787 return c.targetDevice
788}
789
790func (c *configImpl) SetTargetDevice(device string) {
791 c.targetDevice = device
792}
793
794func (c *configImpl) TargetBuildVariant() string {
795 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
796 return v
797 }
798 panic("TARGET_BUILD_VARIANT is not defined")
799}
800
Dan Willemsen1e704462016-08-21 15:17:17 -0700801func (c *configImpl) KatiArgs() []string {
802 return c.katiArgs
803}
804
805func (c *configImpl) Parallel() int {
806 return c.parallel
807}
808
Colin Cross8b8bec32019-11-15 13:18:43 -0800809func (c *configImpl) HighmemParallel() int {
810 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
811 return i
812 }
813
814 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
815 parallel := c.Parallel()
816 if c.UseRemoteBuild() {
817 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
818 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
819 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
820 // Return 1/16th of the size of the local pool, rounding up.
821 return (parallel + 15) / 16
822 } else if c.totalRAM == 0 {
823 // Couldn't detect the total RAM, don't restrict highmem processes.
824 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -0700825 } else if c.totalRAM <= 16*1024*1024*1024 {
826 // Less than 16GB of ram, restrict to 1 highmem processes
827 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -0800828 } else if c.totalRAM <= 32*1024*1024*1024 {
829 // Less than 32GB of ram, restrict to 2 highmem processes
830 return 2
831 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
832 // If less than 8GB total RAM per process, reduce the number of highmem processes
833 return p
834 }
835 // No restriction on highmem processes
836 return parallel
837}
838
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800839func (c *configImpl) TotalRAM() uint64 {
840 return c.totalRAM
841}
842
Kousik Kumarec478642020-09-21 13:39:24 -0400843// ForceUseGoma determines whether we should override Goma deprecation
844// and use Goma for the current build or not.
845func (c *configImpl) ForceUseGoma() bool {
846 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
847 v = strings.TrimSpace(v)
848 if v != "" && v != "false" {
849 return true
850 }
851 }
852 return false
853}
854
Dan Willemsen1e704462016-08-21 15:17:17 -0700855func (c *configImpl) UseGoma() bool {
856 if v, ok := c.environ.Get("USE_GOMA"); ok {
857 v = strings.TrimSpace(v)
858 if v != "" && v != "false" {
859 return true
860 }
861 }
862 return false
863}
864
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +0900865func (c *configImpl) StartGoma() bool {
866 if !c.UseGoma() {
867 return false
868 }
869
870 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
871 v = strings.TrimSpace(v)
872 if v != "" && v != "false" {
873 return false
874 }
875 }
876 return true
877}
878
Ramy Medhatbbf25672019-07-17 12:30:04 +0000879func (c *configImpl) UseRBE() bool {
880 if v, ok := c.environ.Get("USE_RBE"); ok {
881 v = strings.TrimSpace(v)
882 if v != "" && v != "false" {
883 return true
884 }
885 }
886 return false
887}
888
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800889func (c *configImpl) UseBazel() bool {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000890 return c.useBazel
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800891}
892
Ramy Medhatbbf25672019-07-17 12:30:04 +0000893func (c *configImpl) StartRBE() bool {
894 if !c.UseRBE() {
895 return false
896 }
897
898 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
899 v = strings.TrimSpace(v)
900 if v != "" && v != "false" {
901 return false
902 }
903 }
904 return true
905}
906
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000907func (c *configImpl) rbeLogDir() string {
Kousik Kumar0d15a722020-09-23 02:54:11 -0400908 for _, f := range []string{"RBE_log_dir", "FLAG_log_dir"} {
909 if v, ok := c.environ.Get(f); ok {
910 return v
911 }
912 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400913 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000914 return c.LogsDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400915 }
916 return c.OutDir()
917}
918
919func (c *configImpl) rbeStatsOutputDir() string {
Patrice Arruda62f1bf22020-07-07 12:48:26 +0000920 for _, f := range []string{"RBE_output_dir", "FLAG_output_dir"} {
921 if v, ok := c.environ.Get(f); ok {
922 return v
923 }
924 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000925 return c.rbeLogDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400926}
927
928func (c *configImpl) rbeLogPath() string {
929 for _, f := range []string{"RBE_log_path", "FLAG_log_path"} {
930 if v, ok := c.environ.Get(f); ok {
931 return v
932 }
933 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000934 return fmt.Sprintf("text://%v/reproxy_log.txt", c.rbeLogDir())
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400935}
936
937func (c *configImpl) rbeExecRoot() string {
938 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
939 if v, ok := c.environ.Get(f); ok {
940 return v
941 }
942 }
943 wd, err := os.Getwd()
944 if err != nil {
945 return ""
946 }
947 return wd
948}
949
950func (c *configImpl) rbeDir() string {
951 if v, ok := c.environ.Get("RBE_DIR"); ok {
952 return v
953 }
954 return "prebuilts/remoteexecution-client/live/"
955}
956
957func (c *configImpl) rbeReproxy() string {
958 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
959 if v, ok := c.environ.Get(f); ok {
960 return v
961 }
962 }
963 return filepath.Join(c.rbeDir(), "reproxy")
964}
965
966func (c *configImpl) rbeAuth() (string, string) {
967 credFlags := []string{"use_application_default_credentials", "use_gce_credentials", "credential_file"}
968 for _, cf := range credFlags {
969 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
970 if v, ok := c.environ.Get(f); ok {
971 v = strings.TrimSpace(v)
972 if v != "" && v != "false" && v != "0" {
973 return "RBE_" + cf, v
974 }
975 }
976 }
977 }
978 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +0000979}
980
Colin Cross9016b912019-11-11 14:57:42 -0800981func (c *configImpl) UseRemoteBuild() bool {
982 return c.UseGoma() || c.UseRBE()
983}
984
Dan Willemsen1e704462016-08-21 15:17:17 -0700985// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -0700986// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -0700987// still limited by Parallel()
988func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -0800989 if !c.UseRemoteBuild() {
990 return 0
991 }
992 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
993 return i
Dan Willemsen1e704462016-08-21 15:17:17 -0700994 }
995 return 500
996}
997
998func (c *configImpl) SetKatiArgs(args []string) {
999 c.katiArgs = args
1000}
1001
1002func (c *configImpl) SetNinjaArgs(args []string) {
1003 c.ninjaArgs = args
1004}
1005
1006func (c *configImpl) SetKatiSuffix(suffix string) {
1007 c.katiSuffix = suffix
1008}
1009
Dan Willemsene0879fc2017-08-04 15:06:27 -07001010func (c *configImpl) LastKatiSuffixFile() string {
1011 return filepath.Join(c.OutDir(), "last_kati_suffix")
1012}
1013
1014func (c *configImpl) HasKatiSuffix() bool {
1015 return c.katiSuffix != ""
1016}
1017
Dan Willemsen1e704462016-08-21 15:17:17 -07001018func (c *configImpl) KatiEnvFile() string {
1019 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1020}
1021
Dan Willemsen29971232018-09-26 14:58:30 -07001022func (c *configImpl) KatiBuildNinjaFile() string {
1023 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001024}
1025
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001026func (c *configImpl) KatiPackageNinjaFile() string {
1027 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1028}
1029
Dan Willemsen1e704462016-08-21 15:17:17 -07001030func (c *configImpl) SoongNinjaFile() string {
1031 return filepath.Join(c.SoongOutDir(), "build.ninja")
1032}
1033
1034func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001035 if c.katiSuffix == "" {
1036 return filepath.Join(c.OutDir(), "combined.ninja")
1037 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001038 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1039}
1040
1041func (c *configImpl) SoongAndroidMk() string {
1042 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1043}
1044
1045func (c *configImpl) SoongMakeVarsMk() string {
1046 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1047}
1048
Dan Willemsenf052f782017-05-18 15:29:04 -07001049func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001050 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001051}
1052
Dan Willemsen02781d52017-05-12 19:28:13 -07001053func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001054 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1055}
1056
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001057func (c *configImpl) KatiPackageMkDir() string {
1058 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1059}
1060
Dan Willemsenf052f782017-05-18 15:29:04 -07001061func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001062 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001063}
1064
1065func (c *configImpl) HostOut() string {
1066 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1067}
1068
1069// This probably needs to be multi-valued, so not exporting it for now
1070func (c *configImpl) hostCrossOut() string {
1071 if runtime.GOOS == "linux" {
1072 return filepath.Join(c.hostOutRoot(), "windows-x86")
1073 } else {
1074 return ""
1075 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001076}
1077
Dan Willemsen1e704462016-08-21 15:17:17 -07001078func (c *configImpl) HostPrebuiltTag() string {
1079 if runtime.GOOS == "linux" {
1080 return "linux-x86"
1081 } else if runtime.GOOS == "darwin" {
1082 return "darwin-x86"
1083 } else {
1084 panic("Unsupported OS")
1085 }
1086}
Dan Willemsenf173d592017-04-27 14:28:00 -07001087
Dan Willemsen8122bd52017-10-12 20:20:41 -07001088func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001089 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1090 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001091 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1092 if _, err := os.Stat(asan); err == nil {
1093 return asan
1094 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001095 }
1096 }
1097 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1098}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001099
1100func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1101 c.brokenDupRules = val
1102}
1103
1104func (c *configImpl) BuildBrokenDupRules() bool {
1105 return c.brokenDupRules
1106}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001107
Dan Willemsen25e6f092019-04-09 10:22:43 -07001108func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1109 c.brokenUsesNetwork = val
1110}
1111
1112func (c *configImpl) BuildBrokenUsesNetwork() bool {
1113 return c.brokenUsesNetwork
1114}
1115
Dan Willemsene3336352020-01-02 19:10:38 -08001116func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1117 c.brokenNinjaEnvVars = val
1118}
1119
1120func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1121 return c.brokenNinjaEnvVars
1122}
1123
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001124func (c *configImpl) SetTargetDeviceDir(dir string) {
1125 c.targetDeviceDir = dir
1126}
1127
1128func (c *configImpl) TargetDeviceDir() string {
1129 return c.targetDeviceDir
1130}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001131
Patrice Arruda219eef32020-06-01 17:29:30 +00001132func (c *configImpl) BuildDateTime() string {
1133 return c.buildDateTime
1134}
1135
1136func (c *configImpl) MetricsUploaderApp() string {
1137 if p, ok := c.environ.Get("ANDROID_ENABLE_METRICS_UPLOAD"); ok {
1138 return p
1139 }
1140 return ""
1141}
Patrice Arruda83842d72020-12-08 19:42:08 +00001142
1143// LogsDir returns the logs directory where build log and metrics
1144// files are located. By default, the logs directory is the out
1145// directory. If the argument dist is specified, the logs directory
1146// is <dist_dir>/logs.
1147func (c *configImpl) LogsDir() string {
1148 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001149 // Always write logs to the real dist dir, even if Bazel is using a rigged dist dir for other files
1150 return filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001151 }
1152 return c.OutDir()
1153}
1154
1155// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1156// where the bazel profiles are located.
1157func (c *configImpl) BazelMetricsDir() string {
1158 return filepath.Join(c.LogsDir(), "bazel_metrics")
1159}