blob: b9aaaf84e2714867335bba3ca9bf0ceae8766c55 [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
Anton Hansson0b55bdb2021-06-04 10:08:08 +010051 skipKatiNinja bool
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010052 skipNinja bool
Colin Cross00a8a3f2020-10-29 14:08:31 -070053 skipSoongTests bool
Dan Willemsen1e704462016-08-21 15:17:17 -070054
55 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070056 katiArgs []string
57 ninjaArgs []string
58 katiSuffix string
59 targetDevice string
60 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +000061 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -070062
Dan Willemsen2bb82d02019-12-27 09:35:42 -080063 // Autodetected
64 totalRAM uint64
65
Dan Willemsene3336352020-01-02 19:10:38 -080066 brokenDupRules bool
67 brokenUsesNetwork bool
68 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -070069
70 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +000071
72 useBazel bool
73
74 // During Bazel execution, Bazel cannot write outside OUT_DIR.
75 // 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.
76 riggedDistDirForBazel string
Colin Crossf3bdbcb2021-06-01 11:43:55 -070077
78 // Set by multiproduct_kati
79 emptyNinjaFile bool
Dan Willemsen1e704462016-08-21 15:17:17 -070080}
81
Dan Willemsenc2af0be2017-01-20 14:10:01 -080082const srcDirFileCheck = "build/soong/root.bp"
83
Patrice Arruda9450d0b2019-07-08 11:06:46 -070084var buildFiles = []string{"Android.mk", "Android.bp"}
85
Patrice Arruda13848222019-04-22 17:12:02 -070086type BuildAction uint
87
88const (
89 // Builds all of the modules and their dependencies of a specified directory, relative to the root
90 // directory of the source tree.
91 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
92
93 // Builds all of the modules and their dependencies of a list of specified directories. All specified
94 // directories are relative to the root directory of the source tree.
95 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -070096
97 // Build a list of specified modules. If none was specified, simply build the whole source tree.
98 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -070099)
100
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400101type bazelBuildMode int
102
103// Bazel-related build modes.
104const (
105 // Don't use bazel at all.
106 noBazel bazelBuildMode = iota
107
108 // Only generate build files (in a subdirectory of the out directory) and exit.
109 generateBuildFiles
110
111 // Generate synthetic build files and incorporate these files into a build which
112 // partially uses Bazel. Build metadata may come from Android.bp or BUILD files.
113 mixedBuild
114)
115
Patrice Arruda13848222019-04-22 17:12:02 -0700116// checkTopDir validates that the current directory is at the root directory of the source tree.
117func checkTopDir(ctx Context) {
118 if _, err := os.Stat(srcDirFileCheck); err != nil {
119 if os.IsNotExist(err) {
120 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
121 }
122 ctx.Fatalln("Error verifying tree state:", err)
123 }
124}
125
Dan Willemsen1e704462016-08-21 15:17:17 -0700126func NewConfig(ctx Context, args ...string) Config {
127 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000128 environ: OsEnvironment(),
129 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700130 }
131
Patrice Arruda90109172020-07-28 18:07:27 +0000132 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700133 ret.parallel = runtime.NumCPU() + 2
134 ret.keepGoing = 1
135
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800136 ret.totalRAM = detectTotalRAM(ctx)
137
Dan Willemsen9b587492017-07-10 22:13:00 -0700138 ret.parseArgs(ctx, args)
139
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800140 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700141 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
142 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
143 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800144 outDir := "out"
145 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
146 if wd, err := os.Getwd(); err != nil {
147 ctx.Fatalln("Failed to get working directory:", err)
148 } else {
149 outDir = filepath.Join(baseDir, filepath.Base(wd))
150 }
151 }
152 ret.environ.Set("OUT_DIR", outDir)
153 }
154
Dan Willemsen2d31a442018-10-20 21:33:41 -0700155 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
156 ret.distDir = filepath.Clean(distDir)
157 } else {
158 ret.distDir = filepath.Join(ret.OutDir(), "dist")
159 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700160
Dan Willemsen1e704462016-08-21 15:17:17 -0700161 ret.environ.Unset(
162 // We're already using it
163 "USE_SOONG_UI",
164
165 // We should never use GOROOT/GOPATH from the shell environment
166 "GOROOT",
167 "GOPATH",
168
169 // These should only come from Soong, not the environment.
170 "CLANG",
171 "CLANG_CXX",
172 "CCC_CC",
173 "CCC_CXX",
174
175 // Used by the goma compiler wrapper, but should only be set by
176 // gomacc
177 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800178
179 // We handle this above
180 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700181
Dan Willemsen2d31a442018-10-20 21:33:41 -0700182 // This is handled above too, and set for individual commands later
183 "DIST_DIR",
184
Dan Willemsen68a09852017-04-18 13:56:57 -0700185 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000186 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700187 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700188 "DISPLAY",
189 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700190 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700191 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700192
193 // Drop make flags
194 "MAKEFLAGS",
195 "MAKELEVEL",
196 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700197
198 // Set in envsetup.sh, reset in makefiles
199 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700200
201 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
202 "ANDROID_BUILD_TOP",
203 "ANDROID_HOST_OUT",
204 "ANDROID_PRODUCT_OUT",
205 "ANDROID_HOST_OUT_TESTCASES",
206 "ANDROID_TARGET_OUT_TESTCASES",
207 "ANDROID_TOOLCHAIN",
208 "ANDROID_TOOLCHAIN_2ND_ARCH",
209 "ANDROID_DEV_SCRIPTS",
210 "ANDROID_EMULATOR_PREBUILTS",
211 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700212 )
213
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400214 if ret.UseGoma() || ret.ForceUseGoma() {
215 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
216 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400217 }
218
Dan Willemsen1e704462016-08-21 15:17:17 -0700219 // Tell python not to spam the source tree with .pyc files.
220 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
221
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400222 tmpDir := absPath(ctx, ret.TempDir())
223 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800224
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700225 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
226 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
227 "llvm-binutils-stable/llvm-symbolizer")
228 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
229
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800230 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700231 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800232
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700233 if srcDir := absPath(ctx, "."); strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700234 ctx.Println("You are building in a directory whose absolute path contains a space character:")
235 ctx.Println()
236 ctx.Printf("%q\n", srcDir)
237 ctx.Println()
238 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700239 }
240
241 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700242 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
243 ctx.Println()
244 ctx.Printf("%q\n", outDir)
245 ctx.Println()
246 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700247 }
248
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000249 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700250 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
251 ctx.Println()
252 ctx.Printf("%q\n", distDir)
253 ctx.Println()
254 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700255 }
256
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700257 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000258 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
259 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100260 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700261 javaHome := func() string {
262 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
263 return override
264 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000265 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
266 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 +0100267 }
Pete Gillinabbcdda2019-10-28 16:15:33 +0000268 return java11Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700269 }()
270 absJavaHome := absPath(ctx, javaHome)
271
Dan Willemsened869522018-01-08 14:58:46 -0800272 ret.configureLocale(ctx)
273
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700274 newPath := []string{filepath.Join(absJavaHome, "bin")}
275 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
276 newPath = append(newPath, path)
277 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100278
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700279 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
280 ret.environ.Set("JAVA_HOME", absJavaHome)
281 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000282 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
283 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100284 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700285 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
286
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800287 outDir := ret.OutDir()
288 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800289 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800290 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800291 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800292 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800293 }
Colin Cross28f527c2019-11-26 16:19:04 -0800294
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800295 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
296
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400297 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400298 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400299 ret.environ.Set(k, v)
300 }
301 }
302
Patrice Arruda83842d72020-12-08 19:42:08 +0000303 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800304 if err := os.RemoveAll(bpd); err != nil {
305 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
306 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000307
308 ret.useBazel = ret.environ.IsEnvTrue("USE_BAZEL")
309
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800310 if ret.UseBazel() {
311 if err := os.MkdirAll(bpd, 0777); err != nil {
312 ctx.Fatalf("Failed to create bazel profile directory %q: %v", bpd, err)
313 }
314 }
315
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000316 if ret.UseBazel() {
317 ret.riggedDistDirForBazel = filepath.Join(ret.OutDir(), "dist")
318 } else {
319 // Not rigged
320 ret.riggedDistDirForBazel = ret.distDir
321 }
322
Patrice Arruda96850362020-08-11 20:41:11 +0000323 c := Config{ret}
324 storeConfigMetrics(ctx, c)
325 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700326}
327
Patrice Arruda13848222019-04-22 17:12:02 -0700328// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
329// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700330func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
331 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700332}
333
Patrice Arruda96850362020-08-11 20:41:11 +0000334// storeConfigMetrics selects a set of configuration information and store in
335// the metrics system for further analysis.
336func storeConfigMetrics(ctx Context, config Config) {
337 if ctx.Metrics == nil {
338 return
339 }
340
341 b := &smpb.BuildConfig{
Patrice Arrudac97d6dc2020-09-28 18:22:07 +0000342 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
343 UseGoma: proto.Bool(config.UseGoma()),
344 UseRbe: proto.Bool(config.UseRBE()),
Patrice Arruda96850362020-08-11 20:41:11 +0000345 }
346 ctx.Metrics.BuildConfig(b)
Patrice Arruda3edfd482020-10-13 23:58:41 +0000347
348 s := &smpb.SystemResourceInfo{
349 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
350 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
351 }
352 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000353}
354
Patrice Arruda13848222019-04-22 17:12:02 -0700355// getConfigArgs processes the command arguments based on the build action and creates a set of new
356// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700357func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700358 // The next block of code verifies that the current directory is the root directory of the source
359 // tree. It then finds the relative path of dir based on the root directory of the source tree
360 // and verify that dir is inside of the source tree.
361 checkTopDir(ctx)
362 topDir, err := os.Getwd()
363 if err != nil {
364 ctx.Fatalf("Error retrieving top directory: %v", err)
365 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700366 dir, err = filepath.EvalSymlinks(dir)
367 if err != nil {
368 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
369 }
Patrice Arruda13848222019-04-22 17:12:02 -0700370 dir, err = filepath.Abs(dir)
371 if err != nil {
372 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
373 }
374 relDir, err := filepath.Rel(topDir, dir)
375 if err != nil {
376 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
377 }
378 // If there are ".." in the path, it's not in the source tree.
379 if strings.Contains(relDir, "..") {
380 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
381 }
382
383 configArgs := args[:]
384
385 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
386 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
387 targetNamePrefix := "MODULES-IN-"
388 if inList("GET-INSTALL-PATH", configArgs) {
389 targetNamePrefix = "GET-INSTALL-PATH-IN-"
390 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
391 }
392
Patrice Arruda13848222019-04-22 17:12:02 -0700393 var targets []string
394
395 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700396 case BUILD_MODULES:
397 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700398 case BUILD_MODULES_IN_A_DIRECTORY:
399 // If dir is the root source tree, all the modules are built of the source tree are built so
400 // no need to find the build file.
401 if topDir == dir {
402 break
403 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700404
Patrice Arruda13848222019-04-22 17:12:02 -0700405 buildFile := findBuildFile(ctx, relDir)
406 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700407 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700408 }
Patrice Arruda13848222019-04-22 17:12:02 -0700409 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
410 case BUILD_MODULES_IN_DIRECTORIES:
411 newConfigArgs, dirs := splitArgs(configArgs)
412 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700413 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700414 }
415
416 // Tidy only override all other specified targets.
417 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
418 if tidyOnly == "true" || tidyOnly == "1" {
419 configArgs = append(configArgs, "tidy_only")
420 } else {
421 configArgs = append(configArgs, targets...)
422 }
423
424 return configArgs
425}
426
427// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
428func convertToTarget(dir string, targetNamePrefix string) string {
429 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
430}
431
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700432// hasBuildFile returns true if dir contains an Android build file.
433func hasBuildFile(ctx Context, dir string) bool {
434 for _, buildFile := range buildFiles {
435 _, err := os.Stat(filepath.Join(dir, buildFile))
436 if err == nil {
437 return true
438 }
439 if !os.IsNotExist(err) {
440 ctx.Fatalf("Error retrieving the build file stats: %v", err)
441 }
442 }
443 return false
444}
445
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700446// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
447// in the current and any sub directory of dir. If a build file is not found, traverse the path
448// up by one directory and repeat again until either a build file is found or reached to the root
449// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
450// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700451func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700452 // If the string is empty or ".", assume it is top directory of the source tree.
453 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700454 return ""
455 }
456
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700457 found := false
458 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
459 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
460 if err != nil {
461 return err
462 }
463 if found {
464 return filepath.SkipDir
465 }
466 if info.IsDir() {
467 return nil
468 }
469 for _, buildFile := range buildFiles {
470 if info.Name() == buildFile {
471 found = true
472 return filepath.SkipDir
473 }
474 }
475 return nil
476 })
477 if err != nil {
478 ctx.Fatalf("Error finding Android build file: %v", err)
479 }
480
481 if found {
482 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700483 }
484 }
485
486 return ""
487}
488
489// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
490func splitArgs(args []string) (newArgs []string, dirs []string) {
491 specialArgs := map[string]bool{
492 "showcommands": true,
493 "snod": true,
494 "dist": true,
495 "checkbuild": true,
496 }
497
498 newArgs = []string{}
499 dirs = []string{}
500
501 for _, arg := range args {
502 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
503 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
504 newArgs = append(newArgs, arg)
505 continue
506 }
507
508 if _, ok := specialArgs[arg]; ok {
509 newArgs = append(newArgs, arg)
510 continue
511 }
512
513 dirs = append(dirs, arg)
514 }
515
516 return newArgs, dirs
517}
518
519// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
520// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
521// source root tree where the build action command was invoked. Each directory is validated if the
522// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700523func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700524 for _, dir := range dirs {
525 // The directory may have specified specific modules to build. ":" is the separator to separate
526 // the directory and the list of modules.
527 s := strings.Split(dir, ":")
528 l := len(s)
529 if l > 2 { // more than one ":" was specified.
530 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
531 }
532
533 dir = filepath.Join(relDir, s[0])
534 if _, err := os.Stat(dir); err != nil {
535 ctx.Fatalf("couldn't find directory %s", dir)
536 }
537
538 // Verify that if there are any targets specified after ":". Each target is separated by ",".
539 var newTargets []string
540 if l == 2 && s[1] != "" {
541 newTargets = strings.Split(s[1], ",")
542 if inList("", newTargets) {
543 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
544 }
545 }
546
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700547 // If there are specified targets to build in dir, an android build file must exist for the one
548 // shot build. For the non-targets case, find the appropriate build file and build all the
549 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700550 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700551 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700552 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
553 }
554 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700555 buildFile := findBuildFile(ctx, dir)
556 if buildFile == "" {
557 ctx.Fatalf("Build file not found for %s directory", dir)
558 }
559 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700560 }
561
Patrice Arruda13848222019-04-22 17:12:02 -0700562 targets = append(targets, newTargets...)
563 }
564
Dan Willemsence41e942019-07-29 23:39:30 -0700565 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700566}
567
Dan Willemsen9b587492017-07-10 22:13:00 -0700568func (c *configImpl) parseArgs(ctx Context, args []string) {
569 for i := 0; i < len(args); i++ {
570 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100571 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700572 c.verbose = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100573 } else if arg == "--skip-ninja" {
574 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700575 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700576 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
577 // but it does run a Kati ninja file if the .kati_enabled marker file was created
578 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000579 c.skipConfig = true
580 c.skipKati = true
581 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100582 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000583 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100584 } else if arg == "--soong-only" {
585 c.skipKati = true
586 c.skipKatiNinja = true
Colin Cross30e444b2021-06-18 11:26:19 -0700587 } else if arg == "--skip-config" {
588 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700589 } else if arg == "--skip-soong-tests" {
590 c.skipSoongTests = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700591 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700592 parseArgNum := func(def int) int {
593 if len(arg) > 2 {
594 p, err := strconv.ParseUint(arg[2:], 10, 31)
595 if err != nil {
596 ctx.Fatalf("Failed to parse %q: %v", arg, err)
597 }
598 return int(p)
599 } else if i+1 < len(args) {
600 p, err := strconv.ParseUint(args[i+1], 10, 31)
601 if err == nil {
602 i++
603 return int(p)
604 }
605 }
606 return def
607 }
608
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700609 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700610 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700611 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700612 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700613 } else {
614 ctx.Fatalln("Unknown option:", arg)
615 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700616 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700617 if k == "OUT_DIR" {
618 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
619 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700620 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700621 } else if arg == "dist" {
622 c.dist = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700623 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700624 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800625 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700626 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700627 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700628 }
629 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700630}
631
Dan Willemsened869522018-01-08 14:58:46 -0800632func (c *configImpl) configureLocale(ctx Context) {
633 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
634 output, err := cmd.Output()
635
636 var locales []string
637 if err == nil {
638 locales = strings.Split(string(output), "\n")
639 } else {
640 // If we're unable to list the locales, let's assume en_US.UTF-8
641 locales = []string{"en_US.UTF-8"}
642 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
643 }
644
645 // gettext uses LANGUAGE, which is passed directly through
646
647 // For LANG and LC_*, only preserve the evaluated version of
648 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800649 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800650 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800651 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800652 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800653 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800654 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800655 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800656 }
657
658 c.environ.UnsetWithPrefix("LC_")
659
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800660 if userLang != "" {
661 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800662 }
663
664 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
665 // for others)
666 if inList("C.UTF-8", locales) {
667 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500668 } else if inList("C.utf8", locales) {
669 // These normalize to the same thing
670 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800671 } else if inList("en_US.UTF-8", locales) {
672 c.environ.Set("LANG", "en_US.UTF-8")
673 } else if inList("en_US.utf8", locales) {
674 // These normalize to the same thing
675 c.environ.Set("LANG", "en_US.UTF-8")
676 } else {
677 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
678 }
679}
680
Dan Willemsen1e704462016-08-21 15:17:17 -0700681// Lunch configures the environment for a specific product similarly to the
682// `lunch` bash function.
683func (c *configImpl) Lunch(ctx Context, product, variant string) {
684 if variant != "eng" && variant != "userdebug" && variant != "user" {
685 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
686 }
687
688 c.environ.Set("TARGET_PRODUCT", product)
689 c.environ.Set("TARGET_BUILD_VARIANT", variant)
690 c.environ.Set("TARGET_BUILD_TYPE", "release")
691 c.environ.Unset("TARGET_BUILD_APPS")
Martin Stjernholm08802332020-06-04 17:00:01 +0100692 c.environ.Unset("TARGET_BUILD_UNBUNDLED")
Dan Willemsen1e704462016-08-21 15:17:17 -0700693}
694
695// Tapas configures the environment to build one or more unbundled apps,
696// similarly to the `tapas` bash function.
697func (c *configImpl) Tapas(ctx Context, apps []string, arch, variant string) {
698 if len(apps) == 0 {
699 apps = []string{"all"}
700 }
701 if variant == "" {
702 variant = "eng"
703 }
704
705 if variant != "eng" && variant != "userdebug" && variant != "user" {
706 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
707 }
708
709 var product string
710 switch arch {
Dan Willemsen1e704462016-08-21 15:17:17 -0700711 case "arm", "":
712 product = "aosp_arm"
713 case "arm64":
714 product = "aosm_arm64"
Dan Willemsen1e704462016-08-21 15:17:17 -0700715 case "x86":
716 product = "aosp_x86"
717 case "x86_64":
718 product = "aosp_x86_64"
719 default:
720 ctx.Fatalf("Invalid architecture: %q", arch)
721 }
722
723 c.environ.Set("TARGET_PRODUCT", product)
724 c.environ.Set("TARGET_BUILD_VARIANT", variant)
725 c.environ.Set("TARGET_BUILD_TYPE", "release")
726 c.environ.Set("TARGET_BUILD_APPS", strings.Join(apps, " "))
727}
728
729func (c *configImpl) Environment() *Environment {
730 return c.environ
731}
732
733func (c *configImpl) Arguments() []string {
734 return c.arguments
735}
736
737func (c *configImpl) OutDir() string {
738 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700739 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700740 }
741 return "out"
742}
743
Dan Willemsen8a073a82017-02-04 17:30:44 -0800744func (c *configImpl) DistDir() string {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000745 if c.UseBazel() {
746 return c.riggedDistDirForBazel
747 } else {
748 return c.distDir
749 }
750}
751
752func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700753 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800754}
755
Dan Willemsen1e704462016-08-21 15:17:17 -0700756func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000757 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700758 return c.arguments
759 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700760 return c.ninjaArgs
761}
762
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500763func (c *configImpl) BazelOutDir() string {
764 return filepath.Join(c.OutDir(), "bazel")
765}
766
Dan Willemsen1e704462016-08-21 15:17:17 -0700767func (c *configImpl) SoongOutDir() string {
768 return filepath.Join(c.OutDir(), "soong")
769}
770
Jeff Gastonefc1b412017-03-29 17:29:06 -0700771func (c *configImpl) TempDir() string {
772 return shared.TempDirForOutDir(c.SoongOutDir())
773}
774
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700775func (c *configImpl) FileListDir() string {
776 return filepath.Join(c.OutDir(), ".module_paths")
777}
778
Dan Willemsen1e704462016-08-21 15:17:17 -0700779func (c *configImpl) KatiSuffix() string {
780 if c.katiSuffix != "" {
781 return c.katiSuffix
782 }
783 panic("SetKatiSuffix has not been called")
784}
785
Colin Cross37193492017-11-16 17:55:00 -0800786// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
787// user is interested in additional checks at the expense of build time.
788func (c *configImpl) Checkbuild() bool {
789 return c.checkbuild
790}
791
Dan Willemsen8a073a82017-02-04 17:30:44 -0800792func (c *configImpl) Dist() bool {
793 return c.dist
794}
795
Dan Willemsen1e704462016-08-21 15:17:17 -0700796func (c *configImpl) IsVerbose() bool {
797 return c.verbose
798}
799
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000800func (c *configImpl) SkipKati() bool {
801 return c.skipKati
802}
803
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100804func (c *configImpl) SkipKatiNinja() bool {
805 return c.skipKatiNinja
806}
807
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100808func (c *configImpl) SkipNinja() bool {
809 return c.skipNinja
810}
811
Anton Hansson5a7861a2021-06-04 10:09:01 +0100812func (c *configImpl) SetSkipNinja(v bool) {
813 c.skipNinja = v
814}
815
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000816func (c *configImpl) SkipConfig() bool {
817 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -0700818}
819
Dan Willemsen1e704462016-08-21 15:17:17 -0700820func (c *configImpl) TargetProduct() string {
821 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
822 return v
823 }
824 panic("TARGET_PRODUCT is not defined")
825}
826
Dan Willemsen02781d52017-05-12 19:28:13 -0700827func (c *configImpl) TargetDevice() string {
828 return c.targetDevice
829}
830
831func (c *configImpl) SetTargetDevice(device string) {
832 c.targetDevice = device
833}
834
835func (c *configImpl) TargetBuildVariant() string {
836 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
837 return v
838 }
839 panic("TARGET_BUILD_VARIANT is not defined")
840}
841
Dan Willemsen1e704462016-08-21 15:17:17 -0700842func (c *configImpl) KatiArgs() []string {
843 return c.katiArgs
844}
845
846func (c *configImpl) Parallel() int {
847 return c.parallel
848}
849
Colin Cross8b8bec32019-11-15 13:18:43 -0800850func (c *configImpl) HighmemParallel() int {
851 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
852 return i
853 }
854
855 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
856 parallel := c.Parallel()
857 if c.UseRemoteBuild() {
858 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
859 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
860 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
861 // Return 1/16th of the size of the local pool, rounding up.
862 return (parallel + 15) / 16
863 } else if c.totalRAM == 0 {
864 // Couldn't detect the total RAM, don't restrict highmem processes.
865 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -0700866 } else if c.totalRAM <= 16*1024*1024*1024 {
867 // Less than 16GB of ram, restrict to 1 highmem processes
868 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -0800869 } else if c.totalRAM <= 32*1024*1024*1024 {
870 // Less than 32GB of ram, restrict to 2 highmem processes
871 return 2
872 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
873 // If less than 8GB total RAM per process, reduce the number of highmem processes
874 return p
875 }
876 // No restriction on highmem processes
877 return parallel
878}
879
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800880func (c *configImpl) TotalRAM() uint64 {
881 return c.totalRAM
882}
883
Kousik Kumarec478642020-09-21 13:39:24 -0400884// ForceUseGoma determines whether we should override Goma deprecation
885// and use Goma for the current build or not.
886func (c *configImpl) ForceUseGoma() bool {
887 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
888 v = strings.TrimSpace(v)
889 if v != "" && v != "false" {
890 return true
891 }
892 }
893 return false
894}
895
Dan Willemsen1e704462016-08-21 15:17:17 -0700896func (c *configImpl) UseGoma() bool {
897 if v, ok := c.environ.Get("USE_GOMA"); ok {
898 v = strings.TrimSpace(v)
899 if v != "" && v != "false" {
900 return true
901 }
902 }
903 return false
904}
905
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +0900906func (c *configImpl) StartGoma() bool {
907 if !c.UseGoma() {
908 return false
909 }
910
911 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
912 v = strings.TrimSpace(v)
913 if v != "" && v != "false" {
914 return false
915 }
916 }
917 return true
918}
919
Ramy Medhatbbf25672019-07-17 12:30:04 +0000920func (c *configImpl) UseRBE() bool {
921 if v, ok := c.environ.Get("USE_RBE"); ok {
922 v = strings.TrimSpace(v)
923 if v != "" && v != "false" {
924 return true
925 }
926 }
927 return false
928}
929
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800930func (c *configImpl) UseBazel() bool {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000931 return c.useBazel
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800932}
933
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400934func (c *configImpl) bazelBuildMode() bazelBuildMode {
935 if c.Environment().IsEnvTrue("USE_BAZEL_ANALYSIS") {
936 return mixedBuild
937 } else if c.Environment().IsEnvTrue("GENERATE_BAZEL_FILES") {
938 return generateBuildFiles
939 } else {
940 return noBazel
941 }
942}
943
Ramy Medhatbbf25672019-07-17 12:30:04 +0000944func (c *configImpl) StartRBE() bool {
945 if !c.UseRBE() {
946 return false
947 }
948
949 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
950 v = strings.TrimSpace(v)
951 if v != "" && v != "false" {
952 return false
953 }
954 }
955 return true
956}
957
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000958func (c *configImpl) rbeLogDir() string {
Kousik Kumar0d15a722020-09-23 02:54:11 -0400959 for _, f := range []string{"RBE_log_dir", "FLAG_log_dir"} {
960 if v, ok := c.environ.Get(f); ok {
961 return v
962 }
963 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400964 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000965 return c.LogsDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400966 }
967 return c.OutDir()
968}
969
970func (c *configImpl) rbeStatsOutputDir() string {
Patrice Arruda62f1bf22020-07-07 12:48:26 +0000971 for _, f := range []string{"RBE_output_dir", "FLAG_output_dir"} {
972 if v, ok := c.environ.Get(f); ok {
973 return v
974 }
975 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000976 return c.rbeLogDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400977}
978
979func (c *configImpl) rbeLogPath() string {
980 for _, f := range []string{"RBE_log_path", "FLAG_log_path"} {
981 if v, ok := c.environ.Get(f); ok {
982 return v
983 }
984 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000985 return fmt.Sprintf("text://%v/reproxy_log.txt", c.rbeLogDir())
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400986}
987
988func (c *configImpl) rbeExecRoot() string {
989 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
990 if v, ok := c.environ.Get(f); ok {
991 return v
992 }
993 }
994 wd, err := os.Getwd()
995 if err != nil {
996 return ""
997 }
998 return wd
999}
1000
1001func (c *configImpl) rbeDir() string {
1002 if v, ok := c.environ.Get("RBE_DIR"); ok {
1003 return v
1004 }
1005 return "prebuilts/remoteexecution-client/live/"
1006}
1007
1008func (c *configImpl) rbeReproxy() string {
1009 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1010 if v, ok := c.environ.Get(f); ok {
1011 return v
1012 }
1013 }
1014 return filepath.Join(c.rbeDir(), "reproxy")
1015}
1016
1017func (c *configImpl) rbeAuth() (string, string) {
1018 credFlags := []string{"use_application_default_credentials", "use_gce_credentials", "credential_file"}
1019 for _, cf := range credFlags {
1020 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1021 if v, ok := c.environ.Get(f); ok {
1022 v = strings.TrimSpace(v)
1023 if v != "" && v != "false" && v != "0" {
1024 return "RBE_" + cf, v
1025 }
1026 }
1027 }
1028 }
1029 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001030}
1031
Colin Cross9016b912019-11-11 14:57:42 -08001032func (c *configImpl) UseRemoteBuild() bool {
1033 return c.UseGoma() || c.UseRBE()
1034}
1035
Dan Willemsen1e704462016-08-21 15:17:17 -07001036// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001037// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001038// still limited by Parallel()
1039func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001040 if !c.UseRemoteBuild() {
1041 return 0
1042 }
1043 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1044 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001045 }
1046 return 500
1047}
1048
1049func (c *configImpl) SetKatiArgs(args []string) {
1050 c.katiArgs = args
1051}
1052
1053func (c *configImpl) SetNinjaArgs(args []string) {
1054 c.ninjaArgs = args
1055}
1056
1057func (c *configImpl) SetKatiSuffix(suffix string) {
1058 c.katiSuffix = suffix
1059}
1060
Dan Willemsene0879fc2017-08-04 15:06:27 -07001061func (c *configImpl) LastKatiSuffixFile() string {
1062 return filepath.Join(c.OutDir(), "last_kati_suffix")
1063}
1064
1065func (c *configImpl) HasKatiSuffix() bool {
1066 return c.katiSuffix != ""
1067}
1068
Dan Willemsen1e704462016-08-21 15:17:17 -07001069func (c *configImpl) KatiEnvFile() string {
1070 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1071}
1072
Dan Willemsen29971232018-09-26 14:58:30 -07001073func (c *configImpl) KatiBuildNinjaFile() string {
1074 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001075}
1076
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001077func (c *configImpl) KatiPackageNinjaFile() string {
1078 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1079}
1080
Dan Willemsen1e704462016-08-21 15:17:17 -07001081func (c *configImpl) SoongNinjaFile() string {
1082 return filepath.Join(c.SoongOutDir(), "build.ninja")
1083}
1084
1085func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001086 if c.katiSuffix == "" {
1087 return filepath.Join(c.OutDir(), "combined.ninja")
1088 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001089 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1090}
1091
1092func (c *configImpl) SoongAndroidMk() string {
1093 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1094}
1095
1096func (c *configImpl) SoongMakeVarsMk() string {
1097 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1098}
1099
Dan Willemsenf052f782017-05-18 15:29:04 -07001100func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001101 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001102}
1103
Dan Willemsen02781d52017-05-12 19:28:13 -07001104func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001105 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1106}
1107
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001108func (c *configImpl) KatiPackageMkDir() string {
1109 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1110}
1111
Dan Willemsenf052f782017-05-18 15:29:04 -07001112func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001113 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001114}
1115
1116func (c *configImpl) HostOut() string {
1117 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1118}
1119
1120// This probably needs to be multi-valued, so not exporting it for now
1121func (c *configImpl) hostCrossOut() string {
1122 if runtime.GOOS == "linux" {
1123 return filepath.Join(c.hostOutRoot(), "windows-x86")
1124 } else {
1125 return ""
1126 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001127}
1128
Dan Willemsen1e704462016-08-21 15:17:17 -07001129func (c *configImpl) HostPrebuiltTag() string {
1130 if runtime.GOOS == "linux" {
1131 return "linux-x86"
1132 } else if runtime.GOOS == "darwin" {
1133 return "darwin-x86"
1134 } else {
1135 panic("Unsupported OS")
1136 }
1137}
Dan Willemsenf173d592017-04-27 14:28:00 -07001138
Dan Willemsen8122bd52017-10-12 20:20:41 -07001139func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001140 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1141 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001142 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1143 if _, err := os.Stat(asan); err == nil {
1144 return asan
1145 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001146 }
1147 }
1148 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1149}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001150
1151func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1152 c.brokenDupRules = val
1153}
1154
1155func (c *configImpl) BuildBrokenDupRules() bool {
1156 return c.brokenDupRules
1157}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001158
Dan Willemsen25e6f092019-04-09 10:22:43 -07001159func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1160 c.brokenUsesNetwork = val
1161}
1162
1163func (c *configImpl) BuildBrokenUsesNetwork() bool {
1164 return c.brokenUsesNetwork
1165}
1166
Dan Willemsene3336352020-01-02 19:10:38 -08001167func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1168 c.brokenNinjaEnvVars = val
1169}
1170
1171func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1172 return c.brokenNinjaEnvVars
1173}
1174
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001175func (c *configImpl) SetTargetDeviceDir(dir string) {
1176 c.targetDeviceDir = dir
1177}
1178
1179func (c *configImpl) TargetDeviceDir() string {
1180 return c.targetDeviceDir
1181}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001182
Patrice Arruda219eef32020-06-01 17:29:30 +00001183func (c *configImpl) BuildDateTime() string {
1184 return c.buildDateTime
1185}
1186
1187func (c *configImpl) MetricsUploaderApp() string {
1188 if p, ok := c.environ.Get("ANDROID_ENABLE_METRICS_UPLOAD"); ok {
1189 return p
1190 }
1191 return ""
1192}
Patrice Arruda83842d72020-12-08 19:42:08 +00001193
1194// LogsDir returns the logs directory where build log and metrics
1195// files are located. By default, the logs directory is the out
1196// directory. If the argument dist is specified, the logs directory
1197// is <dist_dir>/logs.
1198func (c *configImpl) LogsDir() string {
1199 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001200 // Always write logs to the real dist dir, even if Bazel is using a rigged dist dir for other files
1201 return filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001202 }
1203 return c.OutDir()
1204}
1205
1206// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1207// where the bazel profiles are located.
1208func (c *configImpl) BazelMetricsDir() string {
1209 return filepath.Join(c.LogsDir(), "bazel_metrics")
1210}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001211
1212func (c *configImpl) SetEmptyNinjaFile(v bool) {
1213 c.emptyNinjaFile = v
1214}
1215
1216func (c *configImpl) EmptyNinjaFile() bool {
1217 return c.emptyNinjaFile
1218}