blob: 4816d1f15cae8cbd1976f5e5d39815c8a563b49d [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
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010051 skipNinja bool
Colin Cross00a8a3f2020-10-29 14:08:31 -070052 skipSoongTests bool
Dan Willemsen1e704462016-08-21 15:17:17 -070053
54 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070055 katiArgs []string
56 ninjaArgs []string
57 katiSuffix string
58 targetDevice string
59 targetDeviceDir string
Dan Willemsen3d60b112018-04-04 22:25:56 -070060
Dan Willemsen2bb82d02019-12-27 09:35:42 -080061 // Autodetected
62 totalRAM uint64
63
Dan Willemsene3336352020-01-02 19:10:38 -080064 brokenDupRules bool
65 brokenUsesNetwork bool
66 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -070067
68 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +000069
70 useBazel bool
71
72 // During Bazel execution, Bazel cannot write outside OUT_DIR.
73 // 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.
74 riggedDistDirForBazel string
Dan Willemsen1e704462016-08-21 15:17:17 -070075}
76
Dan Willemsenc2af0be2017-01-20 14:10:01 -080077const srcDirFileCheck = "build/soong/root.bp"
78
Patrice Arruda9450d0b2019-07-08 11:06:46 -070079var buildFiles = []string{"Android.mk", "Android.bp"}
80
Patrice Arruda13848222019-04-22 17:12:02 -070081type BuildAction uint
82
83const (
84 // Builds all of the modules and their dependencies of a specified directory, relative to the root
85 // directory of the source tree.
86 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
87
88 // Builds all of the modules and their dependencies of a list of specified directories. All specified
89 // directories are relative to the root directory of the source tree.
90 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -070091
92 // Build a list of specified modules. If none was specified, simply build the whole source tree.
93 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -070094)
95
96// checkTopDir validates that the current directory is at the root directory of the source tree.
97func checkTopDir(ctx Context) {
98 if _, err := os.Stat(srcDirFileCheck); err != nil {
99 if os.IsNotExist(err) {
100 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
101 }
102 ctx.Fatalln("Error verifying tree state:", err)
103 }
104}
105
Dan Willemsen1e704462016-08-21 15:17:17 -0700106func NewConfig(ctx Context, args ...string) Config {
107 ret := &configImpl{
108 environ: OsEnvironment(),
109 }
110
Patrice Arruda90109172020-07-28 18:07:27 +0000111 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700112 ret.parallel = runtime.NumCPU() + 2
113 ret.keepGoing = 1
114
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800115 ret.totalRAM = detectTotalRAM(ctx)
116
Dan Willemsen9b587492017-07-10 22:13:00 -0700117 ret.parseArgs(ctx, args)
118
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800119 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700120 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
121 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
122 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800123 outDir := "out"
124 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
125 if wd, err := os.Getwd(); err != nil {
126 ctx.Fatalln("Failed to get working directory:", err)
127 } else {
128 outDir = filepath.Join(baseDir, filepath.Base(wd))
129 }
130 }
131 ret.environ.Set("OUT_DIR", outDir)
132 }
133
Dan Willemsen2d31a442018-10-20 21:33:41 -0700134 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
135 ret.distDir = filepath.Clean(distDir)
136 } else {
137 ret.distDir = filepath.Join(ret.OutDir(), "dist")
138 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700139
Dan Willemsen1e704462016-08-21 15:17:17 -0700140 ret.environ.Unset(
141 // We're already using it
142 "USE_SOONG_UI",
143
144 // We should never use GOROOT/GOPATH from the shell environment
145 "GOROOT",
146 "GOPATH",
147
148 // These should only come from Soong, not the environment.
149 "CLANG",
150 "CLANG_CXX",
151 "CCC_CC",
152 "CCC_CXX",
153
154 // Used by the goma compiler wrapper, but should only be set by
155 // gomacc
156 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800157
158 // We handle this above
159 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700160
Dan Willemsen2d31a442018-10-20 21:33:41 -0700161 // This is handled above too, and set for individual commands later
162 "DIST_DIR",
163
Dan Willemsen68a09852017-04-18 13:56:57 -0700164 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000165 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700166 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700167 "DISPLAY",
168 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700169 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700170 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700171
172 // Drop make flags
173 "MAKEFLAGS",
174 "MAKELEVEL",
175 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700176
177 // Set in envsetup.sh, reset in makefiles
178 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700179
180 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
181 "ANDROID_BUILD_TOP",
182 "ANDROID_HOST_OUT",
183 "ANDROID_PRODUCT_OUT",
184 "ANDROID_HOST_OUT_TESTCASES",
185 "ANDROID_TARGET_OUT_TESTCASES",
186 "ANDROID_TOOLCHAIN",
187 "ANDROID_TOOLCHAIN_2ND_ARCH",
188 "ANDROID_DEV_SCRIPTS",
189 "ANDROID_EMULATOR_PREBUILTS",
190 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsenf99915f2018-10-25 22:04:42 -0700191
192 // Only set in multiproduct_kati after config generation
193 "EMPTY_NINJA_FILE",
Dan Willemsen1e704462016-08-21 15:17:17 -0700194 )
195
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400196 if ret.UseGoma() || ret.ForceUseGoma() {
197 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
198 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400199 }
200
Dan Willemsen1e704462016-08-21 15:17:17 -0700201 // Tell python not to spam the source tree with .pyc files.
202 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
203
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400204 tmpDir := absPath(ctx, ret.TempDir())
205 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800206
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700207 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
208 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
209 "llvm-binutils-stable/llvm-symbolizer")
210 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
211
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800212 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700213 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800214
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700215 if srcDir := absPath(ctx, "."); strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700216 ctx.Println("You are building in a directory whose absolute path contains a space character:")
217 ctx.Println()
218 ctx.Printf("%q\n", srcDir)
219 ctx.Println()
220 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700221 }
222
223 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700224 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
225 ctx.Println()
226 ctx.Printf("%q\n", outDir)
227 ctx.Println()
228 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700229 }
230
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000231 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700232 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
233 ctx.Println()
234 ctx.Printf("%q\n", distDir)
235 ctx.Println()
236 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700237 }
238
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700239 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000240 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
241 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100242 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700243 javaHome := func() string {
244 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
245 return override
246 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000247 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
248 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 +0100249 }
Pete Gillinabbcdda2019-10-28 16:15:33 +0000250 return java11Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700251 }()
252 absJavaHome := absPath(ctx, javaHome)
253
Dan Willemsened869522018-01-08 14:58:46 -0800254 ret.configureLocale(ctx)
255
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700256 newPath := []string{filepath.Join(absJavaHome, "bin")}
257 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
258 newPath = append(newPath, path)
259 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100260
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700261 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
262 ret.environ.Set("JAVA_HOME", absJavaHome)
263 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000264 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
265 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100266 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700267 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
268
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800269 outDir := ret.OutDir()
270 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800271 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800272 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800273 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800274 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800275 }
Colin Cross28f527c2019-11-26 16:19:04 -0800276
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800277 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
278
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400279 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400280 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400281 ret.environ.Set(k, v)
282 }
283 }
284
Patrice Arruda83842d72020-12-08 19:42:08 +0000285 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800286 if err := os.RemoveAll(bpd); err != nil {
287 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
288 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000289
290 ret.useBazel = ret.environ.IsEnvTrue("USE_BAZEL")
291
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800292 if ret.UseBazel() {
293 if err := os.MkdirAll(bpd, 0777); err != nil {
294 ctx.Fatalf("Failed to create bazel profile directory %q: %v", bpd, err)
295 }
296 }
297
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000298 if ret.UseBazel() {
299 ret.riggedDistDirForBazel = filepath.Join(ret.OutDir(), "dist")
300 } else {
301 // Not rigged
302 ret.riggedDistDirForBazel = ret.distDir
303 }
304
Patrice Arruda96850362020-08-11 20:41:11 +0000305 c := Config{ret}
306 storeConfigMetrics(ctx, c)
307 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700308}
309
Patrice Arruda13848222019-04-22 17:12:02 -0700310// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
311// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700312func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
313 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700314}
315
Patrice Arruda96850362020-08-11 20:41:11 +0000316// storeConfigMetrics selects a set of configuration information and store in
317// the metrics system for further analysis.
318func storeConfigMetrics(ctx Context, config Config) {
319 if ctx.Metrics == nil {
320 return
321 }
322
323 b := &smpb.BuildConfig{
Patrice Arrudac97d6dc2020-09-28 18:22:07 +0000324 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
325 UseGoma: proto.Bool(config.UseGoma()),
326 UseRbe: proto.Bool(config.UseRBE()),
Patrice Arruda96850362020-08-11 20:41:11 +0000327 }
328 ctx.Metrics.BuildConfig(b)
Patrice Arruda3edfd482020-10-13 23:58:41 +0000329
330 s := &smpb.SystemResourceInfo{
331 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
332 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
333 }
334 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000335}
336
Patrice Arruda13848222019-04-22 17:12:02 -0700337// getConfigArgs processes the command arguments based on the build action and creates a set of new
338// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700339func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700340 // The next block of code verifies that the current directory is the root directory of the source
341 // tree. It then finds the relative path of dir based on the root directory of the source tree
342 // and verify that dir is inside of the source tree.
343 checkTopDir(ctx)
344 topDir, err := os.Getwd()
345 if err != nil {
346 ctx.Fatalf("Error retrieving top directory: %v", err)
347 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700348 dir, err = filepath.EvalSymlinks(dir)
349 if err != nil {
350 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
351 }
Patrice Arruda13848222019-04-22 17:12:02 -0700352 dir, err = filepath.Abs(dir)
353 if err != nil {
354 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
355 }
356 relDir, err := filepath.Rel(topDir, dir)
357 if err != nil {
358 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
359 }
360 // If there are ".." in the path, it's not in the source tree.
361 if strings.Contains(relDir, "..") {
362 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
363 }
364
365 configArgs := args[:]
366
367 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
368 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
369 targetNamePrefix := "MODULES-IN-"
370 if inList("GET-INSTALL-PATH", configArgs) {
371 targetNamePrefix = "GET-INSTALL-PATH-IN-"
372 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
373 }
374
Patrice Arruda13848222019-04-22 17:12:02 -0700375 var targets []string
376
377 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700378 case BUILD_MODULES:
379 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700380 case BUILD_MODULES_IN_A_DIRECTORY:
381 // If dir is the root source tree, all the modules are built of the source tree are built so
382 // no need to find the build file.
383 if topDir == dir {
384 break
385 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700386
Patrice Arruda13848222019-04-22 17:12:02 -0700387 buildFile := findBuildFile(ctx, relDir)
388 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700389 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700390 }
Patrice Arruda13848222019-04-22 17:12:02 -0700391 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
392 case BUILD_MODULES_IN_DIRECTORIES:
393 newConfigArgs, dirs := splitArgs(configArgs)
394 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700395 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700396 }
397
398 // Tidy only override all other specified targets.
399 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
400 if tidyOnly == "true" || tidyOnly == "1" {
401 configArgs = append(configArgs, "tidy_only")
402 } else {
403 configArgs = append(configArgs, targets...)
404 }
405
406 return configArgs
407}
408
409// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
410func convertToTarget(dir string, targetNamePrefix string) string {
411 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
412}
413
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700414// hasBuildFile returns true if dir contains an Android build file.
415func hasBuildFile(ctx Context, dir string) bool {
416 for _, buildFile := range buildFiles {
417 _, err := os.Stat(filepath.Join(dir, buildFile))
418 if err == nil {
419 return true
420 }
421 if !os.IsNotExist(err) {
422 ctx.Fatalf("Error retrieving the build file stats: %v", err)
423 }
424 }
425 return false
426}
427
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700428// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
429// in the current and any sub directory of dir. If a build file is not found, traverse the path
430// up by one directory and repeat again until either a build file is found or reached to the root
431// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
432// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700433func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700434 // If the string is empty or ".", assume it is top directory of the source tree.
435 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700436 return ""
437 }
438
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700439 found := false
440 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
441 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
442 if err != nil {
443 return err
444 }
445 if found {
446 return filepath.SkipDir
447 }
448 if info.IsDir() {
449 return nil
450 }
451 for _, buildFile := range buildFiles {
452 if info.Name() == buildFile {
453 found = true
454 return filepath.SkipDir
455 }
456 }
457 return nil
458 })
459 if err != nil {
460 ctx.Fatalf("Error finding Android build file: %v", err)
461 }
462
463 if found {
464 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700465 }
466 }
467
468 return ""
469}
470
471// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
472func splitArgs(args []string) (newArgs []string, dirs []string) {
473 specialArgs := map[string]bool{
474 "showcommands": true,
475 "snod": true,
476 "dist": true,
477 "checkbuild": true,
478 }
479
480 newArgs = []string{}
481 dirs = []string{}
482
483 for _, arg := range args {
484 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
485 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
486 newArgs = append(newArgs, arg)
487 continue
488 }
489
490 if _, ok := specialArgs[arg]; ok {
491 newArgs = append(newArgs, arg)
492 continue
493 }
494
495 dirs = append(dirs, arg)
496 }
497
498 return newArgs, dirs
499}
500
501// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
502// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
503// source root tree where the build action command was invoked. Each directory is validated if the
504// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700505func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700506 for _, dir := range dirs {
507 // The directory may have specified specific modules to build. ":" is the separator to separate
508 // the directory and the list of modules.
509 s := strings.Split(dir, ":")
510 l := len(s)
511 if l > 2 { // more than one ":" was specified.
512 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
513 }
514
515 dir = filepath.Join(relDir, s[0])
516 if _, err := os.Stat(dir); err != nil {
517 ctx.Fatalf("couldn't find directory %s", dir)
518 }
519
520 // Verify that if there are any targets specified after ":". Each target is separated by ",".
521 var newTargets []string
522 if l == 2 && s[1] != "" {
523 newTargets = strings.Split(s[1], ",")
524 if inList("", newTargets) {
525 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
526 }
527 }
528
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700529 // If there are specified targets to build in dir, an android build file must exist for the one
530 // shot build. For the non-targets case, find the appropriate build file and build all the
531 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700532 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700533 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700534 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
535 }
536 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700537 buildFile := findBuildFile(ctx, dir)
538 if buildFile == "" {
539 ctx.Fatalf("Build file not found for %s directory", dir)
540 }
541 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700542 }
543
Patrice Arruda13848222019-04-22 17:12:02 -0700544 targets = append(targets, newTargets...)
545 }
546
Dan Willemsence41e942019-07-29 23:39:30 -0700547 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700548}
549
Dan Willemsen9b587492017-07-10 22:13:00 -0700550func (c *configImpl) parseArgs(ctx Context, args []string) {
551 for i := 0; i < len(args); i++ {
552 arg := strings.TrimSpace(args[i])
Dan Willemsen1e704462016-08-21 15:17:17 -0700553 if arg == "--make-mode" {
Dan Willemsen1e704462016-08-21 15:17:17 -0700554 } else if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700555 c.verbose = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100556 } else if arg == "--skip-ninja" {
557 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700558 } else if arg == "--skip-make" {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000559 c.skipConfig = true
560 c.skipKati = true
561 } else if arg == "--skip-kati" {
562 c.skipKati = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700563 } else if arg == "--skip-soong-tests" {
564 c.skipSoongTests = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700565 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700566 parseArgNum := func(def int) int {
567 if len(arg) > 2 {
568 p, err := strconv.ParseUint(arg[2:], 10, 31)
569 if err != nil {
570 ctx.Fatalf("Failed to parse %q: %v", arg, err)
571 }
572 return int(p)
573 } else if i+1 < len(args) {
574 p, err := strconv.ParseUint(args[i+1], 10, 31)
575 if err == nil {
576 i++
577 return int(p)
578 }
579 }
580 return def
581 }
582
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700583 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700584 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700585 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700586 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700587 } else {
588 ctx.Fatalln("Unknown option:", arg)
589 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700590 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700591 if k == "OUT_DIR" {
592 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
593 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700594 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700595 } else if arg == "dist" {
596 c.dist = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700597 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700598 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800599 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700600 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700601 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700602 }
603 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700604}
605
Dan Willemsened869522018-01-08 14:58:46 -0800606func (c *configImpl) configureLocale(ctx Context) {
607 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
608 output, err := cmd.Output()
609
610 var locales []string
611 if err == nil {
612 locales = strings.Split(string(output), "\n")
613 } else {
614 // If we're unable to list the locales, let's assume en_US.UTF-8
615 locales = []string{"en_US.UTF-8"}
616 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
617 }
618
619 // gettext uses LANGUAGE, which is passed directly through
620
621 // For LANG and LC_*, only preserve the evaluated version of
622 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800623 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800624 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800625 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800626 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800627 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800628 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800629 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800630 }
631
632 c.environ.UnsetWithPrefix("LC_")
633
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800634 if userLang != "" {
635 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800636 }
637
638 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
639 // for others)
640 if inList("C.UTF-8", locales) {
641 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500642 } else if inList("C.utf8", locales) {
643 // These normalize to the same thing
644 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800645 } else if inList("en_US.UTF-8", locales) {
646 c.environ.Set("LANG", "en_US.UTF-8")
647 } else if inList("en_US.utf8", locales) {
648 // These normalize to the same thing
649 c.environ.Set("LANG", "en_US.UTF-8")
650 } else {
651 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
652 }
653}
654
Dan Willemsen1e704462016-08-21 15:17:17 -0700655// Lunch configures the environment for a specific product similarly to the
656// `lunch` bash function.
657func (c *configImpl) Lunch(ctx Context, product, variant string) {
658 if variant != "eng" && variant != "userdebug" && variant != "user" {
659 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
660 }
661
662 c.environ.Set("TARGET_PRODUCT", product)
663 c.environ.Set("TARGET_BUILD_VARIANT", variant)
664 c.environ.Set("TARGET_BUILD_TYPE", "release")
665 c.environ.Unset("TARGET_BUILD_APPS")
Martin Stjernholm08802332020-06-04 17:00:01 +0100666 c.environ.Unset("TARGET_BUILD_UNBUNDLED")
Dan Willemsen1e704462016-08-21 15:17:17 -0700667}
668
669// Tapas configures the environment to build one or more unbundled apps,
670// similarly to the `tapas` bash function.
671func (c *configImpl) Tapas(ctx Context, apps []string, arch, variant string) {
672 if len(apps) == 0 {
673 apps = []string{"all"}
674 }
675 if variant == "" {
676 variant = "eng"
677 }
678
679 if variant != "eng" && variant != "userdebug" && variant != "user" {
680 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
681 }
682
683 var product string
684 switch arch {
Dan Willemsen1e704462016-08-21 15:17:17 -0700685 case "arm", "":
686 product = "aosp_arm"
687 case "arm64":
688 product = "aosm_arm64"
Dan Willemsen1e704462016-08-21 15:17:17 -0700689 case "x86":
690 product = "aosp_x86"
691 case "x86_64":
692 product = "aosp_x86_64"
693 default:
694 ctx.Fatalf("Invalid architecture: %q", arch)
695 }
696
697 c.environ.Set("TARGET_PRODUCT", product)
698 c.environ.Set("TARGET_BUILD_VARIANT", variant)
699 c.environ.Set("TARGET_BUILD_TYPE", "release")
700 c.environ.Set("TARGET_BUILD_APPS", strings.Join(apps, " "))
701}
702
703func (c *configImpl) Environment() *Environment {
704 return c.environ
705}
706
707func (c *configImpl) Arguments() []string {
708 return c.arguments
709}
710
711func (c *configImpl) OutDir() string {
712 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700713 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700714 }
715 return "out"
716}
717
Dan Willemsen8a073a82017-02-04 17:30:44 -0800718func (c *configImpl) DistDir() string {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000719 if c.UseBazel() {
720 return c.riggedDistDirForBazel
721 } else {
722 return c.distDir
723 }
724}
725
726func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700727 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800728}
729
Dan Willemsen1e704462016-08-21 15:17:17 -0700730func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000731 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700732 return c.arguments
733 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700734 return c.ninjaArgs
735}
736
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500737func (c *configImpl) BazelOutDir() string {
738 return filepath.Join(c.OutDir(), "bazel")
739}
740
Dan Willemsen1e704462016-08-21 15:17:17 -0700741func (c *configImpl) SoongOutDir() string {
742 return filepath.Join(c.OutDir(), "soong")
743}
744
Jeff Gastonefc1b412017-03-29 17:29:06 -0700745func (c *configImpl) TempDir() string {
746 return shared.TempDirForOutDir(c.SoongOutDir())
747}
748
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700749func (c *configImpl) FileListDir() string {
750 return filepath.Join(c.OutDir(), ".module_paths")
751}
752
Dan Willemsen1e704462016-08-21 15:17:17 -0700753func (c *configImpl) KatiSuffix() string {
754 if c.katiSuffix != "" {
755 return c.katiSuffix
756 }
757 panic("SetKatiSuffix has not been called")
758}
759
Colin Cross37193492017-11-16 17:55:00 -0800760// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
761// user is interested in additional checks at the expense of build time.
762func (c *configImpl) Checkbuild() bool {
763 return c.checkbuild
764}
765
Dan Willemsen8a073a82017-02-04 17:30:44 -0800766func (c *configImpl) Dist() bool {
767 return c.dist
768}
769
Dan Willemsen1e704462016-08-21 15:17:17 -0700770func (c *configImpl) IsVerbose() bool {
771 return c.verbose
772}
773
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000774func (c *configImpl) SkipKati() bool {
775 return c.skipKati
776}
777
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100778func (c *configImpl) SkipNinja() bool {
779 return c.skipNinja
780}
781
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000782func (c *configImpl) SkipConfig() bool {
783 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -0700784}
785
Dan Willemsen1e704462016-08-21 15:17:17 -0700786func (c *configImpl) TargetProduct() string {
787 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
788 return v
789 }
790 panic("TARGET_PRODUCT is not defined")
791}
792
Dan Willemsen02781d52017-05-12 19:28:13 -0700793func (c *configImpl) TargetDevice() string {
794 return c.targetDevice
795}
796
797func (c *configImpl) SetTargetDevice(device string) {
798 c.targetDevice = device
799}
800
801func (c *configImpl) TargetBuildVariant() string {
802 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
803 return v
804 }
805 panic("TARGET_BUILD_VARIANT is not defined")
806}
807
Dan Willemsen1e704462016-08-21 15:17:17 -0700808func (c *configImpl) KatiArgs() []string {
809 return c.katiArgs
810}
811
812func (c *configImpl) Parallel() int {
813 return c.parallel
814}
815
Colin Cross8b8bec32019-11-15 13:18:43 -0800816func (c *configImpl) HighmemParallel() int {
817 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
818 return i
819 }
820
821 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
822 parallel := c.Parallel()
823 if c.UseRemoteBuild() {
824 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
825 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
826 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
827 // Return 1/16th of the size of the local pool, rounding up.
828 return (parallel + 15) / 16
829 } else if c.totalRAM == 0 {
830 // Couldn't detect the total RAM, don't restrict highmem processes.
831 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -0700832 } else if c.totalRAM <= 16*1024*1024*1024 {
833 // Less than 16GB of ram, restrict to 1 highmem processes
834 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -0800835 } else if c.totalRAM <= 32*1024*1024*1024 {
836 // Less than 32GB of ram, restrict to 2 highmem processes
837 return 2
838 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
839 // If less than 8GB total RAM per process, reduce the number of highmem processes
840 return p
841 }
842 // No restriction on highmem processes
843 return parallel
844}
845
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800846func (c *configImpl) TotalRAM() uint64 {
847 return c.totalRAM
848}
849
Kousik Kumarec478642020-09-21 13:39:24 -0400850// ForceUseGoma determines whether we should override Goma deprecation
851// and use Goma for the current build or not.
852func (c *configImpl) ForceUseGoma() bool {
853 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
854 v = strings.TrimSpace(v)
855 if v != "" && v != "false" {
856 return true
857 }
858 }
859 return false
860}
861
Dan Willemsen1e704462016-08-21 15:17:17 -0700862func (c *configImpl) UseGoma() bool {
863 if v, ok := c.environ.Get("USE_GOMA"); ok {
864 v = strings.TrimSpace(v)
865 if v != "" && v != "false" {
866 return true
867 }
868 }
869 return false
870}
871
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +0900872func (c *configImpl) StartGoma() bool {
873 if !c.UseGoma() {
874 return false
875 }
876
877 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
878 v = strings.TrimSpace(v)
879 if v != "" && v != "false" {
880 return false
881 }
882 }
883 return true
884}
885
Ramy Medhatbbf25672019-07-17 12:30:04 +0000886func (c *configImpl) UseRBE() bool {
887 if v, ok := c.environ.Get("USE_RBE"); ok {
888 v = strings.TrimSpace(v)
889 if v != "" && v != "false" {
890 return true
891 }
892 }
893 return false
894}
895
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800896func (c *configImpl) UseBazel() bool {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000897 return c.useBazel
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800898}
899
Ramy Medhatbbf25672019-07-17 12:30:04 +0000900func (c *configImpl) StartRBE() bool {
901 if !c.UseRBE() {
902 return false
903 }
904
905 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
906 v = strings.TrimSpace(v)
907 if v != "" && v != "false" {
908 return false
909 }
910 }
911 return true
912}
913
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000914func (c *configImpl) rbeLogDir() string {
Kousik Kumar0d15a722020-09-23 02:54:11 -0400915 for _, f := range []string{"RBE_log_dir", "FLAG_log_dir"} {
916 if v, ok := c.environ.Get(f); ok {
917 return v
918 }
919 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400920 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000921 return c.LogsDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400922 }
923 return c.OutDir()
924}
925
926func (c *configImpl) rbeStatsOutputDir() string {
Patrice Arruda62f1bf22020-07-07 12:48:26 +0000927 for _, f := range []string{"RBE_output_dir", "FLAG_output_dir"} {
928 if v, ok := c.environ.Get(f); ok {
929 return v
930 }
931 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000932 return c.rbeLogDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400933}
934
935func (c *configImpl) rbeLogPath() string {
936 for _, f := range []string{"RBE_log_path", "FLAG_log_path"} {
937 if v, ok := c.environ.Get(f); ok {
938 return v
939 }
940 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000941 return fmt.Sprintf("text://%v/reproxy_log.txt", c.rbeLogDir())
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400942}
943
944func (c *configImpl) rbeExecRoot() string {
945 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
946 if v, ok := c.environ.Get(f); ok {
947 return v
948 }
949 }
950 wd, err := os.Getwd()
951 if err != nil {
952 return ""
953 }
954 return wd
955}
956
957func (c *configImpl) rbeDir() string {
958 if v, ok := c.environ.Get("RBE_DIR"); ok {
959 return v
960 }
961 return "prebuilts/remoteexecution-client/live/"
962}
963
964func (c *configImpl) rbeReproxy() string {
965 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
966 if v, ok := c.environ.Get(f); ok {
967 return v
968 }
969 }
970 return filepath.Join(c.rbeDir(), "reproxy")
971}
972
973func (c *configImpl) rbeAuth() (string, string) {
974 credFlags := []string{"use_application_default_credentials", "use_gce_credentials", "credential_file"}
975 for _, cf := range credFlags {
976 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
977 if v, ok := c.environ.Get(f); ok {
978 v = strings.TrimSpace(v)
979 if v != "" && v != "false" && v != "0" {
980 return "RBE_" + cf, v
981 }
982 }
983 }
984 }
985 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +0000986}
987
Colin Cross9016b912019-11-11 14:57:42 -0800988func (c *configImpl) UseRemoteBuild() bool {
989 return c.UseGoma() || c.UseRBE()
990}
991
Dan Willemsen1e704462016-08-21 15:17:17 -0700992// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -0700993// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -0700994// still limited by Parallel()
995func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -0800996 if !c.UseRemoteBuild() {
997 return 0
998 }
999 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1000 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001001 }
1002 return 500
1003}
1004
1005func (c *configImpl) SetKatiArgs(args []string) {
1006 c.katiArgs = args
1007}
1008
1009func (c *configImpl) SetNinjaArgs(args []string) {
1010 c.ninjaArgs = args
1011}
1012
1013func (c *configImpl) SetKatiSuffix(suffix string) {
1014 c.katiSuffix = suffix
1015}
1016
Dan Willemsene0879fc2017-08-04 15:06:27 -07001017func (c *configImpl) LastKatiSuffixFile() string {
1018 return filepath.Join(c.OutDir(), "last_kati_suffix")
1019}
1020
1021func (c *configImpl) HasKatiSuffix() bool {
1022 return c.katiSuffix != ""
1023}
1024
Dan Willemsen1e704462016-08-21 15:17:17 -07001025func (c *configImpl) KatiEnvFile() string {
1026 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1027}
1028
Dan Willemsen29971232018-09-26 14:58:30 -07001029func (c *configImpl) KatiBuildNinjaFile() string {
1030 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001031}
1032
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001033func (c *configImpl) KatiPackageNinjaFile() string {
1034 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1035}
1036
Dan Willemsen1e704462016-08-21 15:17:17 -07001037func (c *configImpl) SoongNinjaFile() string {
1038 return filepath.Join(c.SoongOutDir(), "build.ninja")
1039}
1040
1041func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001042 if c.katiSuffix == "" {
1043 return filepath.Join(c.OutDir(), "combined.ninja")
1044 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001045 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1046}
1047
1048func (c *configImpl) SoongAndroidMk() string {
1049 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1050}
1051
1052func (c *configImpl) SoongMakeVarsMk() string {
1053 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1054}
1055
Dan Willemsenf052f782017-05-18 15:29:04 -07001056func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001057 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001058}
1059
Dan Willemsen02781d52017-05-12 19:28:13 -07001060func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001061 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1062}
1063
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001064func (c *configImpl) KatiPackageMkDir() string {
1065 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1066}
1067
Dan Willemsenf052f782017-05-18 15:29:04 -07001068func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001069 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001070}
1071
1072func (c *configImpl) HostOut() string {
1073 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1074}
1075
1076// This probably needs to be multi-valued, so not exporting it for now
1077func (c *configImpl) hostCrossOut() string {
1078 if runtime.GOOS == "linux" {
1079 return filepath.Join(c.hostOutRoot(), "windows-x86")
1080 } else {
1081 return ""
1082 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001083}
1084
Dan Willemsen1e704462016-08-21 15:17:17 -07001085func (c *configImpl) HostPrebuiltTag() string {
1086 if runtime.GOOS == "linux" {
1087 return "linux-x86"
1088 } else if runtime.GOOS == "darwin" {
1089 return "darwin-x86"
1090 } else {
1091 panic("Unsupported OS")
1092 }
1093}
Dan Willemsenf173d592017-04-27 14:28:00 -07001094
Dan Willemsen8122bd52017-10-12 20:20:41 -07001095func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001096 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1097 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001098 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1099 if _, err := os.Stat(asan); err == nil {
1100 return asan
1101 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001102 }
1103 }
1104 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1105}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001106
1107func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1108 c.brokenDupRules = val
1109}
1110
1111func (c *configImpl) BuildBrokenDupRules() bool {
1112 return c.brokenDupRules
1113}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001114
Dan Willemsen25e6f092019-04-09 10:22:43 -07001115func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1116 c.brokenUsesNetwork = val
1117}
1118
1119func (c *configImpl) BuildBrokenUsesNetwork() bool {
1120 return c.brokenUsesNetwork
1121}
1122
Dan Willemsene3336352020-01-02 19:10:38 -08001123func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1124 c.brokenNinjaEnvVars = val
1125}
1126
1127func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1128 return c.brokenNinjaEnvVars
1129}
1130
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001131func (c *configImpl) SetTargetDeviceDir(dir string) {
1132 c.targetDeviceDir = dir
1133}
1134
1135func (c *configImpl) TargetDeviceDir() string {
1136 return c.targetDeviceDir
1137}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001138
Patrice Arruda219eef32020-06-01 17:29:30 +00001139func (c *configImpl) BuildDateTime() string {
1140 return c.buildDateTime
1141}
1142
1143func (c *configImpl) MetricsUploaderApp() string {
1144 if p, ok := c.environ.Get("ANDROID_ENABLE_METRICS_UPLOAD"); ok {
1145 return p
1146 }
1147 return ""
1148}
Patrice Arruda83842d72020-12-08 19:42:08 +00001149
1150// LogsDir returns the logs directory where build log and metrics
1151// files are located. By default, the logs directory is the out
1152// directory. If the argument dist is specified, the logs directory
1153// is <dist_dir>/logs.
1154func (c *configImpl) LogsDir() string {
1155 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001156 // Always write logs to the real dist dir, even if Bazel is using a rigged dist dir for other files
1157 return filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001158 }
1159 return c.OutDir()
1160}
1161
1162// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1163// where the bazel profiles are located.
1164func (c *configImpl) BazelMetricsDir() string {
1165 return filepath.Join(c.LogsDir(), "bazel_metrics")
1166}