blob: 1d1f71f67fb95072d4b6ebff1ebde1ab4760eaeb [file] [log] [blame]
Dan Willemsen1e704462016-08-21 15:17:17 -07001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package build
16
17import (
Ramy Medhat0fc67eb2020-08-12 01:26:23 -040018 "fmt"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080019 "os"
Dan Willemsen1e704462016-08-21 15:17:17 -070020 "path/filepath"
21 "runtime"
22 "strconv"
23 "strings"
Nan Zhang2e6a4ff2018-02-14 13:27:26 -080024 "time"
Jeff Gastonefc1b412017-03-29 17:29:06 -070025
26 "android/soong/shared"
Kousik Kumarec478642020-09-21 13:39:24 -040027
Patrice Arruda96850362020-08-11 20:41:11 +000028 "github.com/golang/protobuf/proto"
29
30 smpb "android/soong/ui/metrics/metrics_proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070031)
32
33type Config struct{ *configImpl }
34
35type configImpl struct {
36 // From the environment
Colin Cross28f527c2019-11-26 16:19:04 -080037 arguments []string
38 goma bool
39 environ *Environment
40 distDir string
41 buildDateTime string
Dan Willemsen1e704462016-08-21 15:17:17 -070042
43 // From the arguments
Colin Cross00a8a3f2020-10-29 14:08:31 -070044 parallel int
45 keepGoing int
46 verbose bool
47 checkbuild bool
48 dist bool
Anton Hansson5e5c48b2020-11-27 12:35:20 +000049 skipConfig bool
50 skipKati bool
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010051 skipNinja bool
Colin Cross00a8a3f2020-10-29 14:08:31 -070052 skipSoongTests bool
Dan Willemsen1e704462016-08-21 15:17:17 -070053
54 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070055 katiArgs []string
56 ninjaArgs []string
57 katiSuffix string
58 targetDevice string
59 targetDeviceDir string
Dan Willemsen3d60b112018-04-04 22:25:56 -070060
Dan Willemsen2bb82d02019-12-27 09:35:42 -080061 // Autodetected
62 totalRAM uint64
63
Dan Willemsene3336352020-01-02 19:10:38 -080064 brokenDupRules bool
65 brokenUsesNetwork bool
66 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -070067
68 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +000069
70 useBazel bool
71
72 // During Bazel execution, Bazel cannot write outside OUT_DIR.
73 // So if DIST_DIR is set to an external dir (outside of OUT_DIR), we need to rig it temporarily and then migrate files at the end of the build.
74 riggedDistDirForBazel string
Dan Willemsen1e704462016-08-21 15:17:17 -070075}
76
Dan Willemsenc2af0be2017-01-20 14:10:01 -080077const srcDirFileCheck = "build/soong/root.bp"
78
Patrice Arruda9450d0b2019-07-08 11:06:46 -070079var buildFiles = []string{"Android.mk", "Android.bp"}
80
Patrice Arruda13848222019-04-22 17:12:02 -070081type BuildAction uint
82
83const (
84 // Builds all of the modules and their dependencies of a specified directory, relative to the root
85 // directory of the source tree.
86 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
87
88 // Builds all of the modules and their dependencies of a list of specified directories. All specified
89 // directories are relative to the root directory of the source tree.
90 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -070091
92 // Build a list of specified modules. If none was specified, simply build the whole source tree.
93 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -070094)
95
Chris Parsonsec1a3dc2021-04-20 15:32:07 -040096type bazelBuildMode int
97
98// Bazel-related build modes.
99const (
100 // Don't use bazel at all.
101 noBazel bazelBuildMode = iota
102
103 // Only generate build files (in a subdirectory of the out directory) and exit.
104 generateBuildFiles
105
106 // Generate synthetic build files and incorporate these files into a build which
107 // partially uses Bazel. Build metadata may come from Android.bp or BUILD files.
108 mixedBuild
109)
110
Patrice Arruda13848222019-04-22 17:12:02 -0700111// checkTopDir validates that the current directory is at the root directory of the source tree.
112func checkTopDir(ctx Context) {
113 if _, err := os.Stat(srcDirFileCheck); err != nil {
114 if os.IsNotExist(err) {
115 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
116 }
117 ctx.Fatalln("Error verifying tree state:", err)
118 }
119}
120
Dan Willemsen1e704462016-08-21 15:17:17 -0700121func NewConfig(ctx Context, args ...string) Config {
122 ret := &configImpl{
123 environ: OsEnvironment(),
124 }
125
Patrice Arruda90109172020-07-28 18:07:27 +0000126 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700127 ret.parallel = runtime.NumCPU() + 2
128 ret.keepGoing = 1
129
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800130 ret.totalRAM = detectTotalRAM(ctx)
131
Dan Willemsen9b587492017-07-10 22:13:00 -0700132 ret.parseArgs(ctx, args)
133
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800134 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700135 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
136 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
137 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800138 outDir := "out"
139 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
140 if wd, err := os.Getwd(); err != nil {
141 ctx.Fatalln("Failed to get working directory:", err)
142 } else {
143 outDir = filepath.Join(baseDir, filepath.Base(wd))
144 }
145 }
146 ret.environ.Set("OUT_DIR", outDir)
147 }
148
Dan Willemsen2d31a442018-10-20 21:33:41 -0700149 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
150 ret.distDir = filepath.Clean(distDir)
151 } else {
152 ret.distDir = filepath.Join(ret.OutDir(), "dist")
153 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700154
Dan Willemsen1e704462016-08-21 15:17:17 -0700155 ret.environ.Unset(
156 // We're already using it
157 "USE_SOONG_UI",
158
159 // We should never use GOROOT/GOPATH from the shell environment
160 "GOROOT",
161 "GOPATH",
162
163 // These should only come from Soong, not the environment.
164 "CLANG",
165 "CLANG_CXX",
166 "CCC_CC",
167 "CCC_CXX",
168
169 // Used by the goma compiler wrapper, but should only be set by
170 // gomacc
171 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800172
173 // We handle this above
174 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700175
Dan Willemsen2d31a442018-10-20 21:33:41 -0700176 // This is handled above too, and set for individual commands later
177 "DIST_DIR",
178
Dan Willemsen68a09852017-04-18 13:56:57 -0700179 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000180 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700181 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700182 "DISPLAY",
183 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700184 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700185 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700186
187 // Drop make flags
188 "MAKEFLAGS",
189 "MAKELEVEL",
190 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700191
192 // Set in envsetup.sh, reset in makefiles
193 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700194
195 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
196 "ANDROID_BUILD_TOP",
197 "ANDROID_HOST_OUT",
198 "ANDROID_PRODUCT_OUT",
199 "ANDROID_HOST_OUT_TESTCASES",
200 "ANDROID_TARGET_OUT_TESTCASES",
201 "ANDROID_TOOLCHAIN",
202 "ANDROID_TOOLCHAIN_2ND_ARCH",
203 "ANDROID_DEV_SCRIPTS",
204 "ANDROID_EMULATOR_PREBUILTS",
205 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsenf99915f2018-10-25 22:04:42 -0700206
207 // Only set in multiproduct_kati after config generation
208 "EMPTY_NINJA_FILE",
Dan Willemsen1e704462016-08-21 15:17:17 -0700209 )
210
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400211 if ret.UseGoma() || ret.ForceUseGoma() {
212 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
213 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400214 }
215
Dan Willemsen1e704462016-08-21 15:17:17 -0700216 // Tell python not to spam the source tree with .pyc files.
217 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
218
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400219 tmpDir := absPath(ctx, ret.TempDir())
220 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800221
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700222 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
223 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
224 "llvm-binutils-stable/llvm-symbolizer")
225 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
226
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800227 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700228 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800229
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700230 if srcDir := absPath(ctx, "."); strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700231 ctx.Println("You are building in a directory whose absolute path contains a space character:")
232 ctx.Println()
233 ctx.Printf("%q\n", srcDir)
234 ctx.Println()
235 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700236 }
237
238 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700239 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
240 ctx.Println()
241 ctx.Printf("%q\n", outDir)
242 ctx.Println()
243 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700244 }
245
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000246 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700247 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
248 ctx.Println()
249 ctx.Printf("%q\n", distDir)
250 ctx.Println()
251 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700252 }
253
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700254 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000255 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
256 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100257 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700258 javaHome := func() string {
259 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
260 return override
261 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000262 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
263 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 +0100264 }
Pete Gillinabbcdda2019-10-28 16:15:33 +0000265 return java11Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700266 }()
267 absJavaHome := absPath(ctx, javaHome)
268
Dan Willemsened869522018-01-08 14:58:46 -0800269 ret.configureLocale(ctx)
270
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700271 newPath := []string{filepath.Join(absJavaHome, "bin")}
272 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
273 newPath = append(newPath, path)
274 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100275
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700276 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
277 ret.environ.Set("JAVA_HOME", absJavaHome)
278 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000279 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
280 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100281 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700282 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
283
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800284 outDir := ret.OutDir()
285 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800286 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800287 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800288 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800289 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800290 }
Colin Cross28f527c2019-11-26 16:19:04 -0800291
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800292 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
293
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400294 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400295 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400296 ret.environ.Set(k, v)
297 }
298 }
299
Patrice Arruda83842d72020-12-08 19:42:08 +0000300 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800301 if err := os.RemoveAll(bpd); err != nil {
302 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
303 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000304
305 ret.useBazel = ret.environ.IsEnvTrue("USE_BAZEL")
306
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800307 if ret.UseBazel() {
308 if err := os.MkdirAll(bpd, 0777); err != nil {
309 ctx.Fatalf("Failed to create bazel profile directory %q: %v", bpd, err)
310 }
311 }
312
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000313 if ret.UseBazel() {
314 ret.riggedDistDirForBazel = filepath.Join(ret.OutDir(), "dist")
315 } else {
316 // Not rigged
317 ret.riggedDistDirForBazel = ret.distDir
318 }
319
Patrice Arruda96850362020-08-11 20:41:11 +0000320 c := Config{ret}
321 storeConfigMetrics(ctx, c)
322 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700323}
324
Patrice Arruda13848222019-04-22 17:12:02 -0700325// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
326// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700327func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
328 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700329}
330
Patrice Arruda96850362020-08-11 20:41:11 +0000331// storeConfigMetrics selects a set of configuration information and store in
332// the metrics system for further analysis.
333func storeConfigMetrics(ctx Context, config Config) {
334 if ctx.Metrics == nil {
335 return
336 }
337
338 b := &smpb.BuildConfig{
Patrice Arrudac97d6dc2020-09-28 18:22:07 +0000339 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
340 UseGoma: proto.Bool(config.UseGoma()),
341 UseRbe: proto.Bool(config.UseRBE()),
Patrice Arruda96850362020-08-11 20:41:11 +0000342 }
343 ctx.Metrics.BuildConfig(b)
Patrice Arruda3edfd482020-10-13 23:58:41 +0000344
345 s := &smpb.SystemResourceInfo{
346 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
347 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
348 }
349 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000350}
351
Patrice Arruda13848222019-04-22 17:12:02 -0700352// getConfigArgs processes the command arguments based on the build action and creates a set of new
353// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700354func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700355 // The next block of code verifies that the current directory is the root directory of the source
356 // tree. It then finds the relative path of dir based on the root directory of the source tree
357 // and verify that dir is inside of the source tree.
358 checkTopDir(ctx)
359 topDir, err := os.Getwd()
360 if err != nil {
361 ctx.Fatalf("Error retrieving top directory: %v", err)
362 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700363 dir, err = filepath.EvalSymlinks(dir)
364 if err != nil {
365 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
366 }
Patrice Arruda13848222019-04-22 17:12:02 -0700367 dir, err = filepath.Abs(dir)
368 if err != nil {
369 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
370 }
371 relDir, err := filepath.Rel(topDir, dir)
372 if err != nil {
373 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
374 }
375 // If there are ".." in the path, it's not in the source tree.
376 if strings.Contains(relDir, "..") {
377 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
378 }
379
380 configArgs := args[:]
381
382 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
383 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
384 targetNamePrefix := "MODULES-IN-"
385 if inList("GET-INSTALL-PATH", configArgs) {
386 targetNamePrefix = "GET-INSTALL-PATH-IN-"
387 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
388 }
389
Patrice Arruda13848222019-04-22 17:12:02 -0700390 var targets []string
391
392 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700393 case BUILD_MODULES:
394 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700395 case BUILD_MODULES_IN_A_DIRECTORY:
396 // If dir is the root source tree, all the modules are built of the source tree are built so
397 // no need to find the build file.
398 if topDir == dir {
399 break
400 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700401
Patrice Arruda13848222019-04-22 17:12:02 -0700402 buildFile := findBuildFile(ctx, relDir)
403 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700404 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700405 }
Patrice Arruda13848222019-04-22 17:12:02 -0700406 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
407 case BUILD_MODULES_IN_DIRECTORIES:
408 newConfigArgs, dirs := splitArgs(configArgs)
409 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700410 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700411 }
412
413 // Tidy only override all other specified targets.
414 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
415 if tidyOnly == "true" || tidyOnly == "1" {
416 configArgs = append(configArgs, "tidy_only")
417 } else {
418 configArgs = append(configArgs, targets...)
419 }
420
421 return configArgs
422}
423
424// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
425func convertToTarget(dir string, targetNamePrefix string) string {
426 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
427}
428
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700429// hasBuildFile returns true if dir contains an Android build file.
430func hasBuildFile(ctx Context, dir string) bool {
431 for _, buildFile := range buildFiles {
432 _, err := os.Stat(filepath.Join(dir, buildFile))
433 if err == nil {
434 return true
435 }
436 if !os.IsNotExist(err) {
437 ctx.Fatalf("Error retrieving the build file stats: %v", err)
438 }
439 }
440 return false
441}
442
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700443// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
444// in the current and any sub directory of dir. If a build file is not found, traverse the path
445// up by one directory and repeat again until either a build file is found or reached to the root
446// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
447// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700448func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700449 // If the string is empty or ".", assume it is top directory of the source tree.
450 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700451 return ""
452 }
453
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700454 found := false
455 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
456 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
457 if err != nil {
458 return err
459 }
460 if found {
461 return filepath.SkipDir
462 }
463 if info.IsDir() {
464 return nil
465 }
466 for _, buildFile := range buildFiles {
467 if info.Name() == buildFile {
468 found = true
469 return filepath.SkipDir
470 }
471 }
472 return nil
473 })
474 if err != nil {
475 ctx.Fatalf("Error finding Android build file: %v", err)
476 }
477
478 if found {
479 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700480 }
481 }
482
483 return ""
484}
485
486// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
487func splitArgs(args []string) (newArgs []string, dirs []string) {
488 specialArgs := map[string]bool{
489 "showcommands": true,
490 "snod": true,
491 "dist": true,
492 "checkbuild": true,
493 }
494
495 newArgs = []string{}
496 dirs = []string{}
497
498 for _, arg := range args {
499 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
500 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
501 newArgs = append(newArgs, arg)
502 continue
503 }
504
505 if _, ok := specialArgs[arg]; ok {
506 newArgs = append(newArgs, arg)
507 continue
508 }
509
510 dirs = append(dirs, arg)
511 }
512
513 return newArgs, dirs
514}
515
516// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
517// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
518// source root tree where the build action command was invoked. Each directory is validated if the
519// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700520func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700521 for _, dir := range dirs {
522 // The directory may have specified specific modules to build. ":" is the separator to separate
523 // the directory and the list of modules.
524 s := strings.Split(dir, ":")
525 l := len(s)
526 if l > 2 { // more than one ":" was specified.
527 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
528 }
529
530 dir = filepath.Join(relDir, s[0])
531 if _, err := os.Stat(dir); err != nil {
532 ctx.Fatalf("couldn't find directory %s", dir)
533 }
534
535 // Verify that if there are any targets specified after ":". Each target is separated by ",".
536 var newTargets []string
537 if l == 2 && s[1] != "" {
538 newTargets = strings.Split(s[1], ",")
539 if inList("", newTargets) {
540 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
541 }
542 }
543
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700544 // If there are specified targets to build in dir, an android build file must exist for the one
545 // shot build. For the non-targets case, find the appropriate build file and build all the
546 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700547 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700548 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700549 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
550 }
551 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700552 buildFile := findBuildFile(ctx, dir)
553 if buildFile == "" {
554 ctx.Fatalf("Build file not found for %s directory", dir)
555 }
556 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700557 }
558
Patrice Arruda13848222019-04-22 17:12:02 -0700559 targets = append(targets, newTargets...)
560 }
561
Dan Willemsence41e942019-07-29 23:39:30 -0700562 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700563}
564
Dan Willemsen9b587492017-07-10 22:13:00 -0700565func (c *configImpl) parseArgs(ctx Context, args []string) {
566 for i := 0; i < len(args); i++ {
567 arg := strings.TrimSpace(args[i])
Dan Willemsen1e704462016-08-21 15:17:17 -0700568 if arg == "--make-mode" {
Dan Willemsen1e704462016-08-21 15:17:17 -0700569 } else if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700570 c.verbose = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100571 } else if arg == "--skip-ninja" {
572 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700573 } else if arg == "--skip-make" {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000574 c.skipConfig = true
575 c.skipKati = true
576 } else if arg == "--skip-kati" {
577 c.skipKati = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700578 } else if arg == "--skip-soong-tests" {
579 c.skipSoongTests = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700580 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700581 parseArgNum := func(def int) int {
582 if len(arg) > 2 {
583 p, err := strconv.ParseUint(arg[2:], 10, 31)
584 if err != nil {
585 ctx.Fatalf("Failed to parse %q: %v", arg, err)
586 }
587 return int(p)
588 } else if i+1 < len(args) {
589 p, err := strconv.ParseUint(args[i+1], 10, 31)
590 if err == nil {
591 i++
592 return int(p)
593 }
594 }
595 return def
596 }
597
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700598 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700599 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700600 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700601 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700602 } else {
603 ctx.Fatalln("Unknown option:", arg)
604 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700605 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700606 if k == "OUT_DIR" {
607 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
608 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700609 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700610 } else if arg == "dist" {
611 c.dist = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700612 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700613 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800614 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700615 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700616 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700617 }
618 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700619}
620
Dan Willemsened869522018-01-08 14:58:46 -0800621func (c *configImpl) configureLocale(ctx Context) {
622 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
623 output, err := cmd.Output()
624
625 var locales []string
626 if err == nil {
627 locales = strings.Split(string(output), "\n")
628 } else {
629 // If we're unable to list the locales, let's assume en_US.UTF-8
630 locales = []string{"en_US.UTF-8"}
631 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
632 }
633
634 // gettext uses LANGUAGE, which is passed directly through
635
636 // For LANG and LC_*, only preserve the evaluated version of
637 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800638 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800639 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800640 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800641 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800642 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800643 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800644 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800645 }
646
647 c.environ.UnsetWithPrefix("LC_")
648
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800649 if userLang != "" {
650 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800651 }
652
653 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
654 // for others)
655 if inList("C.UTF-8", locales) {
656 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500657 } else if inList("C.utf8", locales) {
658 // These normalize to the same thing
659 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800660 } else if inList("en_US.UTF-8", locales) {
661 c.environ.Set("LANG", "en_US.UTF-8")
662 } else if inList("en_US.utf8", locales) {
663 // These normalize to the same thing
664 c.environ.Set("LANG", "en_US.UTF-8")
665 } else {
666 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
667 }
668}
669
Dan Willemsen1e704462016-08-21 15:17:17 -0700670// Lunch configures the environment for a specific product similarly to the
671// `lunch` bash function.
672func (c *configImpl) Lunch(ctx Context, product, variant string) {
673 if variant != "eng" && variant != "userdebug" && variant != "user" {
674 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
675 }
676
677 c.environ.Set("TARGET_PRODUCT", product)
678 c.environ.Set("TARGET_BUILD_VARIANT", variant)
679 c.environ.Set("TARGET_BUILD_TYPE", "release")
680 c.environ.Unset("TARGET_BUILD_APPS")
Martin Stjernholm08802332020-06-04 17:00:01 +0100681 c.environ.Unset("TARGET_BUILD_UNBUNDLED")
Dan Willemsen1e704462016-08-21 15:17:17 -0700682}
683
684// Tapas configures the environment to build one or more unbundled apps,
685// similarly to the `tapas` bash function.
686func (c *configImpl) Tapas(ctx Context, apps []string, arch, variant string) {
687 if len(apps) == 0 {
688 apps = []string{"all"}
689 }
690 if variant == "" {
691 variant = "eng"
692 }
693
694 if variant != "eng" && variant != "userdebug" && variant != "user" {
695 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
696 }
697
698 var product string
699 switch arch {
Dan Willemsen1e704462016-08-21 15:17:17 -0700700 case "arm", "":
701 product = "aosp_arm"
702 case "arm64":
703 product = "aosm_arm64"
Dan Willemsen1e704462016-08-21 15:17:17 -0700704 case "x86":
705 product = "aosp_x86"
706 case "x86_64":
707 product = "aosp_x86_64"
708 default:
709 ctx.Fatalf("Invalid architecture: %q", arch)
710 }
711
712 c.environ.Set("TARGET_PRODUCT", product)
713 c.environ.Set("TARGET_BUILD_VARIANT", variant)
714 c.environ.Set("TARGET_BUILD_TYPE", "release")
715 c.environ.Set("TARGET_BUILD_APPS", strings.Join(apps, " "))
716}
717
718func (c *configImpl) Environment() *Environment {
719 return c.environ
720}
721
722func (c *configImpl) Arguments() []string {
723 return c.arguments
724}
725
726func (c *configImpl) OutDir() string {
727 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700728 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700729 }
730 return "out"
731}
732
Dan Willemsen8a073a82017-02-04 17:30:44 -0800733func (c *configImpl) DistDir() string {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000734 if c.UseBazel() {
735 return c.riggedDistDirForBazel
736 } else {
737 return c.distDir
738 }
739}
740
741func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700742 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800743}
744
Dan Willemsen1e704462016-08-21 15:17:17 -0700745func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000746 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700747 return c.arguments
748 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700749 return c.ninjaArgs
750}
751
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500752func (c *configImpl) BazelOutDir() string {
753 return filepath.Join(c.OutDir(), "bazel")
754}
755
Dan Willemsen1e704462016-08-21 15:17:17 -0700756func (c *configImpl) SoongOutDir() string {
757 return filepath.Join(c.OutDir(), "soong")
758}
759
Jeff Gastonefc1b412017-03-29 17:29:06 -0700760func (c *configImpl) TempDir() string {
761 return shared.TempDirForOutDir(c.SoongOutDir())
762}
763
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700764func (c *configImpl) FileListDir() string {
765 return filepath.Join(c.OutDir(), ".module_paths")
766}
767
Dan Willemsen1e704462016-08-21 15:17:17 -0700768func (c *configImpl) KatiSuffix() string {
769 if c.katiSuffix != "" {
770 return c.katiSuffix
771 }
772 panic("SetKatiSuffix has not been called")
773}
774
Colin Cross37193492017-11-16 17:55:00 -0800775// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
776// user is interested in additional checks at the expense of build time.
777func (c *configImpl) Checkbuild() bool {
778 return c.checkbuild
779}
780
Dan Willemsen8a073a82017-02-04 17:30:44 -0800781func (c *configImpl) Dist() bool {
782 return c.dist
783}
784
Dan Willemsen1e704462016-08-21 15:17:17 -0700785func (c *configImpl) IsVerbose() bool {
786 return c.verbose
787}
788
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000789func (c *configImpl) SkipKati() bool {
790 return c.skipKati
791}
792
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100793func (c *configImpl) SkipNinja() bool {
794 return c.skipNinja
795}
796
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000797func (c *configImpl) SkipConfig() bool {
798 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -0700799}
800
Dan Willemsen1e704462016-08-21 15:17:17 -0700801func (c *configImpl) TargetProduct() string {
802 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
803 return v
804 }
805 panic("TARGET_PRODUCT is not defined")
806}
807
Dan Willemsen02781d52017-05-12 19:28:13 -0700808func (c *configImpl) TargetDevice() string {
809 return c.targetDevice
810}
811
812func (c *configImpl) SetTargetDevice(device string) {
813 c.targetDevice = device
814}
815
816func (c *configImpl) TargetBuildVariant() string {
817 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
818 return v
819 }
820 panic("TARGET_BUILD_VARIANT is not defined")
821}
822
Dan Willemsen1e704462016-08-21 15:17:17 -0700823func (c *configImpl) KatiArgs() []string {
824 return c.katiArgs
825}
826
827func (c *configImpl) Parallel() int {
828 return c.parallel
829}
830
Colin Cross8b8bec32019-11-15 13:18:43 -0800831func (c *configImpl) HighmemParallel() int {
832 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
833 return i
834 }
835
836 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
837 parallel := c.Parallel()
838 if c.UseRemoteBuild() {
839 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
840 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
841 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
842 // Return 1/16th of the size of the local pool, rounding up.
843 return (parallel + 15) / 16
844 } else if c.totalRAM == 0 {
845 // Couldn't detect the total RAM, don't restrict highmem processes.
846 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -0700847 } else if c.totalRAM <= 16*1024*1024*1024 {
848 // Less than 16GB of ram, restrict to 1 highmem processes
849 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -0800850 } else if c.totalRAM <= 32*1024*1024*1024 {
851 // Less than 32GB of ram, restrict to 2 highmem processes
852 return 2
853 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
854 // If less than 8GB total RAM per process, reduce the number of highmem processes
855 return p
856 }
857 // No restriction on highmem processes
858 return parallel
859}
860
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800861func (c *configImpl) TotalRAM() uint64 {
862 return c.totalRAM
863}
864
Kousik Kumarec478642020-09-21 13:39:24 -0400865// ForceUseGoma determines whether we should override Goma deprecation
866// and use Goma for the current build or not.
867func (c *configImpl) ForceUseGoma() bool {
868 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
869 v = strings.TrimSpace(v)
870 if v != "" && v != "false" {
871 return true
872 }
873 }
874 return false
875}
876
Dan Willemsen1e704462016-08-21 15:17:17 -0700877func (c *configImpl) UseGoma() bool {
878 if v, ok := c.environ.Get("USE_GOMA"); ok {
879 v = strings.TrimSpace(v)
880 if v != "" && v != "false" {
881 return true
882 }
883 }
884 return false
885}
886
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +0900887func (c *configImpl) StartGoma() bool {
888 if !c.UseGoma() {
889 return false
890 }
891
892 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
893 v = strings.TrimSpace(v)
894 if v != "" && v != "false" {
895 return false
896 }
897 }
898 return true
899}
900
Ramy Medhatbbf25672019-07-17 12:30:04 +0000901func (c *configImpl) UseRBE() bool {
902 if v, ok := c.environ.Get("USE_RBE"); ok {
903 v = strings.TrimSpace(v)
904 if v != "" && v != "false" {
905 return true
906 }
907 }
908 return false
909}
910
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800911func (c *configImpl) UseBazel() bool {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000912 return c.useBazel
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800913}
914
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400915func (c *configImpl) bazelBuildMode() bazelBuildMode {
916 if c.Environment().IsEnvTrue("USE_BAZEL_ANALYSIS") {
917 return mixedBuild
918 } else if c.Environment().IsEnvTrue("GENERATE_BAZEL_FILES") {
919 return generateBuildFiles
920 } else {
921 return noBazel
922 }
923}
924
Ramy Medhatbbf25672019-07-17 12:30:04 +0000925func (c *configImpl) StartRBE() bool {
926 if !c.UseRBE() {
927 return false
928 }
929
930 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
931 v = strings.TrimSpace(v)
932 if v != "" && v != "false" {
933 return false
934 }
935 }
936 return true
937}
938
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000939func (c *configImpl) rbeLogDir() string {
Kousik Kumar0d15a722020-09-23 02:54:11 -0400940 for _, f := range []string{"RBE_log_dir", "FLAG_log_dir"} {
941 if v, ok := c.environ.Get(f); ok {
942 return v
943 }
944 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400945 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000946 return c.LogsDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400947 }
948 return c.OutDir()
949}
950
951func (c *configImpl) rbeStatsOutputDir() string {
Patrice Arruda62f1bf22020-07-07 12:48:26 +0000952 for _, f := range []string{"RBE_output_dir", "FLAG_output_dir"} {
953 if v, ok := c.environ.Get(f); ok {
954 return v
955 }
956 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000957 return c.rbeLogDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400958}
959
960func (c *configImpl) rbeLogPath() string {
961 for _, f := range []string{"RBE_log_path", "FLAG_log_path"} {
962 if v, ok := c.environ.Get(f); ok {
963 return v
964 }
965 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000966 return fmt.Sprintf("text://%v/reproxy_log.txt", c.rbeLogDir())
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400967}
968
969func (c *configImpl) rbeExecRoot() string {
970 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
971 if v, ok := c.environ.Get(f); ok {
972 return v
973 }
974 }
975 wd, err := os.Getwd()
976 if err != nil {
977 return ""
978 }
979 return wd
980}
981
982func (c *configImpl) rbeDir() string {
983 if v, ok := c.environ.Get("RBE_DIR"); ok {
984 return v
985 }
986 return "prebuilts/remoteexecution-client/live/"
987}
988
989func (c *configImpl) rbeReproxy() string {
990 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
991 if v, ok := c.environ.Get(f); ok {
992 return v
993 }
994 }
995 return filepath.Join(c.rbeDir(), "reproxy")
996}
997
998func (c *configImpl) rbeAuth() (string, string) {
999 credFlags := []string{"use_application_default_credentials", "use_gce_credentials", "credential_file"}
1000 for _, cf := range credFlags {
1001 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1002 if v, ok := c.environ.Get(f); ok {
1003 v = strings.TrimSpace(v)
1004 if v != "" && v != "false" && v != "0" {
1005 return "RBE_" + cf, v
1006 }
1007 }
1008 }
1009 }
1010 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001011}
1012
Colin Cross9016b912019-11-11 14:57:42 -08001013func (c *configImpl) UseRemoteBuild() bool {
1014 return c.UseGoma() || c.UseRBE()
1015}
1016
Dan Willemsen1e704462016-08-21 15:17:17 -07001017// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001018// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001019// still limited by Parallel()
1020func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001021 if !c.UseRemoteBuild() {
1022 return 0
1023 }
1024 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1025 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001026 }
1027 return 500
1028}
1029
1030func (c *configImpl) SetKatiArgs(args []string) {
1031 c.katiArgs = args
1032}
1033
1034func (c *configImpl) SetNinjaArgs(args []string) {
1035 c.ninjaArgs = args
1036}
1037
1038func (c *configImpl) SetKatiSuffix(suffix string) {
1039 c.katiSuffix = suffix
1040}
1041
Dan Willemsene0879fc2017-08-04 15:06:27 -07001042func (c *configImpl) LastKatiSuffixFile() string {
1043 return filepath.Join(c.OutDir(), "last_kati_suffix")
1044}
1045
1046func (c *configImpl) HasKatiSuffix() bool {
1047 return c.katiSuffix != ""
1048}
1049
Dan Willemsen1e704462016-08-21 15:17:17 -07001050func (c *configImpl) KatiEnvFile() string {
1051 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1052}
1053
Dan Willemsen29971232018-09-26 14:58:30 -07001054func (c *configImpl) KatiBuildNinjaFile() string {
1055 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001056}
1057
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001058func (c *configImpl) KatiPackageNinjaFile() string {
1059 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1060}
1061
Dan Willemsen1e704462016-08-21 15:17:17 -07001062func (c *configImpl) SoongNinjaFile() string {
1063 return filepath.Join(c.SoongOutDir(), "build.ninja")
1064}
1065
1066func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001067 if c.katiSuffix == "" {
1068 return filepath.Join(c.OutDir(), "combined.ninja")
1069 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001070 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1071}
1072
1073func (c *configImpl) SoongAndroidMk() string {
1074 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1075}
1076
1077func (c *configImpl) SoongMakeVarsMk() string {
1078 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1079}
1080
Dan Willemsenf052f782017-05-18 15:29:04 -07001081func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001082 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001083}
1084
Dan Willemsen02781d52017-05-12 19:28:13 -07001085func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001086 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1087}
1088
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001089func (c *configImpl) KatiPackageMkDir() string {
1090 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1091}
1092
Dan Willemsenf052f782017-05-18 15:29:04 -07001093func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001094 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001095}
1096
1097func (c *configImpl) HostOut() string {
1098 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1099}
1100
1101// This probably needs to be multi-valued, so not exporting it for now
1102func (c *configImpl) hostCrossOut() string {
1103 if runtime.GOOS == "linux" {
1104 return filepath.Join(c.hostOutRoot(), "windows-x86")
1105 } else {
1106 return ""
1107 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001108}
1109
Dan Willemsen1e704462016-08-21 15:17:17 -07001110func (c *configImpl) HostPrebuiltTag() string {
1111 if runtime.GOOS == "linux" {
1112 return "linux-x86"
1113 } else if runtime.GOOS == "darwin" {
1114 return "darwin-x86"
1115 } else {
1116 panic("Unsupported OS")
1117 }
1118}
Dan Willemsenf173d592017-04-27 14:28:00 -07001119
Dan Willemsen8122bd52017-10-12 20:20:41 -07001120func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001121 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1122 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001123 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1124 if _, err := os.Stat(asan); err == nil {
1125 return asan
1126 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001127 }
1128 }
1129 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1130}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001131
1132func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1133 c.brokenDupRules = val
1134}
1135
1136func (c *configImpl) BuildBrokenDupRules() bool {
1137 return c.brokenDupRules
1138}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001139
Dan Willemsen25e6f092019-04-09 10:22:43 -07001140func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1141 c.brokenUsesNetwork = val
1142}
1143
1144func (c *configImpl) BuildBrokenUsesNetwork() bool {
1145 return c.brokenUsesNetwork
1146}
1147
Dan Willemsene3336352020-01-02 19:10:38 -08001148func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1149 c.brokenNinjaEnvVars = val
1150}
1151
1152func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1153 return c.brokenNinjaEnvVars
1154}
1155
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001156func (c *configImpl) SetTargetDeviceDir(dir string) {
1157 c.targetDeviceDir = dir
1158}
1159
1160func (c *configImpl) TargetDeviceDir() string {
1161 return c.targetDeviceDir
1162}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001163
Patrice Arruda219eef32020-06-01 17:29:30 +00001164func (c *configImpl) BuildDateTime() string {
1165 return c.buildDateTime
1166}
1167
1168func (c *configImpl) MetricsUploaderApp() string {
1169 if p, ok := c.environ.Get("ANDROID_ENABLE_METRICS_UPLOAD"); ok {
1170 return p
1171 }
1172 return ""
1173}
Patrice Arruda83842d72020-12-08 19:42:08 +00001174
1175// LogsDir returns the logs directory where build log and metrics
1176// files are located. By default, the logs directory is the out
1177// directory. If the argument dist is specified, the logs directory
1178// is <dist_dir>/logs.
1179func (c *configImpl) LogsDir() string {
1180 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001181 // Always write logs to the real dist dir, even if Bazel is using a rigged dist dir for other files
1182 return filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001183 }
1184 return c.OutDir()
1185}
1186
1187// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1188// where the bazel profiles are located.
1189func (c *configImpl) BazelMetricsDir() string {
1190 return filepath.Join(c.LogsDir(), "bazel_metrics")
1191}