blob: 220e734f07e96ed7d417dbdc6043a7d07c10204e [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" {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000576 c.skipConfig = true
577 c.skipKati = true
578 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100579 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000580 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100581 } else if arg == "--soong-only" {
582 c.skipKati = true
583 c.skipKatiNinja = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700584 } else if arg == "--skip-soong-tests" {
585 c.skipSoongTests = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700586 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700587 parseArgNum := func(def int) int {
588 if len(arg) > 2 {
589 p, err := strconv.ParseUint(arg[2:], 10, 31)
590 if err != nil {
591 ctx.Fatalf("Failed to parse %q: %v", arg, err)
592 }
593 return int(p)
594 } else if i+1 < len(args) {
595 p, err := strconv.ParseUint(args[i+1], 10, 31)
596 if err == nil {
597 i++
598 return int(p)
599 }
600 }
601 return def
602 }
603
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700604 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700605 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700606 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700607 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700608 } else {
609 ctx.Fatalln("Unknown option:", arg)
610 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700611 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700612 if k == "OUT_DIR" {
613 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
614 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700615 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700616 } else if arg == "dist" {
617 c.dist = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700618 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700619 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800620 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700621 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700622 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700623 }
624 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700625}
626
Dan Willemsened869522018-01-08 14:58:46 -0800627func (c *configImpl) configureLocale(ctx Context) {
628 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
629 output, err := cmd.Output()
630
631 var locales []string
632 if err == nil {
633 locales = strings.Split(string(output), "\n")
634 } else {
635 // If we're unable to list the locales, let's assume en_US.UTF-8
636 locales = []string{"en_US.UTF-8"}
637 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
638 }
639
640 // gettext uses LANGUAGE, which is passed directly through
641
642 // For LANG and LC_*, only preserve the evaluated version of
643 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800644 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800645 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800646 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800647 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800648 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800649 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800650 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800651 }
652
653 c.environ.UnsetWithPrefix("LC_")
654
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800655 if userLang != "" {
656 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800657 }
658
659 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
660 // for others)
661 if inList("C.UTF-8", locales) {
662 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500663 } else if inList("C.utf8", locales) {
664 // These normalize to the same thing
665 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800666 } else if inList("en_US.UTF-8", locales) {
667 c.environ.Set("LANG", "en_US.UTF-8")
668 } else if inList("en_US.utf8", locales) {
669 // These normalize to the same thing
670 c.environ.Set("LANG", "en_US.UTF-8")
671 } else {
672 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
673 }
674}
675
Dan Willemsen1e704462016-08-21 15:17:17 -0700676// Lunch configures the environment for a specific product similarly to the
677// `lunch` bash function.
678func (c *configImpl) Lunch(ctx Context, product, variant string) {
679 if variant != "eng" && variant != "userdebug" && variant != "user" {
680 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
681 }
682
683 c.environ.Set("TARGET_PRODUCT", product)
684 c.environ.Set("TARGET_BUILD_VARIANT", variant)
685 c.environ.Set("TARGET_BUILD_TYPE", "release")
686 c.environ.Unset("TARGET_BUILD_APPS")
Martin Stjernholm08802332020-06-04 17:00:01 +0100687 c.environ.Unset("TARGET_BUILD_UNBUNDLED")
Dan Willemsen1e704462016-08-21 15:17:17 -0700688}
689
690// Tapas configures the environment to build one or more unbundled apps,
691// similarly to the `tapas` bash function.
692func (c *configImpl) Tapas(ctx Context, apps []string, arch, variant string) {
693 if len(apps) == 0 {
694 apps = []string{"all"}
695 }
696 if variant == "" {
697 variant = "eng"
698 }
699
700 if variant != "eng" && variant != "userdebug" && variant != "user" {
701 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
702 }
703
704 var product string
705 switch arch {
Dan Willemsen1e704462016-08-21 15:17:17 -0700706 case "arm", "":
707 product = "aosp_arm"
708 case "arm64":
709 product = "aosm_arm64"
Dan Willemsen1e704462016-08-21 15:17:17 -0700710 case "x86":
711 product = "aosp_x86"
712 case "x86_64":
713 product = "aosp_x86_64"
714 default:
715 ctx.Fatalf("Invalid architecture: %q", arch)
716 }
717
718 c.environ.Set("TARGET_PRODUCT", product)
719 c.environ.Set("TARGET_BUILD_VARIANT", variant)
720 c.environ.Set("TARGET_BUILD_TYPE", "release")
721 c.environ.Set("TARGET_BUILD_APPS", strings.Join(apps, " "))
722}
723
724func (c *configImpl) Environment() *Environment {
725 return c.environ
726}
727
728func (c *configImpl) Arguments() []string {
729 return c.arguments
730}
731
732func (c *configImpl) OutDir() string {
733 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700734 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700735 }
736 return "out"
737}
738
Dan Willemsen8a073a82017-02-04 17:30:44 -0800739func (c *configImpl) DistDir() string {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000740 if c.UseBazel() {
741 return c.riggedDistDirForBazel
742 } else {
743 return c.distDir
744 }
745}
746
747func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700748 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800749}
750
Dan Willemsen1e704462016-08-21 15:17:17 -0700751func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000752 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700753 return c.arguments
754 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700755 return c.ninjaArgs
756}
757
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500758func (c *configImpl) BazelOutDir() string {
759 return filepath.Join(c.OutDir(), "bazel")
760}
761
Dan Willemsen1e704462016-08-21 15:17:17 -0700762func (c *configImpl) SoongOutDir() string {
763 return filepath.Join(c.OutDir(), "soong")
764}
765
Jeff Gastonefc1b412017-03-29 17:29:06 -0700766func (c *configImpl) TempDir() string {
767 return shared.TempDirForOutDir(c.SoongOutDir())
768}
769
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700770func (c *configImpl) FileListDir() string {
771 return filepath.Join(c.OutDir(), ".module_paths")
772}
773
Dan Willemsen1e704462016-08-21 15:17:17 -0700774func (c *configImpl) KatiSuffix() string {
775 if c.katiSuffix != "" {
776 return c.katiSuffix
777 }
778 panic("SetKatiSuffix has not been called")
779}
780
Colin Cross37193492017-11-16 17:55:00 -0800781// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
782// user is interested in additional checks at the expense of build time.
783func (c *configImpl) Checkbuild() bool {
784 return c.checkbuild
785}
786
Dan Willemsen8a073a82017-02-04 17:30:44 -0800787func (c *configImpl) Dist() bool {
788 return c.dist
789}
790
Dan Willemsen1e704462016-08-21 15:17:17 -0700791func (c *configImpl) IsVerbose() bool {
792 return c.verbose
793}
794
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000795func (c *configImpl) SkipKati() bool {
796 return c.skipKati
797}
798
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100799func (c *configImpl) SkipKatiNinja() bool {
800 return c.skipKatiNinja
801}
802
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100803func (c *configImpl) SkipNinja() bool {
804 return c.skipNinja
805}
806
Anton Hansson5a7861a2021-06-04 10:09:01 +0100807func (c *configImpl) SetSkipNinja(v bool) {
808 c.skipNinja = v
809}
810
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000811func (c *configImpl) SkipConfig() bool {
812 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -0700813}
814
Dan Willemsen1e704462016-08-21 15:17:17 -0700815func (c *configImpl) TargetProduct() string {
816 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
817 return v
818 }
819 panic("TARGET_PRODUCT is not defined")
820}
821
Dan Willemsen02781d52017-05-12 19:28:13 -0700822func (c *configImpl) TargetDevice() string {
823 return c.targetDevice
824}
825
826func (c *configImpl) SetTargetDevice(device string) {
827 c.targetDevice = device
828}
829
830func (c *configImpl) TargetBuildVariant() string {
831 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
832 return v
833 }
834 panic("TARGET_BUILD_VARIANT is not defined")
835}
836
Dan Willemsen1e704462016-08-21 15:17:17 -0700837func (c *configImpl) KatiArgs() []string {
838 return c.katiArgs
839}
840
841func (c *configImpl) Parallel() int {
842 return c.parallel
843}
844
Colin Cross8b8bec32019-11-15 13:18:43 -0800845func (c *configImpl) HighmemParallel() int {
846 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
847 return i
848 }
849
850 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
851 parallel := c.Parallel()
852 if c.UseRemoteBuild() {
853 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
854 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
855 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
856 // Return 1/16th of the size of the local pool, rounding up.
857 return (parallel + 15) / 16
858 } else if c.totalRAM == 0 {
859 // Couldn't detect the total RAM, don't restrict highmem processes.
860 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -0700861 } else if c.totalRAM <= 16*1024*1024*1024 {
862 // Less than 16GB of ram, restrict to 1 highmem processes
863 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -0800864 } else if c.totalRAM <= 32*1024*1024*1024 {
865 // Less than 32GB of ram, restrict to 2 highmem processes
866 return 2
867 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
868 // If less than 8GB total RAM per process, reduce the number of highmem processes
869 return p
870 }
871 // No restriction on highmem processes
872 return parallel
873}
874
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800875func (c *configImpl) TotalRAM() uint64 {
876 return c.totalRAM
877}
878
Kousik Kumarec478642020-09-21 13:39:24 -0400879// ForceUseGoma determines whether we should override Goma deprecation
880// and use Goma for the current build or not.
881func (c *configImpl) ForceUseGoma() bool {
882 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
883 v = strings.TrimSpace(v)
884 if v != "" && v != "false" {
885 return true
886 }
887 }
888 return false
889}
890
Dan Willemsen1e704462016-08-21 15:17:17 -0700891func (c *configImpl) UseGoma() bool {
892 if v, ok := c.environ.Get("USE_GOMA"); ok {
893 v = strings.TrimSpace(v)
894 if v != "" && v != "false" {
895 return true
896 }
897 }
898 return false
899}
900
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +0900901func (c *configImpl) StartGoma() bool {
902 if !c.UseGoma() {
903 return false
904 }
905
906 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
907 v = strings.TrimSpace(v)
908 if v != "" && v != "false" {
909 return false
910 }
911 }
912 return true
913}
914
Ramy Medhatbbf25672019-07-17 12:30:04 +0000915func (c *configImpl) UseRBE() bool {
916 if v, ok := c.environ.Get("USE_RBE"); ok {
917 v = strings.TrimSpace(v)
918 if v != "" && v != "false" {
919 return true
920 }
921 }
922 return false
923}
924
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800925func (c *configImpl) UseBazel() bool {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000926 return c.useBazel
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800927}
928
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400929func (c *configImpl) bazelBuildMode() bazelBuildMode {
930 if c.Environment().IsEnvTrue("USE_BAZEL_ANALYSIS") {
931 return mixedBuild
932 } else if c.Environment().IsEnvTrue("GENERATE_BAZEL_FILES") {
933 return generateBuildFiles
934 } else {
935 return noBazel
936 }
937}
938
Ramy Medhatbbf25672019-07-17 12:30:04 +0000939func (c *configImpl) StartRBE() bool {
940 if !c.UseRBE() {
941 return false
942 }
943
944 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
945 v = strings.TrimSpace(v)
946 if v != "" && v != "false" {
947 return false
948 }
949 }
950 return true
951}
952
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000953func (c *configImpl) rbeLogDir() string {
Kousik Kumar0d15a722020-09-23 02:54:11 -0400954 for _, f := range []string{"RBE_log_dir", "FLAG_log_dir"} {
955 if v, ok := c.environ.Get(f); ok {
956 return v
957 }
958 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400959 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000960 return c.LogsDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400961 }
962 return c.OutDir()
963}
964
965func (c *configImpl) rbeStatsOutputDir() string {
Patrice Arruda62f1bf22020-07-07 12:48:26 +0000966 for _, f := range []string{"RBE_output_dir", "FLAG_output_dir"} {
967 if v, ok := c.environ.Get(f); ok {
968 return v
969 }
970 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000971 return c.rbeLogDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400972}
973
974func (c *configImpl) rbeLogPath() string {
975 for _, f := range []string{"RBE_log_path", "FLAG_log_path"} {
976 if v, ok := c.environ.Get(f); ok {
977 return v
978 }
979 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000980 return fmt.Sprintf("text://%v/reproxy_log.txt", c.rbeLogDir())
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400981}
982
983func (c *configImpl) rbeExecRoot() string {
984 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
985 if v, ok := c.environ.Get(f); ok {
986 return v
987 }
988 }
989 wd, err := os.Getwd()
990 if err != nil {
991 return ""
992 }
993 return wd
994}
995
996func (c *configImpl) rbeDir() string {
997 if v, ok := c.environ.Get("RBE_DIR"); ok {
998 return v
999 }
1000 return "prebuilts/remoteexecution-client/live/"
1001}
1002
1003func (c *configImpl) rbeReproxy() string {
1004 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1005 if v, ok := c.environ.Get(f); ok {
1006 return v
1007 }
1008 }
1009 return filepath.Join(c.rbeDir(), "reproxy")
1010}
1011
1012func (c *configImpl) rbeAuth() (string, string) {
1013 credFlags := []string{"use_application_default_credentials", "use_gce_credentials", "credential_file"}
1014 for _, cf := range credFlags {
1015 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1016 if v, ok := c.environ.Get(f); ok {
1017 v = strings.TrimSpace(v)
1018 if v != "" && v != "false" && v != "0" {
1019 return "RBE_" + cf, v
1020 }
1021 }
1022 }
1023 }
1024 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001025}
1026
Colin Cross9016b912019-11-11 14:57:42 -08001027func (c *configImpl) UseRemoteBuild() bool {
1028 return c.UseGoma() || c.UseRBE()
1029}
1030
Dan Willemsen1e704462016-08-21 15:17:17 -07001031// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001032// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001033// still limited by Parallel()
1034func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001035 if !c.UseRemoteBuild() {
1036 return 0
1037 }
1038 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1039 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001040 }
1041 return 500
1042}
1043
1044func (c *configImpl) SetKatiArgs(args []string) {
1045 c.katiArgs = args
1046}
1047
1048func (c *configImpl) SetNinjaArgs(args []string) {
1049 c.ninjaArgs = args
1050}
1051
1052func (c *configImpl) SetKatiSuffix(suffix string) {
1053 c.katiSuffix = suffix
1054}
1055
Dan Willemsene0879fc2017-08-04 15:06:27 -07001056func (c *configImpl) LastKatiSuffixFile() string {
1057 return filepath.Join(c.OutDir(), "last_kati_suffix")
1058}
1059
1060func (c *configImpl) HasKatiSuffix() bool {
1061 return c.katiSuffix != ""
1062}
1063
Dan Willemsen1e704462016-08-21 15:17:17 -07001064func (c *configImpl) KatiEnvFile() string {
1065 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1066}
1067
Dan Willemsen29971232018-09-26 14:58:30 -07001068func (c *configImpl) KatiBuildNinjaFile() string {
1069 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001070}
1071
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001072func (c *configImpl) KatiPackageNinjaFile() string {
1073 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1074}
1075
Dan Willemsen1e704462016-08-21 15:17:17 -07001076func (c *configImpl) SoongNinjaFile() string {
1077 return filepath.Join(c.SoongOutDir(), "build.ninja")
1078}
1079
1080func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001081 if c.katiSuffix == "" {
1082 return filepath.Join(c.OutDir(), "combined.ninja")
1083 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001084 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1085}
1086
1087func (c *configImpl) SoongAndroidMk() string {
1088 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1089}
1090
1091func (c *configImpl) SoongMakeVarsMk() string {
1092 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1093}
1094
Dan Willemsenf052f782017-05-18 15:29:04 -07001095func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001096 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001097}
1098
Dan Willemsen02781d52017-05-12 19:28:13 -07001099func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001100 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1101}
1102
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001103func (c *configImpl) KatiPackageMkDir() string {
1104 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1105}
1106
Dan Willemsenf052f782017-05-18 15:29:04 -07001107func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001108 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001109}
1110
1111func (c *configImpl) HostOut() string {
1112 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1113}
1114
1115// This probably needs to be multi-valued, so not exporting it for now
1116func (c *configImpl) hostCrossOut() string {
1117 if runtime.GOOS == "linux" {
1118 return filepath.Join(c.hostOutRoot(), "windows-x86")
1119 } else {
1120 return ""
1121 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001122}
1123
Dan Willemsen1e704462016-08-21 15:17:17 -07001124func (c *configImpl) HostPrebuiltTag() string {
1125 if runtime.GOOS == "linux" {
1126 return "linux-x86"
1127 } else if runtime.GOOS == "darwin" {
1128 return "darwin-x86"
1129 } else {
1130 panic("Unsupported OS")
1131 }
1132}
Dan Willemsenf173d592017-04-27 14:28:00 -07001133
Dan Willemsen8122bd52017-10-12 20:20:41 -07001134func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001135 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1136 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001137 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1138 if _, err := os.Stat(asan); err == nil {
1139 return asan
1140 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001141 }
1142 }
1143 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1144}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001145
1146func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1147 c.brokenDupRules = val
1148}
1149
1150func (c *configImpl) BuildBrokenDupRules() bool {
1151 return c.brokenDupRules
1152}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001153
Dan Willemsen25e6f092019-04-09 10:22:43 -07001154func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1155 c.brokenUsesNetwork = val
1156}
1157
1158func (c *configImpl) BuildBrokenUsesNetwork() bool {
1159 return c.brokenUsesNetwork
1160}
1161
Dan Willemsene3336352020-01-02 19:10:38 -08001162func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1163 c.brokenNinjaEnvVars = val
1164}
1165
1166func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1167 return c.brokenNinjaEnvVars
1168}
1169
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001170func (c *configImpl) SetTargetDeviceDir(dir string) {
1171 c.targetDeviceDir = dir
1172}
1173
1174func (c *configImpl) TargetDeviceDir() string {
1175 return c.targetDeviceDir
1176}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001177
Patrice Arruda219eef32020-06-01 17:29:30 +00001178func (c *configImpl) BuildDateTime() string {
1179 return c.buildDateTime
1180}
1181
1182func (c *configImpl) MetricsUploaderApp() string {
1183 if p, ok := c.environ.Get("ANDROID_ENABLE_METRICS_UPLOAD"); ok {
1184 return p
1185 }
1186 return ""
1187}
Patrice Arruda83842d72020-12-08 19:42:08 +00001188
1189// LogsDir returns the logs directory where build log and metrics
1190// files are located. By default, the logs directory is the out
1191// directory. If the argument dist is specified, the logs directory
1192// is <dist_dir>/logs.
1193func (c *configImpl) LogsDir() string {
1194 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001195 // Always write logs to the real dist dir, even if Bazel is using a rigged dist dir for other files
1196 return filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001197 }
1198 return c.OutDir()
1199}
1200
1201// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1202// where the bazel profiles are located.
1203func (c *configImpl) BazelMetricsDir() string {
1204 return filepath.Join(c.LogsDir(), "bazel_metrics")
1205}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001206
1207func (c *configImpl) SetEmptyNinjaFile(v bool) {
1208 c.emptyNinjaFile = v
1209}
1210
1211func (c *configImpl) EmptyNinjaFile() bool {
1212 return c.emptyNinjaFile
1213}