blob: 3a445a3305979be7aaae5b51a8863bcf3c6a46c2 [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
Spandan Dasa3639e62021-05-25 19:14:02 +000060 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -070061
Dan Willemsen2bb82d02019-12-27 09:35:42 -080062 // Autodetected
63 totalRAM uint64
64
Dan Willemsene3336352020-01-02 19:10:38 -080065 brokenDupRules bool
66 brokenUsesNetwork bool
67 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -070068
69 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +000070
71 useBazel bool
72
73 // During Bazel execution, Bazel cannot write outside OUT_DIR.
74 // 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.
75 riggedDistDirForBazel string
Colin Crossf3bdbcb2021-06-01 11:43:55 -070076
77 // Set by multiproduct_kati
78 emptyNinjaFile bool
Dan Willemsen1e704462016-08-21 15:17:17 -070079}
80
Dan Willemsenc2af0be2017-01-20 14:10:01 -080081const srcDirFileCheck = "build/soong/root.bp"
82
Patrice Arruda9450d0b2019-07-08 11:06:46 -070083var buildFiles = []string{"Android.mk", "Android.bp"}
84
Patrice Arruda13848222019-04-22 17:12:02 -070085type BuildAction uint
86
87const (
88 // Builds all of the modules and their dependencies of a specified directory, relative to the root
89 // directory of the source tree.
90 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
91
92 // Builds all of the modules and their dependencies of a list of specified directories. All specified
93 // directories are relative to the root directory of the source tree.
94 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -070095
96 // Build a list of specified modules. If none was specified, simply build the whole source tree.
97 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -070098)
99
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400100type bazelBuildMode int
101
102// Bazel-related build modes.
103const (
104 // Don't use bazel at all.
105 noBazel bazelBuildMode = iota
106
107 // Only generate build files (in a subdirectory of the out directory) and exit.
108 generateBuildFiles
109
110 // Generate synthetic build files and incorporate these files into a build which
111 // partially uses Bazel. Build metadata may come from Android.bp or BUILD files.
112 mixedBuild
113)
114
Patrice Arruda13848222019-04-22 17:12:02 -0700115// checkTopDir validates that the current directory is at the root directory of the source tree.
116func checkTopDir(ctx Context) {
117 if _, err := os.Stat(srcDirFileCheck); err != nil {
118 if os.IsNotExist(err) {
119 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
120 }
121 ctx.Fatalln("Error verifying tree state:", err)
122 }
123}
124
Dan Willemsen1e704462016-08-21 15:17:17 -0700125func NewConfig(ctx Context, args ...string) Config {
126 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000127 environ: OsEnvironment(),
128 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700129 }
130
Patrice Arruda90109172020-07-28 18:07:27 +0000131 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700132 ret.parallel = runtime.NumCPU() + 2
133 ret.keepGoing = 1
134
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800135 ret.totalRAM = detectTotalRAM(ctx)
136
Dan Willemsen9b587492017-07-10 22:13:00 -0700137 ret.parseArgs(ctx, args)
138
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800139 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700140 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
141 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
142 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800143 outDir := "out"
144 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
145 if wd, err := os.Getwd(); err != nil {
146 ctx.Fatalln("Failed to get working directory:", err)
147 } else {
148 outDir = filepath.Join(baseDir, filepath.Base(wd))
149 }
150 }
151 ret.environ.Set("OUT_DIR", outDir)
152 }
153
Dan Willemsen2d31a442018-10-20 21:33:41 -0700154 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
155 ret.distDir = filepath.Clean(distDir)
156 } else {
157 ret.distDir = filepath.Join(ret.OutDir(), "dist")
158 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700159
Dan Willemsen1e704462016-08-21 15:17:17 -0700160 ret.environ.Unset(
161 // We're already using it
162 "USE_SOONG_UI",
163
164 // We should never use GOROOT/GOPATH from the shell environment
165 "GOROOT",
166 "GOPATH",
167
168 // These should only come from Soong, not the environment.
169 "CLANG",
170 "CLANG_CXX",
171 "CCC_CC",
172 "CCC_CXX",
173
174 // Used by the goma compiler wrapper, but should only be set by
175 // gomacc
176 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800177
178 // We handle this above
179 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700180
Dan Willemsen2d31a442018-10-20 21:33:41 -0700181 // This is handled above too, and set for individual commands later
182 "DIST_DIR",
183
Dan Willemsen68a09852017-04-18 13:56:57 -0700184 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000185 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700186 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700187 "DISPLAY",
188 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700189 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700190 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700191
192 // Drop make flags
193 "MAKEFLAGS",
194 "MAKELEVEL",
195 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700196
197 // Set in envsetup.sh, reset in makefiles
198 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700199
200 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
201 "ANDROID_BUILD_TOP",
202 "ANDROID_HOST_OUT",
203 "ANDROID_PRODUCT_OUT",
204 "ANDROID_HOST_OUT_TESTCASES",
205 "ANDROID_TARGET_OUT_TESTCASES",
206 "ANDROID_TOOLCHAIN",
207 "ANDROID_TOOLCHAIN_2ND_ARCH",
208 "ANDROID_DEV_SCRIPTS",
209 "ANDROID_EMULATOR_PREBUILTS",
210 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700211 )
212
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400213 if ret.UseGoma() || ret.ForceUseGoma() {
214 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
215 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400216 }
217
Dan Willemsen1e704462016-08-21 15:17:17 -0700218 // Tell python not to spam the source tree with .pyc files.
219 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
220
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400221 tmpDir := absPath(ctx, ret.TempDir())
222 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800223
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700224 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
225 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
226 "llvm-binutils-stable/llvm-symbolizer")
227 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
228
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800229 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700230 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800231
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700232 if srcDir := absPath(ctx, "."); strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700233 ctx.Println("You are building in a directory whose absolute path contains a space character:")
234 ctx.Println()
235 ctx.Printf("%q\n", srcDir)
236 ctx.Println()
237 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700238 }
239
240 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700241 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
242 ctx.Println()
243 ctx.Printf("%q\n", outDir)
244 ctx.Println()
245 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700246 }
247
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000248 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700249 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
250 ctx.Println()
251 ctx.Printf("%q\n", distDir)
252 ctx.Println()
253 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700254 }
255
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700256 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000257 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
258 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100259 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700260 javaHome := func() string {
261 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
262 return override
263 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000264 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
265 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 +0100266 }
Pete Gillinabbcdda2019-10-28 16:15:33 +0000267 return java11Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700268 }()
269 absJavaHome := absPath(ctx, javaHome)
270
Dan Willemsened869522018-01-08 14:58:46 -0800271 ret.configureLocale(ctx)
272
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700273 newPath := []string{filepath.Join(absJavaHome, "bin")}
274 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
275 newPath = append(newPath, path)
276 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100277
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700278 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
279 ret.environ.Set("JAVA_HOME", absJavaHome)
280 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000281 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
282 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100283 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700284 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
285
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800286 outDir := ret.OutDir()
287 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800288 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800289 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800290 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800291 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800292 }
Colin Cross28f527c2019-11-26 16:19:04 -0800293
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800294 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
295
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400296 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400297 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400298 ret.environ.Set(k, v)
299 }
300 }
301
Patrice Arruda83842d72020-12-08 19:42:08 +0000302 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800303 if err := os.RemoveAll(bpd); err != nil {
304 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
305 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000306
307 ret.useBazel = ret.environ.IsEnvTrue("USE_BAZEL")
308
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800309 if ret.UseBazel() {
310 if err := os.MkdirAll(bpd, 0777); err != nil {
311 ctx.Fatalf("Failed to create bazel profile directory %q: %v", bpd, err)
312 }
313 }
314
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000315 if ret.UseBazel() {
316 ret.riggedDistDirForBazel = filepath.Join(ret.OutDir(), "dist")
317 } else {
318 // Not rigged
319 ret.riggedDistDirForBazel = ret.distDir
320 }
321
Patrice Arruda96850362020-08-11 20:41:11 +0000322 c := Config{ret}
323 storeConfigMetrics(ctx, c)
324 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700325}
326
Patrice Arruda13848222019-04-22 17:12:02 -0700327// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
328// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700329func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
330 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700331}
332
Patrice Arruda96850362020-08-11 20:41:11 +0000333// storeConfigMetrics selects a set of configuration information and store in
334// the metrics system for further analysis.
335func storeConfigMetrics(ctx Context, config Config) {
336 if ctx.Metrics == nil {
337 return
338 }
339
340 b := &smpb.BuildConfig{
Patrice Arrudac97d6dc2020-09-28 18:22:07 +0000341 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
342 UseGoma: proto.Bool(config.UseGoma()),
343 UseRbe: proto.Bool(config.UseRBE()),
Patrice Arruda96850362020-08-11 20:41:11 +0000344 }
345 ctx.Metrics.BuildConfig(b)
Patrice Arruda3edfd482020-10-13 23:58:41 +0000346
347 s := &smpb.SystemResourceInfo{
348 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
349 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
350 }
351 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000352}
353
Patrice Arruda13848222019-04-22 17:12:02 -0700354// getConfigArgs processes the command arguments based on the build action and creates a set of new
355// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700356func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700357 // The next block of code verifies that the current directory is the root directory of the source
358 // tree. It then finds the relative path of dir based on the root directory of the source tree
359 // and verify that dir is inside of the source tree.
360 checkTopDir(ctx)
361 topDir, err := os.Getwd()
362 if err != nil {
363 ctx.Fatalf("Error retrieving top directory: %v", err)
364 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700365 dir, err = filepath.EvalSymlinks(dir)
366 if err != nil {
367 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
368 }
Patrice Arruda13848222019-04-22 17:12:02 -0700369 dir, err = filepath.Abs(dir)
370 if err != nil {
371 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
372 }
373 relDir, err := filepath.Rel(topDir, dir)
374 if err != nil {
375 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
376 }
377 // If there are ".." in the path, it's not in the source tree.
378 if strings.Contains(relDir, "..") {
379 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
380 }
381
382 configArgs := args[:]
383
384 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
385 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
386 targetNamePrefix := "MODULES-IN-"
387 if inList("GET-INSTALL-PATH", configArgs) {
388 targetNamePrefix = "GET-INSTALL-PATH-IN-"
389 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
390 }
391
Patrice Arruda13848222019-04-22 17:12:02 -0700392 var targets []string
393
394 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700395 case BUILD_MODULES:
396 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700397 case BUILD_MODULES_IN_A_DIRECTORY:
398 // If dir is the root source tree, all the modules are built of the source tree are built so
399 // no need to find the build file.
400 if topDir == dir {
401 break
402 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700403
Patrice Arruda13848222019-04-22 17:12:02 -0700404 buildFile := findBuildFile(ctx, relDir)
405 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700406 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700407 }
Patrice Arruda13848222019-04-22 17:12:02 -0700408 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
409 case BUILD_MODULES_IN_DIRECTORIES:
410 newConfigArgs, dirs := splitArgs(configArgs)
411 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700412 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700413 }
414
415 // Tidy only override all other specified targets.
416 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
417 if tidyOnly == "true" || tidyOnly == "1" {
418 configArgs = append(configArgs, "tidy_only")
419 } else {
420 configArgs = append(configArgs, targets...)
421 }
422
423 return configArgs
424}
425
426// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
427func convertToTarget(dir string, targetNamePrefix string) string {
428 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
429}
430
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700431// hasBuildFile returns true if dir contains an Android build file.
432func hasBuildFile(ctx Context, dir string) bool {
433 for _, buildFile := range buildFiles {
434 _, err := os.Stat(filepath.Join(dir, buildFile))
435 if err == nil {
436 return true
437 }
438 if !os.IsNotExist(err) {
439 ctx.Fatalf("Error retrieving the build file stats: %v", err)
440 }
441 }
442 return false
443}
444
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700445// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
446// in the current and any sub directory of dir. If a build file is not found, traverse the path
447// up by one directory and repeat again until either a build file is found or reached to the root
448// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
449// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700450func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700451 // If the string is empty or ".", assume it is top directory of the source tree.
452 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700453 return ""
454 }
455
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700456 found := false
457 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
458 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
459 if err != nil {
460 return err
461 }
462 if found {
463 return filepath.SkipDir
464 }
465 if info.IsDir() {
466 return nil
467 }
468 for _, buildFile := range buildFiles {
469 if info.Name() == buildFile {
470 found = true
471 return filepath.SkipDir
472 }
473 }
474 return nil
475 })
476 if err != nil {
477 ctx.Fatalf("Error finding Android build file: %v", err)
478 }
479
480 if found {
481 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700482 }
483 }
484
485 return ""
486}
487
488// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
489func splitArgs(args []string) (newArgs []string, dirs []string) {
490 specialArgs := map[string]bool{
491 "showcommands": true,
492 "snod": true,
493 "dist": true,
494 "checkbuild": true,
495 }
496
497 newArgs = []string{}
498 dirs = []string{}
499
500 for _, arg := range args {
501 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
502 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
503 newArgs = append(newArgs, arg)
504 continue
505 }
506
507 if _, ok := specialArgs[arg]; ok {
508 newArgs = append(newArgs, arg)
509 continue
510 }
511
512 dirs = append(dirs, arg)
513 }
514
515 return newArgs, dirs
516}
517
518// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
519// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
520// source root tree where the build action command was invoked. Each directory is validated if the
521// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700522func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700523 for _, dir := range dirs {
524 // The directory may have specified specific modules to build. ":" is the separator to separate
525 // the directory and the list of modules.
526 s := strings.Split(dir, ":")
527 l := len(s)
528 if l > 2 { // more than one ":" was specified.
529 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
530 }
531
532 dir = filepath.Join(relDir, s[0])
533 if _, err := os.Stat(dir); err != nil {
534 ctx.Fatalf("couldn't find directory %s", dir)
535 }
536
537 // Verify that if there are any targets specified after ":". Each target is separated by ",".
538 var newTargets []string
539 if l == 2 && s[1] != "" {
540 newTargets = strings.Split(s[1], ",")
541 if inList("", newTargets) {
542 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
543 }
544 }
545
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700546 // If there are specified targets to build in dir, an android build file must exist for the one
547 // shot build. For the non-targets case, find the appropriate build file and build all the
548 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700549 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700550 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700551 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
552 }
553 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700554 buildFile := findBuildFile(ctx, dir)
555 if buildFile == "" {
556 ctx.Fatalf("Build file not found for %s directory", dir)
557 }
558 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700559 }
560
Patrice Arruda13848222019-04-22 17:12:02 -0700561 targets = append(targets, newTargets...)
562 }
563
Dan Willemsence41e942019-07-29 23:39:30 -0700564 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700565}
566
Dan Willemsen9b587492017-07-10 22:13:00 -0700567func (c *configImpl) parseArgs(ctx Context, args []string) {
568 for i := 0; i < len(args); i++ {
569 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100570 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700571 c.verbose = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100572 } else if arg == "--skip-ninja" {
573 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700574 } else if arg == "--skip-make" {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000575 c.skipConfig = true
576 c.skipKati = true
577 } else if arg == "--skip-kati" {
578 c.skipKati = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700579 } else if arg == "--skip-soong-tests" {
580 c.skipSoongTests = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700581 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700582 parseArgNum := func(def int) int {
583 if len(arg) > 2 {
584 p, err := strconv.ParseUint(arg[2:], 10, 31)
585 if err != nil {
586 ctx.Fatalf("Failed to parse %q: %v", arg, err)
587 }
588 return int(p)
589 } else if i+1 < len(args) {
590 p, err := strconv.ParseUint(args[i+1], 10, 31)
591 if err == nil {
592 i++
593 return int(p)
594 }
595 }
596 return def
597 }
598
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700599 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700600 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700601 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700602 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700603 } else {
604 ctx.Fatalln("Unknown option:", arg)
605 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700606 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700607 if k == "OUT_DIR" {
608 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
609 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700610 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700611 } else if arg == "dist" {
612 c.dist = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700613 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700614 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800615 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700616 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700617 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700618 }
619 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700620}
621
Dan Willemsened869522018-01-08 14:58:46 -0800622func (c *configImpl) configureLocale(ctx Context) {
623 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
624 output, err := cmd.Output()
625
626 var locales []string
627 if err == nil {
628 locales = strings.Split(string(output), "\n")
629 } else {
630 // If we're unable to list the locales, let's assume en_US.UTF-8
631 locales = []string{"en_US.UTF-8"}
632 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
633 }
634
635 // gettext uses LANGUAGE, which is passed directly through
636
637 // For LANG and LC_*, only preserve the evaluated version of
638 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800639 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800640 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800641 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800642 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800643 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800644 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800645 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800646 }
647
648 c.environ.UnsetWithPrefix("LC_")
649
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800650 if userLang != "" {
651 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800652 }
653
654 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
655 // for others)
656 if inList("C.UTF-8", locales) {
657 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500658 } else if inList("C.utf8", locales) {
659 // These normalize to the same thing
660 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800661 } else if inList("en_US.UTF-8", locales) {
662 c.environ.Set("LANG", "en_US.UTF-8")
663 } else if inList("en_US.utf8", locales) {
664 // These normalize to the same thing
665 c.environ.Set("LANG", "en_US.UTF-8")
666 } else {
667 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
668 }
669}
670
Dan Willemsen1e704462016-08-21 15:17:17 -0700671// Lunch configures the environment for a specific product similarly to the
672// `lunch` bash function.
673func (c *configImpl) Lunch(ctx Context, product, variant string) {
674 if variant != "eng" && variant != "userdebug" && variant != "user" {
675 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
676 }
677
678 c.environ.Set("TARGET_PRODUCT", product)
679 c.environ.Set("TARGET_BUILD_VARIANT", variant)
680 c.environ.Set("TARGET_BUILD_TYPE", "release")
681 c.environ.Unset("TARGET_BUILD_APPS")
Martin Stjernholm08802332020-06-04 17:00:01 +0100682 c.environ.Unset("TARGET_BUILD_UNBUNDLED")
Dan Willemsen1e704462016-08-21 15:17:17 -0700683}
684
685// Tapas configures the environment to build one or more unbundled apps,
686// similarly to the `tapas` bash function.
687func (c *configImpl) Tapas(ctx Context, apps []string, arch, variant string) {
688 if len(apps) == 0 {
689 apps = []string{"all"}
690 }
691 if variant == "" {
692 variant = "eng"
693 }
694
695 if variant != "eng" && variant != "userdebug" && variant != "user" {
696 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
697 }
698
699 var product string
700 switch arch {
Dan Willemsen1e704462016-08-21 15:17:17 -0700701 case "arm", "":
702 product = "aosp_arm"
703 case "arm64":
704 product = "aosm_arm64"
Dan Willemsen1e704462016-08-21 15:17:17 -0700705 case "x86":
706 product = "aosp_x86"
707 case "x86_64":
708 product = "aosp_x86_64"
709 default:
710 ctx.Fatalf("Invalid architecture: %q", arch)
711 }
712
713 c.environ.Set("TARGET_PRODUCT", product)
714 c.environ.Set("TARGET_BUILD_VARIANT", variant)
715 c.environ.Set("TARGET_BUILD_TYPE", "release")
716 c.environ.Set("TARGET_BUILD_APPS", strings.Join(apps, " "))
717}
718
719func (c *configImpl) Environment() *Environment {
720 return c.environ
721}
722
723func (c *configImpl) Arguments() []string {
724 return c.arguments
725}
726
727func (c *configImpl) OutDir() string {
728 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700729 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700730 }
731 return "out"
732}
733
Dan Willemsen8a073a82017-02-04 17:30:44 -0800734func (c *configImpl) DistDir() string {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000735 if c.UseBazel() {
736 return c.riggedDistDirForBazel
737 } else {
738 return c.distDir
739 }
740}
741
742func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700743 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800744}
745
Dan Willemsen1e704462016-08-21 15:17:17 -0700746func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000747 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700748 return c.arguments
749 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700750 return c.ninjaArgs
751}
752
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500753func (c *configImpl) BazelOutDir() string {
754 return filepath.Join(c.OutDir(), "bazel")
755}
756
Dan Willemsen1e704462016-08-21 15:17:17 -0700757func (c *configImpl) SoongOutDir() string {
758 return filepath.Join(c.OutDir(), "soong")
759}
760
Jeff Gastonefc1b412017-03-29 17:29:06 -0700761func (c *configImpl) TempDir() string {
762 return shared.TempDirForOutDir(c.SoongOutDir())
763}
764
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700765func (c *configImpl) FileListDir() string {
766 return filepath.Join(c.OutDir(), ".module_paths")
767}
768
Dan Willemsen1e704462016-08-21 15:17:17 -0700769func (c *configImpl) KatiSuffix() string {
770 if c.katiSuffix != "" {
771 return c.katiSuffix
772 }
773 panic("SetKatiSuffix has not been called")
774}
775
Colin Cross37193492017-11-16 17:55:00 -0800776// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
777// user is interested in additional checks at the expense of build time.
778func (c *configImpl) Checkbuild() bool {
779 return c.checkbuild
780}
781
Dan Willemsen8a073a82017-02-04 17:30:44 -0800782func (c *configImpl) Dist() bool {
783 return c.dist
784}
785
Dan Willemsen1e704462016-08-21 15:17:17 -0700786func (c *configImpl) IsVerbose() bool {
787 return c.verbose
788}
789
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000790func (c *configImpl) SkipKati() bool {
791 return c.skipKati
792}
793
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100794func (c *configImpl) SkipNinja() bool {
795 return c.skipNinja
796}
797
Anton Hansson5a7861a2021-06-04 10:09:01 +0100798func (c *configImpl) SetSkipNinja(v bool) {
799 c.skipNinja = v
800}
801
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000802func (c *configImpl) SkipConfig() bool {
803 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -0700804}
805
Dan Willemsen1e704462016-08-21 15:17:17 -0700806func (c *configImpl) TargetProduct() string {
807 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
808 return v
809 }
810 panic("TARGET_PRODUCT is not defined")
811}
812
Dan Willemsen02781d52017-05-12 19:28:13 -0700813func (c *configImpl) TargetDevice() string {
814 return c.targetDevice
815}
816
817func (c *configImpl) SetTargetDevice(device string) {
818 c.targetDevice = device
819}
820
821func (c *configImpl) TargetBuildVariant() string {
822 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
823 return v
824 }
825 panic("TARGET_BUILD_VARIANT is not defined")
826}
827
Dan Willemsen1e704462016-08-21 15:17:17 -0700828func (c *configImpl) KatiArgs() []string {
829 return c.katiArgs
830}
831
832func (c *configImpl) Parallel() int {
833 return c.parallel
834}
835
Colin Cross8b8bec32019-11-15 13:18:43 -0800836func (c *configImpl) HighmemParallel() int {
837 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
838 return i
839 }
840
841 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
842 parallel := c.Parallel()
843 if c.UseRemoteBuild() {
844 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
845 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
846 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
847 // Return 1/16th of the size of the local pool, rounding up.
848 return (parallel + 15) / 16
849 } else if c.totalRAM == 0 {
850 // Couldn't detect the total RAM, don't restrict highmem processes.
851 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -0700852 } else if c.totalRAM <= 16*1024*1024*1024 {
853 // Less than 16GB of ram, restrict to 1 highmem processes
854 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -0800855 } else if c.totalRAM <= 32*1024*1024*1024 {
856 // Less than 32GB of ram, restrict to 2 highmem processes
857 return 2
858 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
859 // If less than 8GB total RAM per process, reduce the number of highmem processes
860 return p
861 }
862 // No restriction on highmem processes
863 return parallel
864}
865
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800866func (c *configImpl) TotalRAM() uint64 {
867 return c.totalRAM
868}
869
Kousik Kumarec478642020-09-21 13:39:24 -0400870// ForceUseGoma determines whether we should override Goma deprecation
871// and use Goma for the current build or not.
872func (c *configImpl) ForceUseGoma() bool {
873 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
874 v = strings.TrimSpace(v)
875 if v != "" && v != "false" {
876 return true
877 }
878 }
879 return false
880}
881
Dan Willemsen1e704462016-08-21 15:17:17 -0700882func (c *configImpl) UseGoma() bool {
883 if v, ok := c.environ.Get("USE_GOMA"); ok {
884 v = strings.TrimSpace(v)
885 if v != "" && v != "false" {
886 return true
887 }
888 }
889 return false
890}
891
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +0900892func (c *configImpl) StartGoma() bool {
893 if !c.UseGoma() {
894 return false
895 }
896
897 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
898 v = strings.TrimSpace(v)
899 if v != "" && v != "false" {
900 return false
901 }
902 }
903 return true
904}
905
Ramy Medhatbbf25672019-07-17 12:30:04 +0000906func (c *configImpl) UseRBE() bool {
907 if v, ok := c.environ.Get("USE_RBE"); ok {
908 v = strings.TrimSpace(v)
909 if v != "" && v != "false" {
910 return true
911 }
912 }
913 return false
914}
915
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800916func (c *configImpl) UseBazel() bool {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000917 return c.useBazel
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800918}
919
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400920func (c *configImpl) bazelBuildMode() bazelBuildMode {
921 if c.Environment().IsEnvTrue("USE_BAZEL_ANALYSIS") {
922 return mixedBuild
923 } else if c.Environment().IsEnvTrue("GENERATE_BAZEL_FILES") {
924 return generateBuildFiles
925 } else {
926 return noBazel
927 }
928}
929
Ramy Medhatbbf25672019-07-17 12:30:04 +0000930func (c *configImpl) StartRBE() bool {
931 if !c.UseRBE() {
932 return false
933 }
934
935 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
936 v = strings.TrimSpace(v)
937 if v != "" && v != "false" {
938 return false
939 }
940 }
941 return true
942}
943
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000944func (c *configImpl) rbeLogDir() string {
Kousik Kumar0d15a722020-09-23 02:54:11 -0400945 for _, f := range []string{"RBE_log_dir", "FLAG_log_dir"} {
946 if v, ok := c.environ.Get(f); ok {
947 return v
948 }
949 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400950 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000951 return c.LogsDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400952 }
953 return c.OutDir()
954}
955
956func (c *configImpl) rbeStatsOutputDir() string {
Patrice Arruda62f1bf22020-07-07 12:48:26 +0000957 for _, f := range []string{"RBE_output_dir", "FLAG_output_dir"} {
958 if v, ok := c.environ.Get(f); ok {
959 return v
960 }
961 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000962 return c.rbeLogDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400963}
964
965func (c *configImpl) rbeLogPath() string {
966 for _, f := range []string{"RBE_log_path", "FLAG_log_path"} {
967 if v, ok := c.environ.Get(f); ok {
968 return v
969 }
970 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000971 return fmt.Sprintf("text://%v/reproxy_log.txt", c.rbeLogDir())
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400972}
973
974func (c *configImpl) rbeExecRoot() string {
975 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
976 if v, ok := c.environ.Get(f); ok {
977 return v
978 }
979 }
980 wd, err := os.Getwd()
981 if err != nil {
982 return ""
983 }
984 return wd
985}
986
987func (c *configImpl) rbeDir() string {
988 if v, ok := c.environ.Get("RBE_DIR"); ok {
989 return v
990 }
991 return "prebuilts/remoteexecution-client/live/"
992}
993
994func (c *configImpl) rbeReproxy() string {
995 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
996 if v, ok := c.environ.Get(f); ok {
997 return v
998 }
999 }
1000 return filepath.Join(c.rbeDir(), "reproxy")
1001}
1002
1003func (c *configImpl) rbeAuth() (string, string) {
1004 credFlags := []string{"use_application_default_credentials", "use_gce_credentials", "credential_file"}
1005 for _, cf := range credFlags {
1006 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1007 if v, ok := c.environ.Get(f); ok {
1008 v = strings.TrimSpace(v)
1009 if v != "" && v != "false" && v != "0" {
1010 return "RBE_" + cf, v
1011 }
1012 }
1013 }
1014 }
1015 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001016}
1017
Colin Cross9016b912019-11-11 14:57:42 -08001018func (c *configImpl) UseRemoteBuild() bool {
1019 return c.UseGoma() || c.UseRBE()
1020}
1021
Dan Willemsen1e704462016-08-21 15:17:17 -07001022// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001023// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001024// still limited by Parallel()
1025func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001026 if !c.UseRemoteBuild() {
1027 return 0
1028 }
1029 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1030 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001031 }
1032 return 500
1033}
1034
1035func (c *configImpl) SetKatiArgs(args []string) {
1036 c.katiArgs = args
1037}
1038
1039func (c *configImpl) SetNinjaArgs(args []string) {
1040 c.ninjaArgs = args
1041}
1042
1043func (c *configImpl) SetKatiSuffix(suffix string) {
1044 c.katiSuffix = suffix
1045}
1046
Dan Willemsene0879fc2017-08-04 15:06:27 -07001047func (c *configImpl) LastKatiSuffixFile() string {
1048 return filepath.Join(c.OutDir(), "last_kati_suffix")
1049}
1050
1051func (c *configImpl) HasKatiSuffix() bool {
1052 return c.katiSuffix != ""
1053}
1054
Dan Willemsen1e704462016-08-21 15:17:17 -07001055func (c *configImpl) KatiEnvFile() string {
1056 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1057}
1058
Dan Willemsen29971232018-09-26 14:58:30 -07001059func (c *configImpl) KatiBuildNinjaFile() string {
1060 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001061}
1062
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001063func (c *configImpl) KatiPackageNinjaFile() string {
1064 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1065}
1066
Dan Willemsen1e704462016-08-21 15:17:17 -07001067func (c *configImpl) SoongNinjaFile() string {
1068 return filepath.Join(c.SoongOutDir(), "build.ninja")
1069}
1070
1071func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001072 if c.katiSuffix == "" {
1073 return filepath.Join(c.OutDir(), "combined.ninja")
1074 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001075 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1076}
1077
1078func (c *configImpl) SoongAndroidMk() string {
1079 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1080}
1081
1082func (c *configImpl) SoongMakeVarsMk() string {
1083 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1084}
1085
Dan Willemsenf052f782017-05-18 15:29:04 -07001086func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001087 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001088}
1089
Dan Willemsen02781d52017-05-12 19:28:13 -07001090func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001091 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1092}
1093
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001094func (c *configImpl) KatiPackageMkDir() string {
1095 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1096}
1097
Dan Willemsenf052f782017-05-18 15:29:04 -07001098func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001099 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001100}
1101
1102func (c *configImpl) HostOut() string {
1103 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1104}
1105
1106// This probably needs to be multi-valued, so not exporting it for now
1107func (c *configImpl) hostCrossOut() string {
1108 if runtime.GOOS == "linux" {
1109 return filepath.Join(c.hostOutRoot(), "windows-x86")
1110 } else {
1111 return ""
1112 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001113}
1114
Dan Willemsen1e704462016-08-21 15:17:17 -07001115func (c *configImpl) HostPrebuiltTag() string {
1116 if runtime.GOOS == "linux" {
1117 return "linux-x86"
1118 } else if runtime.GOOS == "darwin" {
1119 return "darwin-x86"
1120 } else {
1121 panic("Unsupported OS")
1122 }
1123}
Dan Willemsenf173d592017-04-27 14:28:00 -07001124
Dan Willemsen8122bd52017-10-12 20:20:41 -07001125func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001126 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1127 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001128 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1129 if _, err := os.Stat(asan); err == nil {
1130 return asan
1131 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001132 }
1133 }
1134 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1135}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001136
1137func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1138 c.brokenDupRules = val
1139}
1140
1141func (c *configImpl) BuildBrokenDupRules() bool {
1142 return c.brokenDupRules
1143}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001144
Dan Willemsen25e6f092019-04-09 10:22:43 -07001145func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1146 c.brokenUsesNetwork = val
1147}
1148
1149func (c *configImpl) BuildBrokenUsesNetwork() bool {
1150 return c.brokenUsesNetwork
1151}
1152
Dan Willemsene3336352020-01-02 19:10:38 -08001153func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1154 c.brokenNinjaEnvVars = val
1155}
1156
1157func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1158 return c.brokenNinjaEnvVars
1159}
1160
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001161func (c *configImpl) SetTargetDeviceDir(dir string) {
1162 c.targetDeviceDir = dir
1163}
1164
1165func (c *configImpl) TargetDeviceDir() string {
1166 return c.targetDeviceDir
1167}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001168
Patrice Arruda219eef32020-06-01 17:29:30 +00001169func (c *configImpl) BuildDateTime() string {
1170 return c.buildDateTime
1171}
1172
1173func (c *configImpl) MetricsUploaderApp() string {
1174 if p, ok := c.environ.Get("ANDROID_ENABLE_METRICS_UPLOAD"); ok {
1175 return p
1176 }
1177 return ""
1178}
Patrice Arruda83842d72020-12-08 19:42:08 +00001179
1180// LogsDir returns the logs directory where build log and metrics
1181// files are located. By default, the logs directory is the out
1182// directory. If the argument dist is specified, the logs directory
1183// is <dist_dir>/logs.
1184func (c *configImpl) LogsDir() string {
1185 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001186 // Always write logs to the real dist dir, even if Bazel is using a rigged dist dir for other files
1187 return filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001188 }
1189 return c.OutDir()
1190}
1191
1192// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1193// where the bazel profiles are located.
1194func (c *configImpl) BazelMetricsDir() string {
1195 return filepath.Join(c.LogsDir(), "bazel_metrics")
1196}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001197
1198func (c *configImpl) SetEmptyNinjaFile(v bool) {
1199 c.emptyNinjaFile = v
1200}
1201
1202func (c *configImpl) EmptyNinjaFile() bool {
1203 return c.emptyNinjaFile
1204}