blob: b0ed0c4d1d973140609b5f9195dca219bf038aac [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 Hansson546de4a2021-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
Dan Willemsen3d60b112018-04-04 22:25:56 -070061
Dan Willemsen2bb82d02019-12-27 09:35:42 -080062 // Autodetected
63 totalRAM uint64
64
Dan Willemsene3336352020-01-02 19:10:38 -080065 brokenDupRules bool
66 brokenUsesNetwork bool
67 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -070068
69 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +000070
71 useBazel bool
72
73 // During Bazel execution, Bazel cannot write outside OUT_DIR.
74 // So if DIST_DIR is set to an external dir (outside of OUT_DIR), we need to rig it temporarily and then migrate files at the end of the build.
75 riggedDistDirForBazel string
Colin Cross7dcd16c2021-06-01 11:43:55 -070076
77 // Set by multiproduct_kati
78 emptyNinjaFile bool
Dan Willemsen1e704462016-08-21 15:17:17 -070079}
80
Dan Willemsenc2af0be2017-01-20 14:10:01 -080081const srcDirFileCheck = "build/soong/root.bp"
82
Patrice Arruda9450d0b2019-07-08 11:06:46 -070083var buildFiles = []string{"Android.mk", "Android.bp"}
84
Patrice Arruda13848222019-04-22 17:12:02 -070085type BuildAction uint
86
87const (
88 // Builds all of the modules and their dependencies of a specified directory, relative to the root
89 // directory of the source tree.
90 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
91
92 // Builds all of the modules and their dependencies of a list of specified directories. All specified
93 // directories are relative to the root directory of the source tree.
94 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -070095
96 // Build a list of specified modules. If none was specified, simply build the whole source tree.
97 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -070098)
99
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400100type bazelBuildMode int
101
102// Bazel-related build modes.
103const (
104 // Don't use bazel at all.
105 noBazel bazelBuildMode = iota
106
107 // Only generate build files (in a subdirectory of the out directory) and exit.
108 generateBuildFiles
109
110 // Generate synthetic build files and incorporate these files into a build which
111 // partially uses Bazel. Build metadata may come from Android.bp or BUILD files.
112 mixedBuild
113)
114
Patrice Arruda13848222019-04-22 17:12:02 -0700115// checkTopDir validates that the current directory is at the root directory of the source tree.
116func checkTopDir(ctx Context) {
117 if _, err := os.Stat(srcDirFileCheck); err != nil {
118 if os.IsNotExist(err) {
119 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
120 }
121 ctx.Fatalln("Error verifying tree state:", err)
122 }
123}
124
Dan Willemsen1e704462016-08-21 15:17:17 -0700125func NewConfig(ctx Context, args ...string) Config {
126 ret := &configImpl{
127 environ: OsEnvironment(),
128 }
129
Patrice Arruda90109172020-07-28 18:07:27 +0000130 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700131 ret.parallel = runtime.NumCPU() + 2
132 ret.keepGoing = 1
133
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800134 ret.totalRAM = detectTotalRAM(ctx)
135
Dan Willemsen9b587492017-07-10 22:13:00 -0700136 ret.parseArgs(ctx, args)
137
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800138 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700139 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
Adrian DCe9d0a922018-08-10 17:07:47 +0200140 outDir := filepath.Clean(outDir)
141 if (!filepath.IsAbs(outDir)) {
142 outDir = filepath.Join(os.Getenv("TOP"), outDir)
143 }
144 ret.environ.Set("OUT_DIR", outDir)
Dan Willemsen02f3add2017-05-12 13:50:19 -0700145 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800146 outDir := "out"
147 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
148 if wd, err := os.Getwd(); err != nil {
149 ctx.Fatalln("Failed to get working directory:", err)
150 } else {
151 outDir = filepath.Join(baseDir, filepath.Base(wd))
152 }
Dan Pasanenec601212017-08-23 08:32:09 -0500153 } else {
154 outDir = filepath.Join(os.Getenv("TOP"), outDir)
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800155 }
156 ret.environ.Set("OUT_DIR", outDir)
157 }
158
Dan Willemsen2d31a442018-10-20 21:33:41 -0700159 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
160 ret.distDir = filepath.Clean(distDir)
161 } else {
162 ret.distDir = filepath.Join(ret.OutDir(), "dist")
163 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700164
Dan Willemsen1e704462016-08-21 15:17:17 -0700165 ret.environ.Unset(
166 // We're already using it
167 "USE_SOONG_UI",
168
169 // We should never use GOROOT/GOPATH from the shell environment
170 "GOROOT",
171 "GOPATH",
172
173 // These should only come from Soong, not the environment.
174 "CLANG",
175 "CLANG_CXX",
176 "CCC_CC",
177 "CCC_CXX",
178
179 // Used by the goma compiler wrapper, but should only be set by
180 // gomacc
181 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800182
183 // We handle this above
184 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700185
Dan Willemsen2d31a442018-10-20 21:33:41 -0700186 // This is handled above too, and set for individual commands later
187 "DIST_DIR",
188
Dan Willemsen68a09852017-04-18 13:56:57 -0700189 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000190 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700191 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700192 "DISPLAY",
193 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700194 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700195 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700196
197 // Drop make flags
198 "MAKEFLAGS",
199 "MAKELEVEL",
200 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700201
202 // Set in envsetup.sh, reset in makefiles
203 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700204
205 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
206 "ANDROID_BUILD_TOP",
207 "ANDROID_HOST_OUT",
208 "ANDROID_PRODUCT_OUT",
209 "ANDROID_HOST_OUT_TESTCASES",
210 "ANDROID_TARGET_OUT_TESTCASES",
211 "ANDROID_TOOLCHAIN",
212 "ANDROID_TOOLCHAIN_2ND_ARCH",
213 "ANDROID_DEV_SCRIPTS",
214 "ANDROID_EMULATOR_PREBUILTS",
215 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700216 )
217
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400218 if ret.UseGoma() || ret.ForceUseGoma() {
219 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
220 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400221 }
222
Dan Willemsen1e704462016-08-21 15:17:17 -0700223 // Tell python not to spam the source tree with .pyc files.
224 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
225
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400226 tmpDir := absPath(ctx, ret.TempDir())
227 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800228
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700229 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
230 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
231 "llvm-binutils-stable/llvm-symbolizer")
232 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
233
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800234 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700235 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800236
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700237 if srcDir := absPath(ctx, "."); strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700238 ctx.Println("You are building in a directory whose absolute path contains a space character:")
239 ctx.Println()
240 ctx.Printf("%q\n", srcDir)
241 ctx.Println()
242 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700243 }
244
245 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700246 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
247 ctx.Println()
248 ctx.Printf("%q\n", outDir)
249 ctx.Println()
250 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700251 }
252
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000253 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700254 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
255 ctx.Println()
256 ctx.Printf("%q\n", distDir)
257 ctx.Println()
258 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700259 }
260
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700261 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000262 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
263 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100264 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700265 javaHome := func() string {
266 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
267 return override
268 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000269 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
270 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 +0100271 }
Pete Gillinabbcdda2019-10-28 16:15:33 +0000272 return java11Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700273 }()
274 absJavaHome := absPath(ctx, javaHome)
275
Dan Willemsened869522018-01-08 14:58:46 -0800276 ret.configureLocale(ctx)
277
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700278 newPath := []string{filepath.Join(absJavaHome, "bin")}
279 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
280 newPath = append(newPath, path)
281 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100282
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700283 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
284 ret.environ.Set("JAVA_HOME", absJavaHome)
285 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000286 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
287 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100288 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700289 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
290
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800291 outDir := ret.OutDir()
292 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800293 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800294 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800295 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800296 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800297 }
Colin Cross28f527c2019-11-26 16:19:04 -0800298
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800299 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
300
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400301 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400302 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400303 ret.environ.Set(k, v)
304 }
305 }
306
Patrice Arruda83842d72020-12-08 19:42:08 +0000307 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800308 if err := os.RemoveAll(bpd); err != nil {
309 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
310 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000311
312 ret.useBazel = ret.environ.IsEnvTrue("USE_BAZEL")
313
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800314 if ret.UseBazel() {
315 if err := os.MkdirAll(bpd, 0777); err != nil {
316 ctx.Fatalf("Failed to create bazel profile directory %q: %v", bpd, err)
317 }
318 }
319
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000320 if ret.UseBazel() {
321 ret.riggedDistDirForBazel = filepath.Join(ret.OutDir(), "dist")
322 } else {
323 // Not rigged
324 ret.riggedDistDirForBazel = ret.distDir
325 }
326
Patrice Arruda96850362020-08-11 20:41:11 +0000327 c := Config{ret}
328 storeConfigMetrics(ctx, c)
329 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700330}
331
Patrice Arruda13848222019-04-22 17:12:02 -0700332// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
333// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700334func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
335 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700336}
337
Patrice Arruda96850362020-08-11 20:41:11 +0000338// storeConfigMetrics selects a set of configuration information and store in
339// the metrics system for further analysis.
340func storeConfigMetrics(ctx Context, config Config) {
341 if ctx.Metrics == nil {
342 return
343 }
344
345 b := &smpb.BuildConfig{
Patrice Arrudac97d6dc2020-09-28 18:22:07 +0000346 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
347 UseGoma: proto.Bool(config.UseGoma()),
348 UseRbe: proto.Bool(config.UseRBE()),
Patrice Arruda96850362020-08-11 20:41:11 +0000349 }
350 ctx.Metrics.BuildConfig(b)
Patrice Arruda3edfd482020-10-13 23:58:41 +0000351
352 s := &smpb.SystemResourceInfo{
353 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
354 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
355 }
356 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000357}
358
Patrice Arruda13848222019-04-22 17:12:02 -0700359// getConfigArgs processes the command arguments based on the build action and creates a set of new
360// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700361func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700362 // The next block of code verifies that the current directory is the root directory of the source
363 // tree. It then finds the relative path of dir based on the root directory of the source tree
364 // and verify that dir is inside of the source tree.
365 checkTopDir(ctx)
366 topDir, err := os.Getwd()
367 if err != nil {
368 ctx.Fatalf("Error retrieving top directory: %v", err)
369 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700370 dir, err = filepath.EvalSymlinks(dir)
371 if err != nil {
372 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
373 }
Patrice Arruda13848222019-04-22 17:12:02 -0700374 dir, err = filepath.Abs(dir)
375 if err != nil {
376 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
377 }
378 relDir, err := filepath.Rel(topDir, dir)
379 if err != nil {
380 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
381 }
382 // If there are ".." in the path, it's not in the source tree.
383 if strings.Contains(relDir, "..") {
384 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
385 }
386
387 configArgs := args[:]
388
389 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
390 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
391 targetNamePrefix := "MODULES-IN-"
392 if inList("GET-INSTALL-PATH", configArgs) {
393 targetNamePrefix = "GET-INSTALL-PATH-IN-"
394 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
395 }
396
Patrice Arruda13848222019-04-22 17:12:02 -0700397 var targets []string
398
399 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700400 case BUILD_MODULES:
401 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700402 case BUILD_MODULES_IN_A_DIRECTORY:
403 // If dir is the root source tree, all the modules are built of the source tree are built so
404 // no need to find the build file.
405 if topDir == dir {
406 break
407 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700408
Patrice Arruda13848222019-04-22 17:12:02 -0700409 buildFile := findBuildFile(ctx, relDir)
410 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700411 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700412 }
Patrice Arruda13848222019-04-22 17:12:02 -0700413 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
414 case BUILD_MODULES_IN_DIRECTORIES:
415 newConfigArgs, dirs := splitArgs(configArgs)
416 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700417 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700418 }
419
420 // Tidy only override all other specified targets.
421 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
422 if tidyOnly == "true" || tidyOnly == "1" {
423 configArgs = append(configArgs, "tidy_only")
424 } else {
425 configArgs = append(configArgs, targets...)
426 }
427
428 return configArgs
429}
430
431// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
432func convertToTarget(dir string, targetNamePrefix string) string {
433 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
434}
435
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700436// hasBuildFile returns true if dir contains an Android build file.
437func hasBuildFile(ctx Context, dir string) bool {
438 for _, buildFile := range buildFiles {
439 _, err := os.Stat(filepath.Join(dir, buildFile))
440 if err == nil {
441 return true
442 }
443 if !os.IsNotExist(err) {
444 ctx.Fatalf("Error retrieving the build file stats: %v", err)
445 }
446 }
447 return false
448}
449
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700450// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
451// in the current and any sub directory of dir. If a build file is not found, traverse the path
452// up by one directory and repeat again until either a build file is found or reached to the root
453// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
454// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700455func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700456 // If the string is empty or ".", assume it is top directory of the source tree.
457 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700458 return ""
459 }
460
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700461 found := false
462 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
463 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
464 if err != nil {
465 return err
466 }
467 if found {
468 return filepath.SkipDir
469 }
470 if info.IsDir() {
471 return nil
472 }
473 for _, buildFile := range buildFiles {
474 if info.Name() == buildFile {
475 found = true
476 return filepath.SkipDir
477 }
478 }
479 return nil
480 })
481 if err != nil {
482 ctx.Fatalf("Error finding Android build file: %v", err)
483 }
484
485 if found {
486 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700487 }
488 }
489
490 return ""
491}
492
493// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
494func splitArgs(args []string) (newArgs []string, dirs []string) {
495 specialArgs := map[string]bool{
496 "showcommands": true,
497 "snod": true,
498 "dist": true,
499 "checkbuild": true,
500 }
501
502 newArgs = []string{}
503 dirs = []string{}
504
505 for _, arg := range args {
506 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
507 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
508 newArgs = append(newArgs, arg)
509 continue
510 }
511
512 if _, ok := specialArgs[arg]; ok {
513 newArgs = append(newArgs, arg)
514 continue
515 }
516
517 dirs = append(dirs, arg)
518 }
519
520 return newArgs, dirs
521}
522
523// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
524// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
525// source root tree where the build action command was invoked. Each directory is validated if the
526// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700527func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700528 for _, dir := range dirs {
529 // The directory may have specified specific modules to build. ":" is the separator to separate
530 // the directory and the list of modules.
531 s := strings.Split(dir, ":")
532 l := len(s)
533 if l > 2 { // more than one ":" was specified.
534 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
535 }
536
537 dir = filepath.Join(relDir, s[0])
538 if _, err := os.Stat(dir); err != nil {
539 ctx.Fatalf("couldn't find directory %s", dir)
540 }
541
542 // Verify that if there are any targets specified after ":". Each target is separated by ",".
543 var newTargets []string
544 if l == 2 && s[1] != "" {
545 newTargets = strings.Split(s[1], ",")
546 if inList("", newTargets) {
547 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
548 }
549 }
550
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700551 // If there are specified targets to build in dir, an android build file must exist for the one
552 // shot build. For the non-targets case, find the appropriate build file and build all the
553 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700554 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700555 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700556 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
557 }
558 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700559 buildFile := findBuildFile(ctx, dir)
560 if buildFile == "" {
561 ctx.Fatalf("Build file not found for %s directory", dir)
562 }
563 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700564 }
565
Patrice Arruda13848222019-04-22 17:12:02 -0700566 targets = append(targets, newTargets...)
567 }
568
Dan Willemsence41e942019-07-29 23:39:30 -0700569 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700570}
571
Dan Willemsen9b587492017-07-10 22:13:00 -0700572func (c *configImpl) parseArgs(ctx Context, args []string) {
573 for i := 0; i < len(args); i++ {
574 arg := strings.TrimSpace(args[i])
Anton Hanssond274ea92021-06-04 10:09:01 +0100575 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700576 c.verbose = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100577 } else if arg == "--skip-ninja" {
578 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700579 } else if arg == "--skip-make" {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000580 c.skipConfig = true
581 c.skipKati = true
582 } else if arg == "--skip-kati" {
Anton Hansson546de4a2021-06-04 10:08:08 +0100583 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000584 c.skipKati = true
Anton Hansson546de4a2021-06-04 10:08:08 +0100585 } else if arg == "--soong-only" {
586 c.skipKati = true
587 c.skipKatiNinja = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700588 } else if arg == "--skip-soong-tests" {
589 c.skipSoongTests = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700590 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700591 parseArgNum := func(def int) int {
592 if len(arg) > 2 {
593 p, err := strconv.ParseUint(arg[2:], 10, 31)
594 if err != nil {
595 ctx.Fatalf("Failed to parse %q: %v", arg, err)
596 }
597 return int(p)
598 } else if i+1 < len(args) {
599 p, err := strconv.ParseUint(args[i+1], 10, 31)
600 if err == nil {
601 i++
602 return int(p)
603 }
604 }
605 return def
606 }
607
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700608 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700609 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700610 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700611 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700612 } else {
613 ctx.Fatalln("Unknown option:", arg)
614 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700615 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700616 if k == "OUT_DIR" {
617 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
618 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700619 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700620 } else if arg == "dist" {
621 c.dist = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700622 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700623 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800624 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700625 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700626 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700627 }
628 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700629}
630
Dan Willemsened869522018-01-08 14:58:46 -0800631func (c *configImpl) configureLocale(ctx Context) {
632 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
633 output, err := cmd.Output()
634
635 var locales []string
636 if err == nil {
637 locales = strings.Split(string(output), "\n")
638 } else {
639 // If we're unable to list the locales, let's assume en_US.UTF-8
640 locales = []string{"en_US.UTF-8"}
641 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
642 }
643
644 // gettext uses LANGUAGE, which is passed directly through
645
646 // For LANG and LC_*, only preserve the evaluated version of
647 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800648 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800649 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800650 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800651 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800652 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800653 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800654 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800655 }
656
657 c.environ.UnsetWithPrefix("LC_")
658
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800659 if userLang != "" {
660 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800661 }
662
663 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
664 // for others)
665 if inList("C.UTF-8", locales) {
666 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500667 } else if inList("C.utf8", locales) {
668 // These normalize to the same thing
669 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800670 } else if inList("en_US.UTF-8", locales) {
671 c.environ.Set("LANG", "en_US.UTF-8")
672 } else if inList("en_US.utf8", locales) {
673 // These normalize to the same thing
674 c.environ.Set("LANG", "en_US.UTF-8")
675 } else {
676 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
677 }
678}
679
Dan Willemsen1e704462016-08-21 15:17:17 -0700680// Lunch configures the environment for a specific product similarly to the
681// `lunch` bash function.
682func (c *configImpl) Lunch(ctx Context, product, variant string) {
683 if variant != "eng" && variant != "userdebug" && variant != "user" {
684 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
685 }
686
687 c.environ.Set("TARGET_PRODUCT", product)
688 c.environ.Set("TARGET_BUILD_VARIANT", variant)
689 c.environ.Set("TARGET_BUILD_TYPE", "release")
690 c.environ.Unset("TARGET_BUILD_APPS")
Martin Stjernholm08802332020-06-04 17:00:01 +0100691 c.environ.Unset("TARGET_BUILD_UNBUNDLED")
Dan Willemsen1e704462016-08-21 15:17:17 -0700692}
693
694// Tapas configures the environment to build one or more unbundled apps,
695// similarly to the `tapas` bash function.
696func (c *configImpl) Tapas(ctx Context, apps []string, arch, variant string) {
697 if len(apps) == 0 {
698 apps = []string{"all"}
699 }
700 if variant == "" {
701 variant = "eng"
702 }
703
704 if variant != "eng" && variant != "userdebug" && variant != "user" {
705 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
706 }
707
708 var product string
709 switch arch {
Dan Willemsen1e704462016-08-21 15:17:17 -0700710 case "arm", "":
711 product = "aosp_arm"
712 case "arm64":
713 product = "aosm_arm64"
Dan Willemsen1e704462016-08-21 15:17:17 -0700714 case "x86":
715 product = "aosp_x86"
716 case "x86_64":
717 product = "aosp_x86_64"
718 default:
719 ctx.Fatalf("Invalid architecture: %q", arch)
720 }
721
722 c.environ.Set("TARGET_PRODUCT", product)
723 c.environ.Set("TARGET_BUILD_VARIANT", variant)
724 c.environ.Set("TARGET_BUILD_TYPE", "release")
725 c.environ.Set("TARGET_BUILD_APPS", strings.Join(apps, " "))
726}
727
728func (c *configImpl) Environment() *Environment {
729 return c.environ
730}
731
732func (c *configImpl) Arguments() []string {
733 return c.arguments
734}
735
736func (c *configImpl) OutDir() string {
737 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700738 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700739 }
740 return "out"
741}
742
Dan Willemsen8a073a82017-02-04 17:30:44 -0800743func (c *configImpl) DistDir() string {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000744 if c.UseBazel() {
745 return c.riggedDistDirForBazel
746 } else {
747 return c.distDir
748 }
749}
750
751func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700752 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800753}
754
Dan Willemsen1e704462016-08-21 15:17:17 -0700755func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000756 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700757 return c.arguments
758 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700759 return c.ninjaArgs
760}
761
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500762func (c *configImpl) BazelOutDir() string {
763 return filepath.Join(c.OutDir(), "bazel")
764}
765
Dan Willemsen1e704462016-08-21 15:17:17 -0700766func (c *configImpl) SoongOutDir() string {
767 return filepath.Join(c.OutDir(), "soong")
768}
769
Jeff Gastonefc1b412017-03-29 17:29:06 -0700770func (c *configImpl) TempDir() string {
771 return shared.TempDirForOutDir(c.SoongOutDir())
772}
773
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700774func (c *configImpl) FileListDir() string {
775 return filepath.Join(c.OutDir(), ".module_paths")
776}
777
Dan Willemsen1e704462016-08-21 15:17:17 -0700778func (c *configImpl) KatiSuffix() string {
779 if c.katiSuffix != "" {
780 return c.katiSuffix
781 }
782 panic("SetKatiSuffix has not been called")
783}
784
Colin Cross37193492017-11-16 17:55:00 -0800785// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
786// user is interested in additional checks at the expense of build time.
787func (c *configImpl) Checkbuild() bool {
788 return c.checkbuild
789}
790
Dan Willemsen8a073a82017-02-04 17:30:44 -0800791func (c *configImpl) Dist() bool {
792 return c.dist
793}
794
Dan Willemsen1e704462016-08-21 15:17:17 -0700795func (c *configImpl) IsVerbose() bool {
796 return c.verbose
797}
798
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000799func (c *configImpl) SkipKati() bool {
800 return c.skipKati
801}
802
Anton Hansson546de4a2021-06-04 10:08:08 +0100803func (c *configImpl) SkipKatiNinja() bool {
804 return c.skipKatiNinja
805}
806
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100807func (c *configImpl) SkipNinja() bool {
808 return c.skipNinja
809}
810
Anton Hanssond274ea92021-06-04 10:09:01 +0100811func (c *configImpl) SetSkipNinja(v bool) {
812 c.skipNinja = v
813}
814
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000815func (c *configImpl) SkipConfig() bool {
816 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -0700817}
818
Dan Willemsen1e704462016-08-21 15:17:17 -0700819func (c *configImpl) TargetProduct() string {
820 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
821 return v
822 }
823 panic("TARGET_PRODUCT is not defined")
824}
825
Dan Willemsen02781d52017-05-12 19:28:13 -0700826func (c *configImpl) TargetDevice() string {
827 return c.targetDevice
828}
829
830func (c *configImpl) SetTargetDevice(device string) {
831 c.targetDevice = device
832}
833
834func (c *configImpl) TargetBuildVariant() string {
835 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
836 return v
837 }
838 panic("TARGET_BUILD_VARIANT is not defined")
839}
840
Dan Willemsen1e704462016-08-21 15:17:17 -0700841func (c *configImpl) KatiArgs() []string {
842 return c.katiArgs
843}
844
845func (c *configImpl) Parallel() int {
846 return c.parallel
847}
848
Colin Cross8b8bec32019-11-15 13:18:43 -0800849func (c *configImpl) HighmemParallel() int {
850 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
851 return i
852 }
853
854 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
855 parallel := c.Parallel()
856 if c.UseRemoteBuild() {
857 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
858 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
859 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
860 // Return 1/16th of the size of the local pool, rounding up.
861 return (parallel + 15) / 16
862 } else if c.totalRAM == 0 {
863 // Couldn't detect the total RAM, don't restrict highmem processes.
864 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -0700865 } else if c.totalRAM <= 16*1024*1024*1024 {
866 // Less than 16GB of ram, restrict to 1 highmem processes
867 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -0800868 } else if c.totalRAM <= 32*1024*1024*1024 {
869 // Less than 32GB of ram, restrict to 2 highmem processes
870 return 2
871 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
872 // If less than 8GB total RAM per process, reduce the number of highmem processes
873 return p
874 }
875 // No restriction on highmem processes
876 return parallel
877}
878
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800879func (c *configImpl) TotalRAM() uint64 {
880 return c.totalRAM
881}
882
Kousik Kumarec478642020-09-21 13:39:24 -0400883// ForceUseGoma determines whether we should override Goma deprecation
884// and use Goma for the current build or not.
885func (c *configImpl) ForceUseGoma() bool {
886 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
887 v = strings.TrimSpace(v)
888 if v != "" && v != "false" {
889 return true
890 }
891 }
892 return false
893}
894
Dan Willemsen1e704462016-08-21 15:17:17 -0700895func (c *configImpl) UseGoma() bool {
896 if v, ok := c.environ.Get("USE_GOMA"); ok {
897 v = strings.TrimSpace(v)
898 if v != "" && v != "false" {
899 return true
900 }
901 }
902 return false
903}
904
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +0900905func (c *configImpl) StartGoma() bool {
906 if !c.UseGoma() {
907 return false
908 }
909
910 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
911 v = strings.TrimSpace(v)
912 if v != "" && v != "false" {
913 return false
914 }
915 }
916 return true
917}
918
Ramy Medhatbbf25672019-07-17 12:30:04 +0000919func (c *configImpl) UseRBE() bool {
920 if v, ok := c.environ.Get("USE_RBE"); ok {
921 v = strings.TrimSpace(v)
922 if v != "" && v != "false" {
923 return true
924 }
925 }
926 return false
927}
928
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800929func (c *configImpl) UseBazel() bool {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000930 return c.useBazel
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800931}
932
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400933func (c *configImpl) bazelBuildMode() bazelBuildMode {
934 if c.Environment().IsEnvTrue("USE_BAZEL_ANALYSIS") {
935 return mixedBuild
936 } else if c.Environment().IsEnvTrue("GENERATE_BAZEL_FILES") {
937 return generateBuildFiles
938 } else {
939 return noBazel
940 }
941}
942
Ramy Medhatbbf25672019-07-17 12:30:04 +0000943func (c *configImpl) StartRBE() bool {
944 if !c.UseRBE() {
945 return false
946 }
947
948 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
949 v = strings.TrimSpace(v)
950 if v != "" && v != "false" {
951 return false
952 }
953 }
954 return true
955}
956
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000957func (c *configImpl) rbeLogDir() string {
Kousik Kumar0d15a722020-09-23 02:54:11 -0400958 for _, f := range []string{"RBE_log_dir", "FLAG_log_dir"} {
959 if v, ok := c.environ.Get(f); ok {
960 return v
961 }
962 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400963 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000964 return c.LogsDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400965 }
966 return c.OutDir()
967}
968
969func (c *configImpl) rbeStatsOutputDir() string {
Patrice Arruda62f1bf22020-07-07 12:48:26 +0000970 for _, f := range []string{"RBE_output_dir", "FLAG_output_dir"} {
971 if v, ok := c.environ.Get(f); ok {
972 return v
973 }
974 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000975 return c.rbeLogDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400976}
977
978func (c *configImpl) rbeLogPath() string {
979 for _, f := range []string{"RBE_log_path", "FLAG_log_path"} {
980 if v, ok := c.environ.Get(f); ok {
981 return v
982 }
983 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000984 return fmt.Sprintf("text://%v/reproxy_log.txt", c.rbeLogDir())
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400985}
986
987func (c *configImpl) rbeExecRoot() string {
988 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
989 if v, ok := c.environ.Get(f); ok {
990 return v
991 }
992 }
993 wd, err := os.Getwd()
994 if err != nil {
995 return ""
996 }
997 return wd
998}
999
1000func (c *configImpl) rbeDir() string {
1001 if v, ok := c.environ.Get("RBE_DIR"); ok {
1002 return v
1003 }
1004 return "prebuilts/remoteexecution-client/live/"
1005}
1006
1007func (c *configImpl) rbeReproxy() string {
1008 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1009 if v, ok := c.environ.Get(f); ok {
1010 return v
1011 }
1012 }
1013 return filepath.Join(c.rbeDir(), "reproxy")
1014}
1015
1016func (c *configImpl) rbeAuth() (string, string) {
1017 credFlags := []string{"use_application_default_credentials", "use_gce_credentials", "credential_file"}
1018 for _, cf := range credFlags {
1019 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1020 if v, ok := c.environ.Get(f); ok {
1021 v = strings.TrimSpace(v)
1022 if v != "" && v != "false" && v != "0" {
1023 return "RBE_" + cf, v
1024 }
1025 }
1026 }
1027 }
1028 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001029}
1030
Colin Cross9016b912019-11-11 14:57:42 -08001031func (c *configImpl) UseRemoteBuild() bool {
1032 return c.UseGoma() || c.UseRBE()
1033}
1034
Dan Willemsen1e704462016-08-21 15:17:17 -07001035// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001036// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001037// still limited by Parallel()
1038func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001039 if !c.UseRemoteBuild() {
1040 return 0
1041 }
1042 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1043 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001044 }
1045 return 500
1046}
1047
1048func (c *configImpl) SetKatiArgs(args []string) {
1049 c.katiArgs = args
1050}
1051
1052func (c *configImpl) SetNinjaArgs(args []string) {
1053 c.ninjaArgs = args
1054}
1055
1056func (c *configImpl) SetKatiSuffix(suffix string) {
1057 c.katiSuffix = suffix
1058}
1059
Dan Willemsene0879fc2017-08-04 15:06:27 -07001060func (c *configImpl) LastKatiSuffixFile() string {
1061 return filepath.Join(c.OutDir(), "last_kati_suffix")
1062}
1063
1064func (c *configImpl) HasKatiSuffix() bool {
1065 return c.katiSuffix != ""
1066}
1067
Dan Willemsen1e704462016-08-21 15:17:17 -07001068func (c *configImpl) KatiEnvFile() string {
1069 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1070}
1071
Dan Willemsen29971232018-09-26 14:58:30 -07001072func (c *configImpl) KatiBuildNinjaFile() string {
1073 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001074}
1075
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001076func (c *configImpl) KatiPackageNinjaFile() string {
1077 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1078}
1079
Dan Willemsen1e704462016-08-21 15:17:17 -07001080func (c *configImpl) SoongNinjaFile() string {
1081 return filepath.Join(c.SoongOutDir(), "build.ninja")
1082}
1083
1084func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001085 if c.katiSuffix == "" {
1086 return filepath.Join(c.OutDir(), "combined.ninja")
1087 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001088 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1089}
1090
1091func (c *configImpl) SoongAndroidMk() string {
1092 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1093}
1094
1095func (c *configImpl) SoongMakeVarsMk() string {
1096 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1097}
1098
Dan Willemsenf052f782017-05-18 15:29:04 -07001099func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001100 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001101}
1102
Dan Willemsen02781d52017-05-12 19:28:13 -07001103func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001104 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1105}
1106
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001107func (c *configImpl) KatiPackageMkDir() string {
1108 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1109}
1110
Dan Willemsenf052f782017-05-18 15:29:04 -07001111func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001112 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001113}
1114
1115func (c *configImpl) HostOut() string {
1116 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1117}
1118
1119// This probably needs to be multi-valued, so not exporting it for now
1120func (c *configImpl) hostCrossOut() string {
1121 if runtime.GOOS == "linux" {
1122 return filepath.Join(c.hostOutRoot(), "windows-x86")
1123 } else {
1124 return ""
1125 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001126}
1127
Dan Willemsen1e704462016-08-21 15:17:17 -07001128func (c *configImpl) HostPrebuiltTag() string {
1129 if runtime.GOOS == "linux" {
1130 return "linux-x86"
1131 } else if runtime.GOOS == "darwin" {
1132 return "darwin-x86"
1133 } else {
1134 panic("Unsupported OS")
1135 }
1136}
Dan Willemsenf173d592017-04-27 14:28:00 -07001137
Dan Willemsen8122bd52017-10-12 20:20:41 -07001138func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001139 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1140 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001141 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1142 if _, err := os.Stat(asan); err == nil {
1143 return asan
1144 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001145 }
1146 }
1147 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1148}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001149
1150func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1151 c.brokenDupRules = val
1152}
1153
1154func (c *configImpl) BuildBrokenDupRules() bool {
1155 return c.brokenDupRules
1156}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001157
Dan Willemsen25e6f092019-04-09 10:22:43 -07001158func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1159 c.brokenUsesNetwork = val
1160}
1161
1162func (c *configImpl) BuildBrokenUsesNetwork() bool {
1163 return c.brokenUsesNetwork
1164}
1165
Dan Willemsene3336352020-01-02 19:10:38 -08001166func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1167 c.brokenNinjaEnvVars = val
1168}
1169
1170func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1171 return c.brokenNinjaEnvVars
1172}
1173
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001174func (c *configImpl) SetTargetDeviceDir(dir string) {
1175 c.targetDeviceDir = dir
1176}
1177
1178func (c *configImpl) TargetDeviceDir() string {
1179 return c.targetDeviceDir
1180}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001181
Patrice Arruda219eef32020-06-01 17:29:30 +00001182func (c *configImpl) BuildDateTime() string {
1183 return c.buildDateTime
1184}
1185
1186func (c *configImpl) MetricsUploaderApp() string {
1187 if p, ok := c.environ.Get("ANDROID_ENABLE_METRICS_UPLOAD"); ok {
1188 return p
1189 }
1190 return ""
1191}
Patrice Arruda83842d72020-12-08 19:42:08 +00001192
1193// LogsDir returns the logs directory where build log and metrics
1194// files are located. By default, the logs directory is the out
1195// directory. If the argument dist is specified, the logs directory
1196// is <dist_dir>/logs.
1197func (c *configImpl) LogsDir() string {
1198 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001199 // Always write logs to the real dist dir, even if Bazel is using a rigged dist dir for other files
1200 return filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001201 }
1202 return c.OutDir()
1203}
1204
1205// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1206// where the bazel profiles are located.
1207func (c *configImpl) BazelMetricsDir() string {
1208 return filepath.Join(c.LogsDir(), "bazel_metrics")
1209}
Colin Cross7dcd16c2021-06-01 11:43:55 -07001210
1211func (c *configImpl) SetEmptyNinjaFile(v bool) {
1212 c.emptyNinjaFile = v
1213}
1214
1215func (c *configImpl) EmptyNinjaFile() bool {
1216 return c.emptyNinjaFile
1217}