blob: 4806721719fd9e818f9e536d0084f049df905858 [file] [log] [blame]
Dan Willemsen1e704462016-08-21 15:17:17 -07001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package build
16
17import (
Ramy Medhat0fc67eb2020-08-12 01:26:23 -040018 "fmt"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080019 "os"
Dan Willemsen1e704462016-08-21 15:17:17 -070020 "path/filepath"
21 "runtime"
22 "strconv"
23 "strings"
Nan Zhang2e6a4ff2018-02-14 13:27:26 -080024 "time"
Jeff Gastonefc1b412017-03-29 17:29:06 -070025
26 "android/soong/shared"
Kousik Kumarec478642020-09-21 13:39:24 -040027
Patrice Arruda96850362020-08-11 20:41:11 +000028 "github.com/golang/protobuf/proto"
29
30 smpb "android/soong/ui/metrics/metrics_proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070031)
32
33type Config struct{ *configImpl }
34
35type configImpl struct {
36 // From the environment
Colin Cross28f527c2019-11-26 16:19:04 -080037 arguments []string
38 goma bool
39 environ *Environment
40 distDir string
41 buildDateTime string
Dan Willemsen1e704462016-08-21 15:17:17 -070042
43 // From the arguments
Colin Cross00a8a3f2020-10-29 14:08:31 -070044 parallel int
45 keepGoing int
46 verbose bool
47 checkbuild bool
48 dist bool
Anton Hansson5e5c48b2020-11-27 12:35:20 +000049 skipConfig bool
50 skipKati bool
Anton Hansson0b55bdb2021-06-04 10:08:08 +010051 skipKatiNinja bool
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010052 skipNinja bool
Colin Cross00a8a3f2020-10-29 14:08:31 -070053 skipSoongTests bool
Dan Willemsen1e704462016-08-21 15:17:17 -070054
55 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070056 katiArgs []string
57 ninjaArgs []string
58 katiSuffix string
59 targetDevice string
60 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +000061 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -070062
Dan Willemsen2bb82d02019-12-27 09:35:42 -080063 // Autodetected
64 totalRAM uint64
65
Dan Willemsene3336352020-01-02 19:10:38 -080066 brokenDupRules bool
67 brokenUsesNetwork bool
68 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -070069
70 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +000071
72 useBazel bool
73
74 // During Bazel execution, Bazel cannot write outside OUT_DIR.
75 // So if DIST_DIR is set to an external dir (outside of OUT_DIR), we need to rig it temporarily and then migrate files at the end of the build.
76 riggedDistDirForBazel string
Colin Crossf3bdbcb2021-06-01 11:43:55 -070077
78 // Set by multiproduct_kati
79 emptyNinjaFile bool
Dan Willemsen1e704462016-08-21 15:17:17 -070080}
81
Dan Willemsenc2af0be2017-01-20 14:10:01 -080082const srcDirFileCheck = "build/soong/root.bp"
83
Patrice Arruda9450d0b2019-07-08 11:06:46 -070084var buildFiles = []string{"Android.mk", "Android.bp"}
85
Patrice Arruda13848222019-04-22 17:12:02 -070086type BuildAction uint
87
88const (
89 // Builds all of the modules and their dependencies of a specified directory, relative to the root
90 // directory of the source tree.
91 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
92
93 // Builds all of the modules and their dependencies of a list of specified directories. All specified
94 // directories are relative to the root directory of the source tree.
95 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -070096
97 // Build a list of specified modules. If none was specified, simply build the whole source tree.
98 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -070099)
100
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400101type bazelBuildMode int
102
103// Bazel-related build modes.
104const (
105 // Don't use bazel at all.
106 noBazel bazelBuildMode = iota
107
108 // Only generate build files (in a subdirectory of the out directory) and exit.
109 generateBuildFiles
110
Jingwen Chendd9725c2021-06-24 08:41:16 +0000111 // Only generate the Soong json module graph for use with jq, and exit.
112 generateJsonModuleGraph
113
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400114 // Generate synthetic build files and incorporate these files into a build which
115 // partially uses Bazel. Build metadata may come from Android.bp or BUILD files.
116 mixedBuild
117)
118
Patrice Arruda13848222019-04-22 17:12:02 -0700119// checkTopDir validates that the current directory is at the root directory of the source tree.
120func checkTopDir(ctx Context) {
121 if _, err := os.Stat(srcDirFileCheck); err != nil {
122 if os.IsNotExist(err) {
123 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
124 }
125 ctx.Fatalln("Error verifying tree state:", err)
126 }
127}
128
Dan Willemsen1e704462016-08-21 15:17:17 -0700129func NewConfig(ctx Context, args ...string) Config {
130 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000131 environ: OsEnvironment(),
132 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700133 }
134
Patrice Arruda90109172020-07-28 18:07:27 +0000135 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700136 ret.parallel = runtime.NumCPU() + 2
137 ret.keepGoing = 1
138
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800139 ret.totalRAM = detectTotalRAM(ctx)
140
Dan Willemsen9b587492017-07-10 22:13:00 -0700141 ret.parseArgs(ctx, args)
142
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800143 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700144 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
145 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
146 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800147 outDir := "out"
148 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
149 if wd, err := os.Getwd(); err != nil {
150 ctx.Fatalln("Failed to get working directory:", err)
151 } else {
152 outDir = filepath.Join(baseDir, filepath.Base(wd))
153 }
154 }
155 ret.environ.Set("OUT_DIR", outDir)
156 }
157
Dan Willemsen2d31a442018-10-20 21:33:41 -0700158 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
159 ret.distDir = filepath.Clean(distDir)
160 } else {
161 ret.distDir = filepath.Join(ret.OutDir(), "dist")
162 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700163
Dan Willemsen1e704462016-08-21 15:17:17 -0700164 ret.environ.Unset(
165 // We're already using it
166 "USE_SOONG_UI",
167
168 // We should never use GOROOT/GOPATH from the shell environment
169 "GOROOT",
170 "GOPATH",
171
172 // These should only come from Soong, not the environment.
173 "CLANG",
174 "CLANG_CXX",
175 "CCC_CC",
176 "CCC_CXX",
177
178 // Used by the goma compiler wrapper, but should only be set by
179 // gomacc
180 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800181
182 // We handle this above
183 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700184
Dan Willemsen2d31a442018-10-20 21:33:41 -0700185 // This is handled above too, and set for individual commands later
186 "DIST_DIR",
187
Dan Willemsen68a09852017-04-18 13:56:57 -0700188 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000189 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700190 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700191 "DISPLAY",
192 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700193 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700194 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700195
196 // Drop make flags
197 "MAKEFLAGS",
198 "MAKELEVEL",
199 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700200
201 // Set in envsetup.sh, reset in makefiles
202 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700203
204 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
205 "ANDROID_BUILD_TOP",
206 "ANDROID_HOST_OUT",
207 "ANDROID_PRODUCT_OUT",
208 "ANDROID_HOST_OUT_TESTCASES",
209 "ANDROID_TARGET_OUT_TESTCASES",
210 "ANDROID_TOOLCHAIN",
211 "ANDROID_TOOLCHAIN_2ND_ARCH",
212 "ANDROID_DEV_SCRIPTS",
213 "ANDROID_EMULATOR_PREBUILTS",
214 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700215 )
216
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400217 if ret.UseGoma() || ret.ForceUseGoma() {
218 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
219 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400220 }
221
Dan Willemsen1e704462016-08-21 15:17:17 -0700222 // Tell python not to spam the source tree with .pyc files.
223 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
224
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400225 tmpDir := absPath(ctx, ret.TempDir())
226 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800227
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700228 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
229 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
230 "llvm-binutils-stable/llvm-symbolizer")
231 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
232
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800233 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700234 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800235
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700236 if srcDir := absPath(ctx, "."); strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700237 ctx.Println("You are building in a directory whose absolute path contains a space character:")
238 ctx.Println()
239 ctx.Printf("%q\n", srcDir)
240 ctx.Println()
241 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700242 }
243
244 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700245 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
246 ctx.Println()
247 ctx.Printf("%q\n", outDir)
248 ctx.Println()
249 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700250 }
251
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000252 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700253 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
254 ctx.Println()
255 ctx.Printf("%q\n", distDir)
256 ctx.Println()
257 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700258 }
259
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700260 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000261 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
262 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100263 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700264 javaHome := func() string {
265 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
266 return override
267 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000268 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
269 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 +0100270 }
Pete Gillinabbcdda2019-10-28 16:15:33 +0000271 return java11Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700272 }()
273 absJavaHome := absPath(ctx, javaHome)
274
Dan Willemsened869522018-01-08 14:58:46 -0800275 ret.configureLocale(ctx)
276
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700277 newPath := []string{filepath.Join(absJavaHome, "bin")}
278 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
279 newPath = append(newPath, path)
280 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100281
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700282 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
283 ret.environ.Set("JAVA_HOME", absJavaHome)
284 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000285 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
286 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100287 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700288 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
289
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800290 outDir := ret.OutDir()
291 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800292 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800293 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800294 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800295 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800296 }
Colin Cross28f527c2019-11-26 16:19:04 -0800297
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800298 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
299
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400300 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400301 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400302 ret.environ.Set(k, v)
303 }
304 }
305
Patrice Arruda83842d72020-12-08 19:42:08 +0000306 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800307 if err := os.RemoveAll(bpd); err != nil {
308 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
309 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000310
311 ret.useBazel = ret.environ.IsEnvTrue("USE_BAZEL")
312
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800313 if ret.UseBazel() {
314 if err := os.MkdirAll(bpd, 0777); err != nil {
315 ctx.Fatalf("Failed to create bazel profile directory %q: %v", bpd, err)
316 }
317 }
318
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000319 if ret.UseBazel() {
320 ret.riggedDistDirForBazel = filepath.Join(ret.OutDir(), "dist")
321 } else {
322 // Not rigged
323 ret.riggedDistDirForBazel = ret.distDir
324 }
325
Patrice Arruda96850362020-08-11 20:41:11 +0000326 c := Config{ret}
327 storeConfigMetrics(ctx, c)
328 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700329}
330
Patrice Arruda13848222019-04-22 17:12:02 -0700331// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
332// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700333func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
334 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700335}
336
Patrice Arruda96850362020-08-11 20:41:11 +0000337// storeConfigMetrics selects a set of configuration information and store in
338// the metrics system for further analysis.
339func storeConfigMetrics(ctx Context, config Config) {
340 if ctx.Metrics == nil {
341 return
342 }
343
344 b := &smpb.BuildConfig{
Patrice Arrudac97d6dc2020-09-28 18:22:07 +0000345 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
346 UseGoma: proto.Bool(config.UseGoma()),
347 UseRbe: proto.Bool(config.UseRBE()),
Patrice Arruda96850362020-08-11 20:41:11 +0000348 }
349 ctx.Metrics.BuildConfig(b)
Patrice Arruda3edfd482020-10-13 23:58:41 +0000350
351 s := &smpb.SystemResourceInfo{
352 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
353 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
354 }
355 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000356}
357
Patrice Arruda13848222019-04-22 17:12:02 -0700358// getConfigArgs processes the command arguments based on the build action and creates a set of new
359// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700360func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700361 // The next block of code verifies that the current directory is the root directory of the source
362 // tree. It then finds the relative path of dir based on the root directory of the source tree
363 // and verify that dir is inside of the source tree.
364 checkTopDir(ctx)
365 topDir, err := os.Getwd()
366 if err != nil {
367 ctx.Fatalf("Error retrieving top directory: %v", err)
368 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700369 dir, err = filepath.EvalSymlinks(dir)
370 if err != nil {
371 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
372 }
Patrice Arruda13848222019-04-22 17:12:02 -0700373 dir, err = filepath.Abs(dir)
374 if err != nil {
375 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
376 }
377 relDir, err := filepath.Rel(topDir, dir)
378 if err != nil {
379 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
380 }
381 // If there are ".." in the path, it's not in the source tree.
382 if strings.Contains(relDir, "..") {
383 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
384 }
385
386 configArgs := args[:]
387
388 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
389 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
390 targetNamePrefix := "MODULES-IN-"
391 if inList("GET-INSTALL-PATH", configArgs) {
392 targetNamePrefix = "GET-INSTALL-PATH-IN-"
393 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
394 }
395
Patrice Arruda13848222019-04-22 17:12:02 -0700396 var targets []string
397
398 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700399 case BUILD_MODULES:
400 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700401 case BUILD_MODULES_IN_A_DIRECTORY:
402 // If dir is the root source tree, all the modules are built of the source tree are built so
403 // no need to find the build file.
404 if topDir == dir {
405 break
406 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700407
Patrice Arruda13848222019-04-22 17:12:02 -0700408 buildFile := findBuildFile(ctx, relDir)
409 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700410 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700411 }
Patrice Arruda13848222019-04-22 17:12:02 -0700412 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
413 case BUILD_MODULES_IN_DIRECTORIES:
414 newConfigArgs, dirs := splitArgs(configArgs)
415 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700416 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700417 }
418
419 // Tidy only override all other specified targets.
420 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
421 if tidyOnly == "true" || tidyOnly == "1" {
422 configArgs = append(configArgs, "tidy_only")
423 } else {
424 configArgs = append(configArgs, targets...)
425 }
426
427 return configArgs
428}
429
430// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
431func convertToTarget(dir string, targetNamePrefix string) string {
432 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
433}
434
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700435// hasBuildFile returns true if dir contains an Android build file.
436func hasBuildFile(ctx Context, dir string) bool {
437 for _, buildFile := range buildFiles {
438 _, err := os.Stat(filepath.Join(dir, buildFile))
439 if err == nil {
440 return true
441 }
442 if !os.IsNotExist(err) {
443 ctx.Fatalf("Error retrieving the build file stats: %v", err)
444 }
445 }
446 return false
447}
448
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700449// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
450// in the current and any sub directory of dir. If a build file is not found, traverse the path
451// up by one directory and repeat again until either a build file is found or reached to the root
452// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
453// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700454func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700455 // If the string is empty or ".", assume it is top directory of the source tree.
456 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700457 return ""
458 }
459
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700460 found := false
461 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
462 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
463 if err != nil {
464 return err
465 }
466 if found {
467 return filepath.SkipDir
468 }
469 if info.IsDir() {
470 return nil
471 }
472 for _, buildFile := range buildFiles {
473 if info.Name() == buildFile {
474 found = true
475 return filepath.SkipDir
476 }
477 }
478 return nil
479 })
480 if err != nil {
481 ctx.Fatalf("Error finding Android build file: %v", err)
482 }
483
484 if found {
485 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700486 }
487 }
488
489 return ""
490}
491
492// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
493func splitArgs(args []string) (newArgs []string, dirs []string) {
494 specialArgs := map[string]bool{
495 "showcommands": true,
496 "snod": true,
497 "dist": true,
498 "checkbuild": true,
499 }
500
501 newArgs = []string{}
502 dirs = []string{}
503
504 for _, arg := range args {
505 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
506 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
507 newArgs = append(newArgs, arg)
508 continue
509 }
510
511 if _, ok := specialArgs[arg]; ok {
512 newArgs = append(newArgs, arg)
513 continue
514 }
515
516 dirs = append(dirs, arg)
517 }
518
519 return newArgs, dirs
520}
521
522// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
523// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
524// source root tree where the build action command was invoked. Each directory is validated if the
525// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700526func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700527 for _, dir := range dirs {
528 // The directory may have specified specific modules to build. ":" is the separator to separate
529 // the directory and the list of modules.
530 s := strings.Split(dir, ":")
531 l := len(s)
532 if l > 2 { // more than one ":" was specified.
533 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
534 }
535
536 dir = filepath.Join(relDir, s[0])
537 if _, err := os.Stat(dir); err != nil {
538 ctx.Fatalf("couldn't find directory %s", dir)
539 }
540
541 // Verify that if there are any targets specified after ":". Each target is separated by ",".
542 var newTargets []string
543 if l == 2 && s[1] != "" {
544 newTargets = strings.Split(s[1], ",")
545 if inList("", newTargets) {
546 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
547 }
548 }
549
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700550 // If there are specified targets to build in dir, an android build file must exist for the one
551 // shot build. For the non-targets case, find the appropriate build file and build all the
552 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700553 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700554 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700555 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
556 }
557 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700558 buildFile := findBuildFile(ctx, dir)
559 if buildFile == "" {
560 ctx.Fatalf("Build file not found for %s directory", dir)
561 }
562 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700563 }
564
Patrice Arruda13848222019-04-22 17:12:02 -0700565 targets = append(targets, newTargets...)
566 }
567
Dan Willemsence41e942019-07-29 23:39:30 -0700568 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700569}
570
Dan Willemsen9b587492017-07-10 22:13:00 -0700571func (c *configImpl) parseArgs(ctx Context, args []string) {
572 for i := 0; i < len(args); i++ {
573 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100574 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700575 c.verbose = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100576 } else if arg == "--skip-ninja" {
577 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700578 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700579 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
580 // but it does run a Kati ninja file if the .kati_enabled marker file was created
581 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000582 c.skipConfig = true
583 c.skipKati = true
584 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100585 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000586 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100587 } else if arg == "--soong-only" {
588 c.skipKati = true
589 c.skipKatiNinja = true
Colin Cross30e444b2021-06-18 11:26:19 -0700590 } else if arg == "--skip-config" {
591 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700592 } else if arg == "--skip-soong-tests" {
593 c.skipSoongTests = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700594 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700595 parseArgNum := func(def int) int {
596 if len(arg) > 2 {
597 p, err := strconv.ParseUint(arg[2:], 10, 31)
598 if err != nil {
599 ctx.Fatalf("Failed to parse %q: %v", arg, err)
600 }
601 return int(p)
602 } else if i+1 < len(args) {
603 p, err := strconv.ParseUint(args[i+1], 10, 31)
604 if err == nil {
605 i++
606 return int(p)
607 }
608 }
609 return def
610 }
611
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700612 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700613 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700614 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700615 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700616 } else {
617 ctx.Fatalln("Unknown option:", arg)
618 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700619 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700620 if k == "OUT_DIR" {
621 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
622 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700623 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700624 } else if arg == "dist" {
625 c.dist = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700626 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700627 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800628 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700629 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700630 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700631 }
632 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700633}
634
Dan Willemsened869522018-01-08 14:58:46 -0800635func (c *configImpl) configureLocale(ctx Context) {
636 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
637 output, err := cmd.Output()
638
639 var locales []string
640 if err == nil {
641 locales = strings.Split(string(output), "\n")
642 } else {
643 // If we're unable to list the locales, let's assume en_US.UTF-8
644 locales = []string{"en_US.UTF-8"}
645 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
646 }
647
648 // gettext uses LANGUAGE, which is passed directly through
649
650 // For LANG and LC_*, only preserve the evaluated version of
651 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800652 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800653 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800654 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800655 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800656 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800657 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800658 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800659 }
660
661 c.environ.UnsetWithPrefix("LC_")
662
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800663 if userLang != "" {
664 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800665 }
666
667 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
668 // for others)
669 if inList("C.UTF-8", locales) {
670 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500671 } else if inList("C.utf8", locales) {
672 // These normalize to the same thing
673 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800674 } else if inList("en_US.UTF-8", locales) {
675 c.environ.Set("LANG", "en_US.UTF-8")
676 } else if inList("en_US.utf8", locales) {
677 // These normalize to the same thing
678 c.environ.Set("LANG", "en_US.UTF-8")
679 } else {
680 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
681 }
682}
683
Dan Willemsen1e704462016-08-21 15:17:17 -0700684// Lunch configures the environment for a specific product similarly to the
685// `lunch` bash function.
686func (c *configImpl) Lunch(ctx Context, product, variant string) {
687 if variant != "eng" && variant != "userdebug" && variant != "user" {
688 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
689 }
690
691 c.environ.Set("TARGET_PRODUCT", product)
692 c.environ.Set("TARGET_BUILD_VARIANT", variant)
693 c.environ.Set("TARGET_BUILD_TYPE", "release")
694 c.environ.Unset("TARGET_BUILD_APPS")
Martin Stjernholm08802332020-06-04 17:00:01 +0100695 c.environ.Unset("TARGET_BUILD_UNBUNDLED")
Dan Willemsen1e704462016-08-21 15:17:17 -0700696}
697
698// Tapas configures the environment to build one or more unbundled apps,
699// similarly to the `tapas` bash function.
700func (c *configImpl) Tapas(ctx Context, apps []string, arch, variant string) {
701 if len(apps) == 0 {
702 apps = []string{"all"}
703 }
704 if variant == "" {
705 variant = "eng"
706 }
707
708 if variant != "eng" && variant != "userdebug" && variant != "user" {
709 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
710 }
711
712 var product string
713 switch arch {
Dan Willemsen1e704462016-08-21 15:17:17 -0700714 case "arm", "":
715 product = "aosp_arm"
716 case "arm64":
717 product = "aosm_arm64"
Dan Willemsen1e704462016-08-21 15:17:17 -0700718 case "x86":
719 product = "aosp_x86"
720 case "x86_64":
721 product = "aosp_x86_64"
722 default:
723 ctx.Fatalf("Invalid architecture: %q", arch)
724 }
725
726 c.environ.Set("TARGET_PRODUCT", product)
727 c.environ.Set("TARGET_BUILD_VARIANT", variant)
728 c.environ.Set("TARGET_BUILD_TYPE", "release")
729 c.environ.Set("TARGET_BUILD_APPS", strings.Join(apps, " "))
730}
731
732func (c *configImpl) Environment() *Environment {
733 return c.environ
734}
735
736func (c *configImpl) Arguments() []string {
737 return c.arguments
738}
739
740func (c *configImpl) OutDir() string {
741 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700742 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700743 }
744 return "out"
745}
746
Dan Willemsen8a073a82017-02-04 17:30:44 -0800747func (c *configImpl) DistDir() string {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000748 if c.UseBazel() {
749 return c.riggedDistDirForBazel
750 } else {
751 return c.distDir
752 }
753}
754
755func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700756 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800757}
758
Dan Willemsen1e704462016-08-21 15:17:17 -0700759func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000760 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700761 return c.arguments
762 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700763 return c.ninjaArgs
764}
765
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500766func (c *configImpl) BazelOutDir() string {
767 return filepath.Join(c.OutDir(), "bazel")
768}
769
Dan Willemsen1e704462016-08-21 15:17:17 -0700770func (c *configImpl) SoongOutDir() string {
771 return filepath.Join(c.OutDir(), "soong")
772}
773
Jeff Gastonefc1b412017-03-29 17:29:06 -0700774func (c *configImpl) TempDir() string {
775 return shared.TempDirForOutDir(c.SoongOutDir())
776}
777
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700778func (c *configImpl) FileListDir() string {
779 return filepath.Join(c.OutDir(), ".module_paths")
780}
781
Dan Willemsen1e704462016-08-21 15:17:17 -0700782func (c *configImpl) KatiSuffix() string {
783 if c.katiSuffix != "" {
784 return c.katiSuffix
785 }
786 panic("SetKatiSuffix has not been called")
787}
788
Colin Cross37193492017-11-16 17:55:00 -0800789// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
790// user is interested in additional checks at the expense of build time.
791func (c *configImpl) Checkbuild() bool {
792 return c.checkbuild
793}
794
Dan Willemsen8a073a82017-02-04 17:30:44 -0800795func (c *configImpl) Dist() bool {
796 return c.dist
797}
798
Dan Willemsen1e704462016-08-21 15:17:17 -0700799func (c *configImpl) IsVerbose() bool {
800 return c.verbose
801}
802
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000803func (c *configImpl) SkipKati() bool {
804 return c.skipKati
805}
806
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100807func (c *configImpl) SkipKatiNinja() bool {
808 return c.skipKatiNinja
809}
810
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100811func (c *configImpl) SkipNinja() bool {
812 return c.skipNinja
813}
814
Anton Hansson5a7861a2021-06-04 10:09:01 +0100815func (c *configImpl) SetSkipNinja(v bool) {
816 c.skipNinja = v
817}
818
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000819func (c *configImpl) SkipConfig() bool {
820 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -0700821}
822
Dan Willemsen1e704462016-08-21 15:17:17 -0700823func (c *configImpl) TargetProduct() string {
824 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
825 return v
826 }
827 panic("TARGET_PRODUCT is not defined")
828}
829
Dan Willemsen02781d52017-05-12 19:28:13 -0700830func (c *configImpl) TargetDevice() string {
831 return c.targetDevice
832}
833
834func (c *configImpl) SetTargetDevice(device string) {
835 c.targetDevice = device
836}
837
838func (c *configImpl) TargetBuildVariant() string {
839 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
840 return v
841 }
842 panic("TARGET_BUILD_VARIANT is not defined")
843}
844
Dan Willemsen1e704462016-08-21 15:17:17 -0700845func (c *configImpl) KatiArgs() []string {
846 return c.katiArgs
847}
848
849func (c *configImpl) Parallel() int {
850 return c.parallel
851}
852
Colin Cross8b8bec32019-11-15 13:18:43 -0800853func (c *configImpl) HighmemParallel() int {
854 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
855 return i
856 }
857
858 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
859 parallel := c.Parallel()
860 if c.UseRemoteBuild() {
861 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
862 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
863 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
864 // Return 1/16th of the size of the local pool, rounding up.
865 return (parallel + 15) / 16
866 } else if c.totalRAM == 0 {
867 // Couldn't detect the total RAM, don't restrict highmem processes.
868 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -0700869 } else if c.totalRAM <= 16*1024*1024*1024 {
870 // Less than 16GB of ram, restrict to 1 highmem processes
871 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -0800872 } else if c.totalRAM <= 32*1024*1024*1024 {
873 // Less than 32GB of ram, restrict to 2 highmem processes
874 return 2
875 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
876 // If less than 8GB total RAM per process, reduce the number of highmem processes
877 return p
878 }
879 // No restriction on highmem processes
880 return parallel
881}
882
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800883func (c *configImpl) TotalRAM() uint64 {
884 return c.totalRAM
885}
886
Kousik Kumarec478642020-09-21 13:39:24 -0400887// ForceUseGoma determines whether we should override Goma deprecation
888// and use Goma for the current build or not.
889func (c *configImpl) ForceUseGoma() bool {
890 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
891 v = strings.TrimSpace(v)
892 if v != "" && v != "false" {
893 return true
894 }
895 }
896 return false
897}
898
Dan Willemsen1e704462016-08-21 15:17:17 -0700899func (c *configImpl) UseGoma() bool {
900 if v, ok := c.environ.Get("USE_GOMA"); ok {
901 v = strings.TrimSpace(v)
902 if v != "" && v != "false" {
903 return true
904 }
905 }
906 return false
907}
908
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +0900909func (c *configImpl) StartGoma() bool {
910 if !c.UseGoma() {
911 return false
912 }
913
914 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
915 v = strings.TrimSpace(v)
916 if v != "" && v != "false" {
917 return false
918 }
919 }
920 return true
921}
922
Ramy Medhatbbf25672019-07-17 12:30:04 +0000923func (c *configImpl) UseRBE() bool {
924 if v, ok := c.environ.Get("USE_RBE"); ok {
925 v = strings.TrimSpace(v)
926 if v != "" && v != "false" {
927 return true
928 }
929 }
930 return false
931}
932
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800933func (c *configImpl) UseBazel() bool {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000934 return c.useBazel
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800935}
936
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400937func (c *configImpl) bazelBuildMode() bazelBuildMode {
938 if c.Environment().IsEnvTrue("USE_BAZEL_ANALYSIS") {
939 return mixedBuild
940 } else if c.Environment().IsEnvTrue("GENERATE_BAZEL_FILES") {
941 return generateBuildFiles
Jingwen Chendd9725c2021-06-24 08:41:16 +0000942 } else if v, ok := c.Environment().Get("SOONG_DUMP_JSON_MODULE_GRAPH"); ok && v != "" {
943 return generateJsonModuleGraph
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400944 } else {
945 return noBazel
946 }
947}
948
Ramy Medhatbbf25672019-07-17 12:30:04 +0000949func (c *configImpl) StartRBE() bool {
950 if !c.UseRBE() {
951 return false
952 }
953
954 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
955 v = strings.TrimSpace(v)
956 if v != "" && v != "false" {
957 return false
958 }
959 }
960 return true
961}
962
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000963func (c *configImpl) rbeLogDir() string {
Kousik Kumar0d15a722020-09-23 02:54:11 -0400964 for _, f := range []string{"RBE_log_dir", "FLAG_log_dir"} {
965 if v, ok := c.environ.Get(f); ok {
966 return v
967 }
968 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400969 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000970 return c.LogsDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400971 }
972 return c.OutDir()
973}
974
975func (c *configImpl) rbeStatsOutputDir() string {
Patrice Arruda62f1bf22020-07-07 12:48:26 +0000976 for _, f := range []string{"RBE_output_dir", "FLAG_output_dir"} {
977 if v, ok := c.environ.Get(f); ok {
978 return v
979 }
980 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000981 return c.rbeLogDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400982}
983
984func (c *configImpl) rbeLogPath() string {
985 for _, f := range []string{"RBE_log_path", "FLAG_log_path"} {
986 if v, ok := c.environ.Get(f); ok {
987 return v
988 }
989 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000990 return fmt.Sprintf("text://%v/reproxy_log.txt", c.rbeLogDir())
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400991}
992
993func (c *configImpl) rbeExecRoot() string {
994 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
995 if v, ok := c.environ.Get(f); ok {
996 return v
997 }
998 }
999 wd, err := os.Getwd()
1000 if err != nil {
1001 return ""
1002 }
1003 return wd
1004}
1005
1006func (c *configImpl) rbeDir() string {
1007 if v, ok := c.environ.Get("RBE_DIR"); ok {
1008 return v
1009 }
1010 return "prebuilts/remoteexecution-client/live/"
1011}
1012
1013func (c *configImpl) rbeReproxy() string {
1014 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1015 if v, ok := c.environ.Get(f); ok {
1016 return v
1017 }
1018 }
1019 return filepath.Join(c.rbeDir(), "reproxy")
1020}
1021
1022func (c *configImpl) rbeAuth() (string, string) {
1023 credFlags := []string{"use_application_default_credentials", "use_gce_credentials", "credential_file"}
1024 for _, cf := range credFlags {
1025 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1026 if v, ok := c.environ.Get(f); ok {
1027 v = strings.TrimSpace(v)
1028 if v != "" && v != "false" && v != "0" {
1029 return "RBE_" + cf, v
1030 }
1031 }
1032 }
1033 }
1034 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001035}
1036
Colin Cross9016b912019-11-11 14:57:42 -08001037func (c *configImpl) UseRemoteBuild() bool {
1038 return c.UseGoma() || c.UseRBE()
1039}
1040
Dan Willemsen1e704462016-08-21 15:17:17 -07001041// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001042// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001043// still limited by Parallel()
1044func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001045 if !c.UseRemoteBuild() {
1046 return 0
1047 }
1048 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1049 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001050 }
1051 return 500
1052}
1053
1054func (c *configImpl) SetKatiArgs(args []string) {
1055 c.katiArgs = args
1056}
1057
1058func (c *configImpl) SetNinjaArgs(args []string) {
1059 c.ninjaArgs = args
1060}
1061
1062func (c *configImpl) SetKatiSuffix(suffix string) {
1063 c.katiSuffix = suffix
1064}
1065
Dan Willemsene0879fc2017-08-04 15:06:27 -07001066func (c *configImpl) LastKatiSuffixFile() string {
1067 return filepath.Join(c.OutDir(), "last_kati_suffix")
1068}
1069
1070func (c *configImpl) HasKatiSuffix() bool {
1071 return c.katiSuffix != ""
1072}
1073
Dan Willemsen1e704462016-08-21 15:17:17 -07001074func (c *configImpl) KatiEnvFile() string {
1075 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1076}
1077
Dan Willemsen29971232018-09-26 14:58:30 -07001078func (c *configImpl) KatiBuildNinjaFile() string {
1079 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001080}
1081
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001082func (c *configImpl) KatiPackageNinjaFile() string {
1083 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1084}
1085
Dan Willemsen1e704462016-08-21 15:17:17 -07001086func (c *configImpl) SoongNinjaFile() string {
1087 return filepath.Join(c.SoongOutDir(), "build.ninja")
1088}
1089
1090func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001091 if c.katiSuffix == "" {
1092 return filepath.Join(c.OutDir(), "combined.ninja")
1093 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001094 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1095}
1096
1097func (c *configImpl) SoongAndroidMk() string {
1098 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1099}
1100
1101func (c *configImpl) SoongMakeVarsMk() string {
1102 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1103}
1104
Dan Willemsenf052f782017-05-18 15:29:04 -07001105func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001106 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001107}
1108
Dan Willemsen02781d52017-05-12 19:28:13 -07001109func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001110 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1111}
1112
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001113func (c *configImpl) KatiPackageMkDir() string {
1114 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1115}
1116
Dan Willemsenf052f782017-05-18 15:29:04 -07001117func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001118 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001119}
1120
1121func (c *configImpl) HostOut() string {
1122 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1123}
1124
1125// This probably needs to be multi-valued, so not exporting it for now
1126func (c *configImpl) hostCrossOut() string {
1127 if runtime.GOOS == "linux" {
1128 return filepath.Join(c.hostOutRoot(), "windows-x86")
1129 } else {
1130 return ""
1131 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001132}
1133
Dan Willemsen1e704462016-08-21 15:17:17 -07001134func (c *configImpl) HostPrebuiltTag() string {
1135 if runtime.GOOS == "linux" {
1136 return "linux-x86"
1137 } else if runtime.GOOS == "darwin" {
1138 return "darwin-x86"
1139 } else {
1140 panic("Unsupported OS")
1141 }
1142}
Dan Willemsenf173d592017-04-27 14:28:00 -07001143
Dan Willemsen8122bd52017-10-12 20:20:41 -07001144func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001145 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1146 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001147 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1148 if _, err := os.Stat(asan); err == nil {
1149 return asan
1150 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001151 }
1152 }
1153 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1154}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001155
1156func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1157 c.brokenDupRules = val
1158}
1159
1160func (c *configImpl) BuildBrokenDupRules() bool {
1161 return c.brokenDupRules
1162}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001163
Dan Willemsen25e6f092019-04-09 10:22:43 -07001164func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1165 c.brokenUsesNetwork = val
1166}
1167
1168func (c *configImpl) BuildBrokenUsesNetwork() bool {
1169 return c.brokenUsesNetwork
1170}
1171
Dan Willemsene3336352020-01-02 19:10:38 -08001172func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1173 c.brokenNinjaEnvVars = val
1174}
1175
1176func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1177 return c.brokenNinjaEnvVars
1178}
1179
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001180func (c *configImpl) SetTargetDeviceDir(dir string) {
1181 c.targetDeviceDir = dir
1182}
1183
1184func (c *configImpl) TargetDeviceDir() string {
1185 return c.targetDeviceDir
1186}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001187
Patrice Arruda219eef32020-06-01 17:29:30 +00001188func (c *configImpl) BuildDateTime() string {
1189 return c.buildDateTime
1190}
1191
1192func (c *configImpl) MetricsUploaderApp() string {
1193 if p, ok := c.environ.Get("ANDROID_ENABLE_METRICS_UPLOAD"); ok {
1194 return p
1195 }
1196 return ""
1197}
Patrice Arruda83842d72020-12-08 19:42:08 +00001198
1199// LogsDir returns the logs directory where build log and metrics
1200// files are located. By default, the logs directory is the out
1201// directory. If the argument dist is specified, the logs directory
1202// is <dist_dir>/logs.
1203func (c *configImpl) LogsDir() string {
1204 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001205 // Always write logs to the real dist dir, even if Bazel is using a rigged dist dir for other files
1206 return filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001207 }
1208 return c.OutDir()
1209}
1210
1211// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1212// where the bazel profiles are located.
1213func (c *configImpl) BazelMetricsDir() string {
1214 return filepath.Join(c.LogsDir(), "bazel_metrics")
1215}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001216
1217func (c *configImpl) SetEmptyNinjaFile(v bool) {
1218 c.emptyNinjaFile = v
1219}
1220
1221func (c *configImpl) EmptyNinjaFile() bool {
1222 return c.emptyNinjaFile
1223}