blob: 862e09f3cf7b328b8244055a5b7386b35b8d69a0 [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 {
140 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
141 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800142 outDir := "out"
143 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
144 if wd, err := os.Getwd(); err != nil {
145 ctx.Fatalln("Failed to get working directory:", err)
146 } else {
147 outDir = filepath.Join(baseDir, filepath.Base(wd))
148 }
149 }
150 ret.environ.Set("OUT_DIR", outDir)
151 }
152
Dan Willemsen2d31a442018-10-20 21:33:41 -0700153 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
154 ret.distDir = filepath.Clean(distDir)
155 } else {
156 ret.distDir = filepath.Join(ret.OutDir(), "dist")
157 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700158
Dan Willemsen1e704462016-08-21 15:17:17 -0700159 ret.environ.Unset(
160 // We're already using it
161 "USE_SOONG_UI",
162
163 // We should never use GOROOT/GOPATH from the shell environment
164 "GOROOT",
165 "GOPATH",
166
167 // These should only come from Soong, not the environment.
168 "CLANG",
169 "CLANG_CXX",
170 "CCC_CC",
171 "CCC_CXX",
172
173 // Used by the goma compiler wrapper, but should only be set by
174 // gomacc
175 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800176
177 // We handle this above
178 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700179
Dan Willemsen2d31a442018-10-20 21:33:41 -0700180 // This is handled above too, and set for individual commands later
181 "DIST_DIR",
182
Dan Willemsen68a09852017-04-18 13:56:57 -0700183 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000184 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700185 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700186 "DISPLAY",
187 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700188 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700189 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700190
191 // Drop make flags
192 "MAKEFLAGS",
193 "MAKELEVEL",
194 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700195
196 // Set in envsetup.sh, reset in makefiles
197 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700198
199 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
200 "ANDROID_BUILD_TOP",
201 "ANDROID_HOST_OUT",
202 "ANDROID_PRODUCT_OUT",
203 "ANDROID_HOST_OUT_TESTCASES",
204 "ANDROID_TARGET_OUT_TESTCASES",
205 "ANDROID_TOOLCHAIN",
206 "ANDROID_TOOLCHAIN_2ND_ARCH",
207 "ANDROID_DEV_SCRIPTS",
208 "ANDROID_EMULATOR_PREBUILTS",
209 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700210 )
211
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400212 if ret.UseGoma() || ret.ForceUseGoma() {
213 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
214 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400215 }
216
Dan Willemsen1e704462016-08-21 15:17:17 -0700217 // Tell python not to spam the source tree with .pyc files.
218 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
219
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400220 tmpDir := absPath(ctx, ret.TempDir())
221 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800222
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700223 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
224 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
225 "llvm-binutils-stable/llvm-symbolizer")
226 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
227
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800228 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700229 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800230
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700231 if srcDir := absPath(ctx, "."); strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700232 ctx.Println("You are building in a directory whose absolute path contains a space character:")
233 ctx.Println()
234 ctx.Printf("%q\n", srcDir)
235 ctx.Println()
236 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700237 }
238
239 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700240 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
241 ctx.Println()
242 ctx.Printf("%q\n", outDir)
243 ctx.Println()
244 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700245 }
246
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000247 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700248 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
249 ctx.Println()
250 ctx.Printf("%q\n", distDir)
251 ctx.Println()
252 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700253 }
254
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700255 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000256 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
257 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100258 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700259 javaHome := func() string {
260 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
261 return override
262 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000263 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
264 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 +0100265 }
Pete Gillinabbcdda2019-10-28 16:15:33 +0000266 return java11Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700267 }()
268 absJavaHome := absPath(ctx, javaHome)
269
Dan Willemsened869522018-01-08 14:58:46 -0800270 ret.configureLocale(ctx)
271
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700272 newPath := []string{filepath.Join(absJavaHome, "bin")}
273 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
274 newPath = append(newPath, path)
275 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100276
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700277 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
278 ret.environ.Set("JAVA_HOME", absJavaHome)
279 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000280 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
281 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100282 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700283 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
284
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800285 outDir := ret.OutDir()
286 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800287 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800288 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800289 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800290 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800291 }
Colin Cross28f527c2019-11-26 16:19:04 -0800292
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800293 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
294
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400295 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400296 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400297 ret.environ.Set(k, v)
298 }
299 }
300
Patrice Arruda83842d72020-12-08 19:42:08 +0000301 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800302 if err := os.RemoveAll(bpd); err != nil {
303 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
304 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000305
306 ret.useBazel = ret.environ.IsEnvTrue("USE_BAZEL")
307
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800308 if ret.UseBazel() {
309 if err := os.MkdirAll(bpd, 0777); err != nil {
310 ctx.Fatalf("Failed to create bazel profile directory %q: %v", bpd, err)
311 }
312 }
313
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000314 if ret.UseBazel() {
315 ret.riggedDistDirForBazel = filepath.Join(ret.OutDir(), "dist")
316 } else {
317 // Not rigged
318 ret.riggedDistDirForBazel = ret.distDir
319 }
320
Patrice Arruda96850362020-08-11 20:41:11 +0000321 c := Config{ret}
322 storeConfigMetrics(ctx, c)
323 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700324}
325
Patrice Arruda13848222019-04-22 17:12:02 -0700326// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
327// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700328func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
329 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700330}
331
Patrice Arruda96850362020-08-11 20:41:11 +0000332// storeConfigMetrics selects a set of configuration information and store in
333// the metrics system for further analysis.
334func storeConfigMetrics(ctx Context, config Config) {
335 if ctx.Metrics == nil {
336 return
337 }
338
339 b := &smpb.BuildConfig{
Patrice Arrudac97d6dc2020-09-28 18:22:07 +0000340 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
341 UseGoma: proto.Bool(config.UseGoma()),
342 UseRbe: proto.Bool(config.UseRBE()),
Patrice Arruda96850362020-08-11 20:41:11 +0000343 }
344 ctx.Metrics.BuildConfig(b)
Patrice Arruda3edfd482020-10-13 23:58:41 +0000345
346 s := &smpb.SystemResourceInfo{
347 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
348 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
349 }
350 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000351}
352
Patrice Arruda13848222019-04-22 17:12:02 -0700353// getConfigArgs processes the command arguments based on the build action and creates a set of new
354// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700355func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700356 // The next block of code verifies that the current directory is the root directory of the source
357 // tree. It then finds the relative path of dir based on the root directory of the source tree
358 // and verify that dir is inside of the source tree.
359 checkTopDir(ctx)
360 topDir, err := os.Getwd()
361 if err != nil {
362 ctx.Fatalf("Error retrieving top directory: %v", err)
363 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700364 dir, err = filepath.EvalSymlinks(dir)
365 if err != nil {
366 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
367 }
Patrice Arruda13848222019-04-22 17:12:02 -0700368 dir, err = filepath.Abs(dir)
369 if err != nil {
370 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
371 }
372 relDir, err := filepath.Rel(topDir, dir)
373 if err != nil {
374 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
375 }
376 // If there are ".." in the path, it's not in the source tree.
377 if strings.Contains(relDir, "..") {
378 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
379 }
380
381 configArgs := args[:]
382
383 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
384 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
385 targetNamePrefix := "MODULES-IN-"
386 if inList("GET-INSTALL-PATH", configArgs) {
387 targetNamePrefix = "GET-INSTALL-PATH-IN-"
388 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
389 }
390
Patrice Arruda13848222019-04-22 17:12:02 -0700391 var targets []string
392
393 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700394 case BUILD_MODULES:
395 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700396 case BUILD_MODULES_IN_A_DIRECTORY:
397 // If dir is the root source tree, all the modules are built of the source tree are built so
398 // no need to find the build file.
399 if topDir == dir {
400 break
401 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700402
Patrice Arruda13848222019-04-22 17:12:02 -0700403 buildFile := findBuildFile(ctx, relDir)
404 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700405 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700406 }
Patrice Arruda13848222019-04-22 17:12:02 -0700407 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
408 case BUILD_MODULES_IN_DIRECTORIES:
409 newConfigArgs, dirs := splitArgs(configArgs)
410 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700411 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700412 }
413
414 // Tidy only override all other specified targets.
415 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
416 if tidyOnly == "true" || tidyOnly == "1" {
417 configArgs = append(configArgs, "tidy_only")
418 } else {
419 configArgs = append(configArgs, targets...)
420 }
421
422 return configArgs
423}
424
425// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
426func convertToTarget(dir string, targetNamePrefix string) string {
427 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
428}
429
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700430// hasBuildFile returns true if dir contains an Android build file.
431func hasBuildFile(ctx Context, dir string) bool {
432 for _, buildFile := range buildFiles {
433 _, err := os.Stat(filepath.Join(dir, buildFile))
434 if err == nil {
435 return true
436 }
437 if !os.IsNotExist(err) {
438 ctx.Fatalf("Error retrieving the build file stats: %v", err)
439 }
440 }
441 return false
442}
443
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700444// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
445// in the current and any sub directory of dir. If a build file is not found, traverse the path
446// up by one directory and repeat again until either a build file is found or reached to the root
447// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
448// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700449func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700450 // If the string is empty or ".", assume it is top directory of the source tree.
451 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700452 return ""
453 }
454
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700455 found := false
456 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
457 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
458 if err != nil {
459 return err
460 }
461 if found {
462 return filepath.SkipDir
463 }
464 if info.IsDir() {
465 return nil
466 }
467 for _, buildFile := range buildFiles {
468 if info.Name() == buildFile {
469 found = true
470 return filepath.SkipDir
471 }
472 }
473 return nil
474 })
475 if err != nil {
476 ctx.Fatalf("Error finding Android build file: %v", err)
477 }
478
479 if found {
480 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700481 }
482 }
483
484 return ""
485}
486
487// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
488func splitArgs(args []string) (newArgs []string, dirs []string) {
489 specialArgs := map[string]bool{
490 "showcommands": true,
491 "snod": true,
492 "dist": true,
493 "checkbuild": true,
494 }
495
496 newArgs = []string{}
497 dirs = []string{}
498
499 for _, arg := range args {
500 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
501 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
502 newArgs = append(newArgs, arg)
503 continue
504 }
505
506 if _, ok := specialArgs[arg]; ok {
507 newArgs = append(newArgs, arg)
508 continue
509 }
510
511 dirs = append(dirs, arg)
512 }
513
514 return newArgs, dirs
515}
516
517// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
518// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
519// source root tree where the build action command was invoked. Each directory is validated if the
520// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700521func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700522 for _, dir := range dirs {
523 // The directory may have specified specific modules to build. ":" is the separator to separate
524 // the directory and the list of modules.
525 s := strings.Split(dir, ":")
526 l := len(s)
527 if l > 2 { // more than one ":" was specified.
528 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
529 }
530
531 dir = filepath.Join(relDir, s[0])
532 if _, err := os.Stat(dir); err != nil {
533 ctx.Fatalf("couldn't find directory %s", dir)
534 }
535
536 // Verify that if there are any targets specified after ":". Each target is separated by ",".
537 var newTargets []string
538 if l == 2 && s[1] != "" {
539 newTargets = strings.Split(s[1], ",")
540 if inList("", newTargets) {
541 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
542 }
543 }
544
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700545 // If there are specified targets to build in dir, an android build file must exist for the one
546 // shot build. For the non-targets case, find the appropriate build file and build all the
547 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700548 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700549 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700550 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
551 }
552 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700553 buildFile := findBuildFile(ctx, dir)
554 if buildFile == "" {
555 ctx.Fatalf("Build file not found for %s directory", dir)
556 }
557 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700558 }
559
Patrice Arruda13848222019-04-22 17:12:02 -0700560 targets = append(targets, newTargets...)
561 }
562
Dan Willemsence41e942019-07-29 23:39:30 -0700563 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700564}
565
Dan Willemsen9b587492017-07-10 22:13:00 -0700566func (c *configImpl) parseArgs(ctx Context, args []string) {
567 for i := 0; i < len(args); i++ {
568 arg := strings.TrimSpace(args[i])
Anton Hanssond274ea92021-06-04 10:09:01 +0100569 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" {
Anton Hansson546de4a2021-06-04 10:08:08 +0100577 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000578 c.skipKati = true
Anton Hansson546de4a2021-06-04 10:08:08 +0100579 } else if arg == "--soong-only" {
580 c.skipKati = true
581 c.skipKatiNinja = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700582 } else if arg == "--skip-soong-tests" {
583 c.skipSoongTests = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700584 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700585 parseArgNum := func(def int) int {
586 if len(arg) > 2 {
587 p, err := strconv.ParseUint(arg[2:], 10, 31)
588 if err != nil {
589 ctx.Fatalf("Failed to parse %q: %v", arg, err)
590 }
591 return int(p)
592 } else if i+1 < len(args) {
593 p, err := strconv.ParseUint(args[i+1], 10, 31)
594 if err == nil {
595 i++
596 return int(p)
597 }
598 }
599 return def
600 }
601
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700602 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700603 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700604 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700605 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700606 } else {
607 ctx.Fatalln("Unknown option:", arg)
608 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700609 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700610 if k == "OUT_DIR" {
611 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
612 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700613 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700614 } else if arg == "dist" {
615 c.dist = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700616 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700617 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800618 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700619 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700620 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700621 }
622 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700623}
624
Dan Willemsened869522018-01-08 14:58:46 -0800625func (c *configImpl) configureLocale(ctx Context) {
626 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
627 output, err := cmd.Output()
628
629 var locales []string
630 if err == nil {
631 locales = strings.Split(string(output), "\n")
632 } else {
633 // If we're unable to list the locales, let's assume en_US.UTF-8
634 locales = []string{"en_US.UTF-8"}
635 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
636 }
637
638 // gettext uses LANGUAGE, which is passed directly through
639
640 // For LANG and LC_*, only preserve the evaluated version of
641 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800642 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800643 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800644 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800645 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800646 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800647 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800648 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800649 }
650
651 c.environ.UnsetWithPrefix("LC_")
652
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800653 if userLang != "" {
654 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800655 }
656
657 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
658 // for others)
659 if inList("C.UTF-8", locales) {
660 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500661 } else if inList("C.utf8", locales) {
662 // These normalize to the same thing
663 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800664 } else if inList("en_US.UTF-8", locales) {
665 c.environ.Set("LANG", "en_US.UTF-8")
666 } else if inList("en_US.utf8", locales) {
667 // These normalize to the same thing
668 c.environ.Set("LANG", "en_US.UTF-8")
669 } else {
670 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
671 }
672}
673
Dan Willemsen1e704462016-08-21 15:17:17 -0700674// Lunch configures the environment for a specific product similarly to the
675// `lunch` bash function.
676func (c *configImpl) Lunch(ctx Context, product, variant string) {
677 if variant != "eng" && variant != "userdebug" && variant != "user" {
678 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
679 }
680
681 c.environ.Set("TARGET_PRODUCT", product)
682 c.environ.Set("TARGET_BUILD_VARIANT", variant)
683 c.environ.Set("TARGET_BUILD_TYPE", "release")
684 c.environ.Unset("TARGET_BUILD_APPS")
Martin Stjernholm08802332020-06-04 17:00:01 +0100685 c.environ.Unset("TARGET_BUILD_UNBUNDLED")
Dan Willemsen1e704462016-08-21 15:17:17 -0700686}
687
688// Tapas configures the environment to build one or more unbundled apps,
689// similarly to the `tapas` bash function.
690func (c *configImpl) Tapas(ctx Context, apps []string, arch, variant string) {
691 if len(apps) == 0 {
692 apps = []string{"all"}
693 }
694 if variant == "" {
695 variant = "eng"
696 }
697
698 if variant != "eng" && variant != "userdebug" && variant != "user" {
699 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
700 }
701
702 var product string
703 switch arch {
Dan Willemsen1e704462016-08-21 15:17:17 -0700704 case "arm", "":
705 product = "aosp_arm"
706 case "arm64":
707 product = "aosm_arm64"
Dan Willemsen1e704462016-08-21 15:17:17 -0700708 case "x86":
709 product = "aosp_x86"
710 case "x86_64":
711 product = "aosp_x86_64"
712 default:
713 ctx.Fatalf("Invalid architecture: %q", arch)
714 }
715
716 c.environ.Set("TARGET_PRODUCT", product)
717 c.environ.Set("TARGET_BUILD_VARIANT", variant)
718 c.environ.Set("TARGET_BUILD_TYPE", "release")
719 c.environ.Set("TARGET_BUILD_APPS", strings.Join(apps, " "))
720}
721
722func (c *configImpl) Environment() *Environment {
723 return c.environ
724}
725
726func (c *configImpl) Arguments() []string {
727 return c.arguments
728}
729
730func (c *configImpl) OutDir() string {
731 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700732 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700733 }
734 return "out"
735}
736
Dan Willemsen8a073a82017-02-04 17:30:44 -0800737func (c *configImpl) DistDir() string {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000738 if c.UseBazel() {
739 return c.riggedDistDirForBazel
740 } else {
741 return c.distDir
742 }
743}
744
745func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700746 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800747}
748
Dan Willemsen1e704462016-08-21 15:17:17 -0700749func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000750 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700751 return c.arguments
752 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700753 return c.ninjaArgs
754}
755
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500756func (c *configImpl) BazelOutDir() string {
757 return filepath.Join(c.OutDir(), "bazel")
758}
759
Dan Willemsen1e704462016-08-21 15:17:17 -0700760func (c *configImpl) SoongOutDir() string {
761 return filepath.Join(c.OutDir(), "soong")
762}
763
Jeff Gastonefc1b412017-03-29 17:29:06 -0700764func (c *configImpl) TempDir() string {
765 return shared.TempDirForOutDir(c.SoongOutDir())
766}
767
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700768func (c *configImpl) FileListDir() string {
769 return filepath.Join(c.OutDir(), ".module_paths")
770}
771
Dan Willemsen1e704462016-08-21 15:17:17 -0700772func (c *configImpl) KatiSuffix() string {
773 if c.katiSuffix != "" {
774 return c.katiSuffix
775 }
776 panic("SetKatiSuffix has not been called")
777}
778
Colin Cross37193492017-11-16 17:55:00 -0800779// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
780// user is interested in additional checks at the expense of build time.
781func (c *configImpl) Checkbuild() bool {
782 return c.checkbuild
783}
784
Dan Willemsen8a073a82017-02-04 17:30:44 -0800785func (c *configImpl) Dist() bool {
786 return c.dist
787}
788
Dan Willemsen1e704462016-08-21 15:17:17 -0700789func (c *configImpl) IsVerbose() bool {
790 return c.verbose
791}
792
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000793func (c *configImpl) SkipKati() bool {
794 return c.skipKati
795}
796
Anton Hansson546de4a2021-06-04 10:08:08 +0100797func (c *configImpl) SkipKatiNinja() bool {
798 return c.skipKatiNinja
799}
800
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100801func (c *configImpl) SkipNinja() bool {
802 return c.skipNinja
803}
804
Anton Hanssond274ea92021-06-04 10:09:01 +0100805func (c *configImpl) SetSkipNinja(v bool) {
806 c.skipNinja = v
807}
808
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000809func (c *configImpl) SkipConfig() bool {
810 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -0700811}
812
Dan Willemsen1e704462016-08-21 15:17:17 -0700813func (c *configImpl) TargetProduct() string {
814 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
815 return v
816 }
817 panic("TARGET_PRODUCT is not defined")
818}
819
Dan Willemsen02781d52017-05-12 19:28:13 -0700820func (c *configImpl) TargetDevice() string {
821 return c.targetDevice
822}
823
824func (c *configImpl) SetTargetDevice(device string) {
825 c.targetDevice = device
826}
827
828func (c *configImpl) TargetBuildVariant() string {
829 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
830 return v
831 }
832 panic("TARGET_BUILD_VARIANT is not defined")
833}
834
Dan Willemsen1e704462016-08-21 15:17:17 -0700835func (c *configImpl) KatiArgs() []string {
836 return c.katiArgs
837}
838
839func (c *configImpl) Parallel() int {
840 return c.parallel
841}
842
Colin Cross8b8bec32019-11-15 13:18:43 -0800843func (c *configImpl) HighmemParallel() int {
844 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
845 return i
846 }
847
848 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
849 parallel := c.Parallel()
850 if c.UseRemoteBuild() {
851 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
852 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
853 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
854 // Return 1/16th of the size of the local pool, rounding up.
855 return (parallel + 15) / 16
856 } else if c.totalRAM == 0 {
857 // Couldn't detect the total RAM, don't restrict highmem processes.
858 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -0700859 } else if c.totalRAM <= 16*1024*1024*1024 {
860 // Less than 16GB of ram, restrict to 1 highmem processes
861 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -0800862 } else if c.totalRAM <= 32*1024*1024*1024 {
863 // Less than 32GB of ram, restrict to 2 highmem processes
864 return 2
865 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
866 // If less than 8GB total RAM per process, reduce the number of highmem processes
867 return p
868 }
869 // No restriction on highmem processes
870 return parallel
871}
872
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800873func (c *configImpl) TotalRAM() uint64 {
874 return c.totalRAM
875}
876
Kousik Kumarec478642020-09-21 13:39:24 -0400877// ForceUseGoma determines whether we should override Goma deprecation
878// and use Goma for the current build or not.
879func (c *configImpl) ForceUseGoma() bool {
880 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
881 v = strings.TrimSpace(v)
882 if v != "" && v != "false" {
883 return true
884 }
885 }
886 return false
887}
888
Dan Willemsen1e704462016-08-21 15:17:17 -0700889func (c *configImpl) UseGoma() bool {
890 if v, ok := c.environ.Get("USE_GOMA"); ok {
891 v = strings.TrimSpace(v)
892 if v != "" && v != "false" {
893 return true
894 }
895 }
896 return false
897}
898
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +0900899func (c *configImpl) StartGoma() bool {
900 if !c.UseGoma() {
901 return false
902 }
903
904 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
905 v = strings.TrimSpace(v)
906 if v != "" && v != "false" {
907 return false
908 }
909 }
910 return true
911}
912
Ramy Medhatbbf25672019-07-17 12:30:04 +0000913func (c *configImpl) UseRBE() bool {
914 if v, ok := c.environ.Get("USE_RBE"); ok {
915 v = strings.TrimSpace(v)
916 if v != "" && v != "false" {
917 return true
918 }
919 }
920 return false
921}
922
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800923func (c *configImpl) UseBazel() bool {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000924 return c.useBazel
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800925}
926
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400927func (c *configImpl) bazelBuildMode() bazelBuildMode {
928 if c.Environment().IsEnvTrue("USE_BAZEL_ANALYSIS") {
929 return mixedBuild
930 } else if c.Environment().IsEnvTrue("GENERATE_BAZEL_FILES") {
931 return generateBuildFiles
932 } else {
933 return noBazel
934 }
935}
936
Ramy Medhatbbf25672019-07-17 12:30:04 +0000937func (c *configImpl) StartRBE() bool {
938 if !c.UseRBE() {
939 return false
940 }
941
942 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
943 v = strings.TrimSpace(v)
944 if v != "" && v != "false" {
945 return false
946 }
947 }
948 return true
949}
950
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000951func (c *configImpl) rbeLogDir() string {
Kousik Kumar0d15a722020-09-23 02:54:11 -0400952 for _, f := range []string{"RBE_log_dir", "FLAG_log_dir"} {
953 if v, ok := c.environ.Get(f); ok {
954 return v
955 }
956 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400957 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000958 return c.LogsDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400959 }
960 return c.OutDir()
961}
962
963func (c *configImpl) rbeStatsOutputDir() string {
Patrice Arruda62f1bf22020-07-07 12:48:26 +0000964 for _, f := range []string{"RBE_output_dir", "FLAG_output_dir"} {
965 if v, ok := c.environ.Get(f); ok {
966 return v
967 }
968 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000969 return c.rbeLogDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400970}
971
972func (c *configImpl) rbeLogPath() string {
973 for _, f := range []string{"RBE_log_path", "FLAG_log_path"} {
974 if v, ok := c.environ.Get(f); ok {
975 return v
976 }
977 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000978 return fmt.Sprintf("text://%v/reproxy_log.txt", c.rbeLogDir())
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400979}
980
981func (c *configImpl) rbeExecRoot() string {
982 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
983 if v, ok := c.environ.Get(f); ok {
984 return v
985 }
986 }
987 wd, err := os.Getwd()
988 if err != nil {
989 return ""
990 }
991 return wd
992}
993
994func (c *configImpl) rbeDir() string {
995 if v, ok := c.environ.Get("RBE_DIR"); ok {
996 return v
997 }
998 return "prebuilts/remoteexecution-client/live/"
999}
1000
1001func (c *configImpl) rbeReproxy() string {
1002 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1003 if v, ok := c.environ.Get(f); ok {
1004 return v
1005 }
1006 }
1007 return filepath.Join(c.rbeDir(), "reproxy")
1008}
1009
1010func (c *configImpl) rbeAuth() (string, string) {
1011 credFlags := []string{"use_application_default_credentials", "use_gce_credentials", "credential_file"}
1012 for _, cf := range credFlags {
1013 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1014 if v, ok := c.environ.Get(f); ok {
1015 v = strings.TrimSpace(v)
1016 if v != "" && v != "false" && v != "0" {
1017 return "RBE_" + cf, v
1018 }
1019 }
1020 }
1021 }
1022 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001023}
1024
Colin Cross9016b912019-11-11 14:57:42 -08001025func (c *configImpl) UseRemoteBuild() bool {
1026 return c.UseGoma() || c.UseRBE()
1027}
1028
Dan Willemsen1e704462016-08-21 15:17:17 -07001029// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001030// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001031// still limited by Parallel()
1032func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001033 if !c.UseRemoteBuild() {
1034 return 0
1035 }
1036 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1037 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001038 }
1039 return 500
1040}
1041
1042func (c *configImpl) SetKatiArgs(args []string) {
1043 c.katiArgs = args
1044}
1045
1046func (c *configImpl) SetNinjaArgs(args []string) {
1047 c.ninjaArgs = args
1048}
1049
1050func (c *configImpl) SetKatiSuffix(suffix string) {
1051 c.katiSuffix = suffix
1052}
1053
Dan Willemsene0879fc2017-08-04 15:06:27 -07001054func (c *configImpl) LastKatiSuffixFile() string {
1055 return filepath.Join(c.OutDir(), "last_kati_suffix")
1056}
1057
1058func (c *configImpl) HasKatiSuffix() bool {
1059 return c.katiSuffix != ""
1060}
1061
Dan Willemsen1e704462016-08-21 15:17:17 -07001062func (c *configImpl) KatiEnvFile() string {
1063 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1064}
1065
Dan Willemsen29971232018-09-26 14:58:30 -07001066func (c *configImpl) KatiBuildNinjaFile() string {
1067 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001068}
1069
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001070func (c *configImpl) KatiPackageNinjaFile() string {
1071 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1072}
1073
Dan Willemsen1e704462016-08-21 15:17:17 -07001074func (c *configImpl) SoongNinjaFile() string {
1075 return filepath.Join(c.SoongOutDir(), "build.ninja")
1076}
1077
1078func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001079 if c.katiSuffix == "" {
1080 return filepath.Join(c.OutDir(), "combined.ninja")
1081 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001082 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1083}
1084
1085func (c *configImpl) SoongAndroidMk() string {
1086 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1087}
1088
1089func (c *configImpl) SoongMakeVarsMk() string {
1090 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1091}
1092
Dan Willemsenf052f782017-05-18 15:29:04 -07001093func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001094 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001095}
1096
Dan Willemsen02781d52017-05-12 19:28:13 -07001097func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001098 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1099}
1100
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001101func (c *configImpl) KatiPackageMkDir() string {
1102 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1103}
1104
Dan Willemsenf052f782017-05-18 15:29:04 -07001105func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001106 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001107}
1108
1109func (c *configImpl) HostOut() string {
1110 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1111}
1112
1113// This probably needs to be multi-valued, so not exporting it for now
1114func (c *configImpl) hostCrossOut() string {
1115 if runtime.GOOS == "linux" {
1116 return filepath.Join(c.hostOutRoot(), "windows-x86")
1117 } else {
1118 return ""
1119 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001120}
1121
Dan Willemsen1e704462016-08-21 15:17:17 -07001122func (c *configImpl) HostPrebuiltTag() string {
1123 if runtime.GOOS == "linux" {
1124 return "linux-x86"
1125 } else if runtime.GOOS == "darwin" {
1126 return "darwin-x86"
1127 } else {
1128 panic("Unsupported OS")
1129 }
1130}
Dan Willemsenf173d592017-04-27 14:28:00 -07001131
Dan Willemsen8122bd52017-10-12 20:20:41 -07001132func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001133 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1134 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001135 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1136 if _, err := os.Stat(asan); err == nil {
1137 return asan
1138 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001139 }
1140 }
1141 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1142}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001143
1144func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1145 c.brokenDupRules = val
1146}
1147
1148func (c *configImpl) BuildBrokenDupRules() bool {
1149 return c.brokenDupRules
1150}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001151
Dan Willemsen25e6f092019-04-09 10:22:43 -07001152func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1153 c.brokenUsesNetwork = val
1154}
1155
1156func (c *configImpl) BuildBrokenUsesNetwork() bool {
1157 return c.brokenUsesNetwork
1158}
1159
Dan Willemsene3336352020-01-02 19:10:38 -08001160func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1161 c.brokenNinjaEnvVars = val
1162}
1163
1164func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1165 return c.brokenNinjaEnvVars
1166}
1167
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001168func (c *configImpl) SetTargetDeviceDir(dir string) {
1169 c.targetDeviceDir = dir
1170}
1171
1172func (c *configImpl) TargetDeviceDir() string {
1173 return c.targetDeviceDir
1174}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001175
Patrice Arruda219eef32020-06-01 17:29:30 +00001176func (c *configImpl) BuildDateTime() string {
1177 return c.buildDateTime
1178}
1179
1180func (c *configImpl) MetricsUploaderApp() string {
1181 if p, ok := c.environ.Get("ANDROID_ENABLE_METRICS_UPLOAD"); ok {
1182 return p
1183 }
1184 return ""
1185}
Patrice Arruda83842d72020-12-08 19:42:08 +00001186
1187// LogsDir returns the logs directory where build log and metrics
1188// files are located. By default, the logs directory is the out
1189// directory. If the argument dist is specified, the logs directory
1190// is <dist_dir>/logs.
1191func (c *configImpl) LogsDir() string {
1192 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001193 // Always write logs to the real dist dir, even if Bazel is using a rigged dist dir for other files
1194 return filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001195 }
1196 return c.OutDir()
1197}
1198
1199// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1200// where the bazel profiles are located.
1201func (c *configImpl) BazelMetricsDir() string {
1202 return filepath.Join(c.LogsDir(), "bazel_metrics")
1203}
Colin Cross7dcd16c2021-06-01 11:43:55 -07001204
1205func (c *configImpl) SetEmptyNinjaFile(v bool) {
1206 c.emptyNinjaFile = v
1207}
1208
1209func (c *configImpl) EmptyNinjaFile() bool {
1210 return c.emptyNinjaFile
1211}