blob: 918a956b8693d08e39416e9b878ae091483cee9d [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
Dan Willemsen4591b642021-05-24 14:24:12 -070028 "google.golang.org/protobuf/proto"
Patrice Arruda96850362020-08-11 20:41:11 +000029
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
Spandan Das05063612021-06-25 01:39:04 +0000164 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
165 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
166 }
167
Dan Willemsen1e704462016-08-21 15:17:17 -0700168 ret.environ.Unset(
169 // We're already using it
170 "USE_SOONG_UI",
171
172 // We should never use GOROOT/GOPATH from the shell environment
173 "GOROOT",
174 "GOPATH",
175
176 // These should only come from Soong, not the environment.
177 "CLANG",
178 "CLANG_CXX",
179 "CCC_CC",
180 "CCC_CXX",
181
182 // Used by the goma compiler wrapper, but should only be set by
183 // gomacc
184 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800185
186 // We handle this above
187 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700188
Dan Willemsen2d31a442018-10-20 21:33:41 -0700189 // This is handled above too, and set for individual commands later
190 "DIST_DIR",
191
Dan Willemsen68a09852017-04-18 13:56:57 -0700192 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000193 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700194 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700195 "DISPLAY",
196 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700197 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700198 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700199
200 // Drop make flags
201 "MAKEFLAGS",
202 "MAKELEVEL",
203 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700204
205 // Set in envsetup.sh, reset in makefiles
206 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700207
208 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
209 "ANDROID_BUILD_TOP",
210 "ANDROID_HOST_OUT",
211 "ANDROID_PRODUCT_OUT",
212 "ANDROID_HOST_OUT_TESTCASES",
213 "ANDROID_TARGET_OUT_TESTCASES",
214 "ANDROID_TOOLCHAIN",
215 "ANDROID_TOOLCHAIN_2ND_ARCH",
216 "ANDROID_DEV_SCRIPTS",
217 "ANDROID_EMULATOR_PREBUILTS",
218 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700219 )
220
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400221 if ret.UseGoma() || ret.ForceUseGoma() {
222 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
223 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400224 }
225
Dan Willemsen1e704462016-08-21 15:17:17 -0700226 // Tell python not to spam the source tree with .pyc files.
227 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
228
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400229 tmpDir := absPath(ctx, ret.TempDir())
230 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800231
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700232 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
233 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
234 "llvm-binutils-stable/llvm-symbolizer")
235 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
236
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800237 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700238 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800239
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700240 if srcDir := absPath(ctx, "."); strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700241 ctx.Println("You are building in a directory whose absolute path contains a space character:")
242 ctx.Println()
243 ctx.Printf("%q\n", srcDir)
244 ctx.Println()
245 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700246 }
247
248 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700249 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
250 ctx.Println()
251 ctx.Printf("%q\n", outDir)
252 ctx.Println()
253 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700254 }
255
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000256 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700257 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
258 ctx.Println()
259 ctx.Printf("%q\n", distDir)
260 ctx.Println()
261 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700262 }
263
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700264 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000265 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
266 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100267 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700268 javaHome := func() string {
269 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
270 return override
271 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000272 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
273 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 +0100274 }
Pete Gillinabbcdda2019-10-28 16:15:33 +0000275 return java11Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700276 }()
277 absJavaHome := absPath(ctx, javaHome)
278
Dan Willemsened869522018-01-08 14:58:46 -0800279 ret.configureLocale(ctx)
280
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700281 newPath := []string{filepath.Join(absJavaHome, "bin")}
282 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
283 newPath = append(newPath, path)
284 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100285
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700286 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
287 ret.environ.Set("JAVA_HOME", absJavaHome)
288 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000289 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
290 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100291 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700292 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
293
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800294 outDir := ret.OutDir()
295 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800296 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800297 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800298 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800299 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800300 }
Colin Cross28f527c2019-11-26 16:19:04 -0800301
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800302 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
303
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400304 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400305 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400306 ret.environ.Set(k, v)
307 }
308 }
309
Patrice Arruda83842d72020-12-08 19:42:08 +0000310 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800311 if err := os.RemoveAll(bpd); err != nil {
312 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
313 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000314
315 ret.useBazel = ret.environ.IsEnvTrue("USE_BAZEL")
316
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800317 if ret.UseBazel() {
318 if err := os.MkdirAll(bpd, 0777); err != nil {
319 ctx.Fatalf("Failed to create bazel profile directory %q: %v", bpd, err)
320 }
321 }
322
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000323 if ret.UseBazel() {
324 ret.riggedDistDirForBazel = filepath.Join(ret.OutDir(), "dist")
325 } else {
326 // Not rigged
327 ret.riggedDistDirForBazel = ret.distDir
328 }
329
Patrice Arruda96850362020-08-11 20:41:11 +0000330 c := Config{ret}
331 storeConfigMetrics(ctx, c)
332 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700333}
334
Patrice Arruda13848222019-04-22 17:12:02 -0700335// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
336// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700337func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
338 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700339}
340
Patrice Arruda96850362020-08-11 20:41:11 +0000341// storeConfigMetrics selects a set of configuration information and store in
342// the metrics system for further analysis.
343func storeConfigMetrics(ctx Context, config Config) {
344 if ctx.Metrics == nil {
345 return
346 }
347
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400348 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000349
350 s := &smpb.SystemResourceInfo{
351 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
352 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
353 }
354 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000355}
356
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400357func buildConfig(config Config) *smpb.BuildConfig {
358 return &smpb.BuildConfig{
359 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
360 UseGoma: proto.Bool(config.UseGoma()),
361 UseRbe: proto.Bool(config.UseRBE()),
362 BazelAsNinja: proto.Bool(config.UseBazel()),
363 BazelMixedBuild: proto.Bool(config.bazelBuildMode() == mixedBuild),
364 }
365}
366
Patrice Arruda13848222019-04-22 17:12:02 -0700367// getConfigArgs processes the command arguments based on the build action and creates a set of new
368// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700369func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700370 // The next block of code verifies that the current directory is the root directory of the source
371 // tree. It then finds the relative path of dir based on the root directory of the source tree
372 // and verify that dir is inside of the source tree.
373 checkTopDir(ctx)
374 topDir, err := os.Getwd()
375 if err != nil {
376 ctx.Fatalf("Error retrieving top directory: %v", err)
377 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700378 dir, err = filepath.EvalSymlinks(dir)
379 if err != nil {
380 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
381 }
Patrice Arruda13848222019-04-22 17:12:02 -0700382 dir, err = filepath.Abs(dir)
383 if err != nil {
384 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
385 }
386 relDir, err := filepath.Rel(topDir, dir)
387 if err != nil {
388 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
389 }
390 // If there are ".." in the path, it's not in the source tree.
391 if strings.Contains(relDir, "..") {
392 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
393 }
394
395 configArgs := args[:]
396
397 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
398 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
399 targetNamePrefix := "MODULES-IN-"
400 if inList("GET-INSTALL-PATH", configArgs) {
401 targetNamePrefix = "GET-INSTALL-PATH-IN-"
402 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
403 }
404
Patrice Arruda13848222019-04-22 17:12:02 -0700405 var targets []string
406
407 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700408 case BUILD_MODULES:
409 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700410 case BUILD_MODULES_IN_A_DIRECTORY:
411 // If dir is the root source tree, all the modules are built of the source tree are built so
412 // no need to find the build file.
413 if topDir == dir {
414 break
415 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700416
Patrice Arruda13848222019-04-22 17:12:02 -0700417 buildFile := findBuildFile(ctx, relDir)
418 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700419 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700420 }
Patrice Arruda13848222019-04-22 17:12:02 -0700421 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
422 case BUILD_MODULES_IN_DIRECTORIES:
423 newConfigArgs, dirs := splitArgs(configArgs)
424 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700425 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700426 }
427
428 // Tidy only override all other specified targets.
429 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
430 if tidyOnly == "true" || tidyOnly == "1" {
431 configArgs = append(configArgs, "tidy_only")
432 } else {
433 configArgs = append(configArgs, targets...)
434 }
435
436 return configArgs
437}
438
439// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
440func convertToTarget(dir string, targetNamePrefix string) string {
441 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
442}
443
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700444// hasBuildFile returns true if dir contains an Android build file.
445func hasBuildFile(ctx Context, dir string) bool {
446 for _, buildFile := range buildFiles {
447 _, err := os.Stat(filepath.Join(dir, buildFile))
448 if err == nil {
449 return true
450 }
451 if !os.IsNotExist(err) {
452 ctx.Fatalf("Error retrieving the build file stats: %v", err)
453 }
454 }
455 return false
456}
457
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700458// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
459// in the current and any sub directory of dir. If a build file is not found, traverse the path
460// up by one directory and repeat again until either a build file is found or reached to the root
461// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
462// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700463func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700464 // If the string is empty or ".", assume it is top directory of the source tree.
465 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700466 return ""
467 }
468
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700469 found := false
470 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
471 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
472 if err != nil {
473 return err
474 }
475 if found {
476 return filepath.SkipDir
477 }
478 if info.IsDir() {
479 return nil
480 }
481 for _, buildFile := range buildFiles {
482 if info.Name() == buildFile {
483 found = true
484 return filepath.SkipDir
485 }
486 }
487 return nil
488 })
489 if err != nil {
490 ctx.Fatalf("Error finding Android build file: %v", err)
491 }
492
493 if found {
494 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700495 }
496 }
497
498 return ""
499}
500
501// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
502func splitArgs(args []string) (newArgs []string, dirs []string) {
503 specialArgs := map[string]bool{
504 "showcommands": true,
505 "snod": true,
506 "dist": true,
507 "checkbuild": true,
508 }
509
510 newArgs = []string{}
511 dirs = []string{}
512
513 for _, arg := range args {
514 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
515 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
516 newArgs = append(newArgs, arg)
517 continue
518 }
519
520 if _, ok := specialArgs[arg]; ok {
521 newArgs = append(newArgs, arg)
522 continue
523 }
524
525 dirs = append(dirs, arg)
526 }
527
528 return newArgs, dirs
529}
530
531// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
532// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
533// source root tree where the build action command was invoked. Each directory is validated if the
534// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700535func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700536 for _, dir := range dirs {
537 // The directory may have specified specific modules to build. ":" is the separator to separate
538 // the directory and the list of modules.
539 s := strings.Split(dir, ":")
540 l := len(s)
541 if l > 2 { // more than one ":" was specified.
542 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
543 }
544
545 dir = filepath.Join(relDir, s[0])
546 if _, err := os.Stat(dir); err != nil {
547 ctx.Fatalf("couldn't find directory %s", dir)
548 }
549
550 // Verify that if there are any targets specified after ":". Each target is separated by ",".
551 var newTargets []string
552 if l == 2 && s[1] != "" {
553 newTargets = strings.Split(s[1], ",")
554 if inList("", newTargets) {
555 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
556 }
557 }
558
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700559 // If there are specified targets to build in dir, an android build file must exist for the one
560 // shot build. For the non-targets case, find the appropriate build file and build all the
561 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700562 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700563 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700564 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
565 }
566 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700567 buildFile := findBuildFile(ctx, dir)
568 if buildFile == "" {
569 ctx.Fatalf("Build file not found for %s directory", dir)
570 }
571 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700572 }
573
Patrice Arruda13848222019-04-22 17:12:02 -0700574 targets = append(targets, newTargets...)
575 }
576
Dan Willemsence41e942019-07-29 23:39:30 -0700577 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700578}
579
Dan Willemsen9b587492017-07-10 22:13:00 -0700580func (c *configImpl) parseArgs(ctx Context, args []string) {
581 for i := 0; i < len(args); i++ {
582 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100583 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700584 c.verbose = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100585 } else if arg == "--skip-ninja" {
586 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700587 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700588 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
589 // but it does run a Kati ninja file if the .kati_enabled marker file was created
590 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000591 c.skipConfig = true
592 c.skipKati = true
593 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100594 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000595 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100596 } else if arg == "--soong-only" {
597 c.skipKati = true
598 c.skipKatiNinja = true
Colin Cross30e444b2021-06-18 11:26:19 -0700599 } else if arg == "--skip-config" {
600 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700601 } else if arg == "--skip-soong-tests" {
602 c.skipSoongTests = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700603 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700604 parseArgNum := func(def int) int {
605 if len(arg) > 2 {
606 p, err := strconv.ParseUint(arg[2:], 10, 31)
607 if err != nil {
608 ctx.Fatalf("Failed to parse %q: %v", arg, err)
609 }
610 return int(p)
611 } else if i+1 < len(args) {
612 p, err := strconv.ParseUint(args[i+1], 10, 31)
613 if err == nil {
614 i++
615 return int(p)
616 }
617 }
618 return def
619 }
620
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700621 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700622 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700623 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700624 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700625 } else {
626 ctx.Fatalln("Unknown option:", arg)
627 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700628 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700629 if k == "OUT_DIR" {
630 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
631 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700632 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700633 } else if arg == "dist" {
634 c.dist = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700635 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700636 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800637 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700638 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700639 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700640 }
641 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700642}
643
Dan Willemsened869522018-01-08 14:58:46 -0800644func (c *configImpl) configureLocale(ctx Context) {
645 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
646 output, err := cmd.Output()
647
648 var locales []string
649 if err == nil {
650 locales = strings.Split(string(output), "\n")
651 } else {
652 // If we're unable to list the locales, let's assume en_US.UTF-8
653 locales = []string{"en_US.UTF-8"}
654 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
655 }
656
657 // gettext uses LANGUAGE, which is passed directly through
658
659 // For LANG and LC_*, only preserve the evaluated version of
660 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800661 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800662 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800663 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800664 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800665 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800666 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800667 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800668 }
669
670 c.environ.UnsetWithPrefix("LC_")
671
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800672 if userLang != "" {
673 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800674 }
675
676 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
677 // for others)
678 if inList("C.UTF-8", locales) {
679 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500680 } else if inList("C.utf8", locales) {
681 // These normalize to the same thing
682 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800683 } else if inList("en_US.UTF-8", locales) {
684 c.environ.Set("LANG", "en_US.UTF-8")
685 } else if inList("en_US.utf8", locales) {
686 // These normalize to the same thing
687 c.environ.Set("LANG", "en_US.UTF-8")
688 } else {
689 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
690 }
691}
692
Dan Willemsen1e704462016-08-21 15:17:17 -0700693// Lunch configures the environment for a specific product similarly to the
694// `lunch` bash function.
695func (c *configImpl) Lunch(ctx Context, product, variant string) {
696 if variant != "eng" && variant != "userdebug" && variant != "user" {
697 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
698 }
699
700 c.environ.Set("TARGET_PRODUCT", product)
701 c.environ.Set("TARGET_BUILD_VARIANT", variant)
702 c.environ.Set("TARGET_BUILD_TYPE", "release")
703 c.environ.Unset("TARGET_BUILD_APPS")
Martin Stjernholm08802332020-06-04 17:00:01 +0100704 c.environ.Unset("TARGET_BUILD_UNBUNDLED")
Dan Willemsen1e704462016-08-21 15:17:17 -0700705}
706
707// Tapas configures the environment to build one or more unbundled apps,
708// similarly to the `tapas` bash function.
709func (c *configImpl) Tapas(ctx Context, apps []string, arch, variant string) {
710 if len(apps) == 0 {
711 apps = []string{"all"}
712 }
713 if variant == "" {
714 variant = "eng"
715 }
716
717 if variant != "eng" && variant != "userdebug" && variant != "user" {
718 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
719 }
720
721 var product string
722 switch arch {
Dan Willemsen1e704462016-08-21 15:17:17 -0700723 case "arm", "":
724 product = "aosp_arm"
725 case "arm64":
726 product = "aosm_arm64"
Dan Willemsen1e704462016-08-21 15:17:17 -0700727 case "x86":
728 product = "aosp_x86"
729 case "x86_64":
730 product = "aosp_x86_64"
731 default:
732 ctx.Fatalf("Invalid architecture: %q", arch)
733 }
734
735 c.environ.Set("TARGET_PRODUCT", product)
736 c.environ.Set("TARGET_BUILD_VARIANT", variant)
737 c.environ.Set("TARGET_BUILD_TYPE", "release")
738 c.environ.Set("TARGET_BUILD_APPS", strings.Join(apps, " "))
739}
740
741func (c *configImpl) Environment() *Environment {
742 return c.environ
743}
744
745func (c *configImpl) Arguments() []string {
746 return c.arguments
747}
748
749func (c *configImpl) OutDir() string {
750 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700751 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700752 }
753 return "out"
754}
755
Dan Willemsen8a073a82017-02-04 17:30:44 -0800756func (c *configImpl) DistDir() string {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000757 if c.UseBazel() {
758 return c.riggedDistDirForBazel
759 } else {
760 return c.distDir
761 }
762}
763
764func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700765 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800766}
767
Dan Willemsen1e704462016-08-21 15:17:17 -0700768func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000769 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700770 return c.arguments
771 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700772 return c.ninjaArgs
773}
774
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500775func (c *configImpl) BazelOutDir() string {
776 return filepath.Join(c.OutDir(), "bazel")
777}
778
Dan Willemsen1e704462016-08-21 15:17:17 -0700779func (c *configImpl) SoongOutDir() string {
780 return filepath.Join(c.OutDir(), "soong")
781}
782
Jeff Gastonefc1b412017-03-29 17:29:06 -0700783func (c *configImpl) TempDir() string {
784 return shared.TempDirForOutDir(c.SoongOutDir())
785}
786
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700787func (c *configImpl) FileListDir() string {
788 return filepath.Join(c.OutDir(), ".module_paths")
789}
790
Dan Willemsen1e704462016-08-21 15:17:17 -0700791func (c *configImpl) KatiSuffix() string {
792 if c.katiSuffix != "" {
793 return c.katiSuffix
794 }
795 panic("SetKatiSuffix has not been called")
796}
797
Colin Cross37193492017-11-16 17:55:00 -0800798// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
799// user is interested in additional checks at the expense of build time.
800func (c *configImpl) Checkbuild() bool {
801 return c.checkbuild
802}
803
Dan Willemsen8a073a82017-02-04 17:30:44 -0800804func (c *configImpl) Dist() bool {
805 return c.dist
806}
807
Dan Willemsen1e704462016-08-21 15:17:17 -0700808func (c *configImpl) IsVerbose() bool {
809 return c.verbose
810}
811
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000812func (c *configImpl) SkipKati() bool {
813 return c.skipKati
814}
815
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100816func (c *configImpl) SkipKatiNinja() bool {
817 return c.skipKatiNinja
818}
819
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100820func (c *configImpl) SkipNinja() bool {
821 return c.skipNinja
822}
823
Anton Hansson5a7861a2021-06-04 10:09:01 +0100824func (c *configImpl) SetSkipNinja(v bool) {
825 c.skipNinja = v
826}
827
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000828func (c *configImpl) SkipConfig() bool {
829 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -0700830}
831
Dan Willemsen1e704462016-08-21 15:17:17 -0700832func (c *configImpl) TargetProduct() string {
833 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
834 return v
835 }
836 panic("TARGET_PRODUCT is not defined")
837}
838
Dan Willemsen02781d52017-05-12 19:28:13 -0700839func (c *configImpl) TargetDevice() string {
840 return c.targetDevice
841}
842
843func (c *configImpl) SetTargetDevice(device string) {
844 c.targetDevice = device
845}
846
847func (c *configImpl) TargetBuildVariant() string {
848 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
849 return v
850 }
851 panic("TARGET_BUILD_VARIANT is not defined")
852}
853
Dan Willemsen1e704462016-08-21 15:17:17 -0700854func (c *configImpl) KatiArgs() []string {
855 return c.katiArgs
856}
857
858func (c *configImpl) Parallel() int {
859 return c.parallel
860}
861
Colin Cross8b8bec32019-11-15 13:18:43 -0800862func (c *configImpl) HighmemParallel() int {
863 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
864 return i
865 }
866
867 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
868 parallel := c.Parallel()
869 if c.UseRemoteBuild() {
870 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
871 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
872 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
873 // Return 1/16th of the size of the local pool, rounding up.
874 return (parallel + 15) / 16
875 } else if c.totalRAM == 0 {
876 // Couldn't detect the total RAM, don't restrict highmem processes.
877 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -0700878 } else if c.totalRAM <= 16*1024*1024*1024 {
879 // Less than 16GB of ram, restrict to 1 highmem processes
880 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -0800881 } else if c.totalRAM <= 32*1024*1024*1024 {
882 // Less than 32GB of ram, restrict to 2 highmem processes
883 return 2
884 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
885 // If less than 8GB total RAM per process, reduce the number of highmem processes
886 return p
887 }
888 // No restriction on highmem processes
889 return parallel
890}
891
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800892func (c *configImpl) TotalRAM() uint64 {
893 return c.totalRAM
894}
895
Kousik Kumarec478642020-09-21 13:39:24 -0400896// ForceUseGoma determines whether we should override Goma deprecation
897// and use Goma for the current build or not.
898func (c *configImpl) ForceUseGoma() bool {
899 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
900 v = strings.TrimSpace(v)
901 if v != "" && v != "false" {
902 return true
903 }
904 }
905 return false
906}
907
Dan Willemsen1e704462016-08-21 15:17:17 -0700908func (c *configImpl) UseGoma() bool {
909 if v, ok := c.environ.Get("USE_GOMA"); ok {
910 v = strings.TrimSpace(v)
911 if v != "" && v != "false" {
912 return true
913 }
914 }
915 return false
916}
917
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +0900918func (c *configImpl) StartGoma() bool {
919 if !c.UseGoma() {
920 return false
921 }
922
923 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
924 v = strings.TrimSpace(v)
925 if v != "" && v != "false" {
926 return false
927 }
928 }
929 return true
930}
931
Ramy Medhatbbf25672019-07-17 12:30:04 +0000932func (c *configImpl) UseRBE() bool {
933 if v, ok := c.environ.Get("USE_RBE"); ok {
934 v = strings.TrimSpace(v)
935 if v != "" && v != "false" {
936 return true
937 }
938 }
939 return false
940}
941
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800942func (c *configImpl) UseBazel() bool {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000943 return c.useBazel
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800944}
945
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400946func (c *configImpl) bazelBuildMode() bazelBuildMode {
947 if c.Environment().IsEnvTrue("USE_BAZEL_ANALYSIS") {
948 return mixedBuild
949 } else if c.Environment().IsEnvTrue("GENERATE_BAZEL_FILES") {
950 return generateBuildFiles
Jingwen Chendd9725c2021-06-24 08:41:16 +0000951 } else if v, ok := c.Environment().Get("SOONG_DUMP_JSON_MODULE_GRAPH"); ok && v != "" {
952 return generateJsonModuleGraph
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400953 } else {
954 return noBazel
955 }
956}
957
Ramy Medhatbbf25672019-07-17 12:30:04 +0000958func (c *configImpl) StartRBE() bool {
959 if !c.UseRBE() {
960 return false
961 }
962
963 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
964 v = strings.TrimSpace(v)
965 if v != "" && v != "false" {
966 return false
967 }
968 }
969 return true
970}
971
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000972func (c *configImpl) rbeLogDir() string {
Kousik Kumar0d15a722020-09-23 02:54:11 -0400973 for _, f := range []string{"RBE_log_dir", "FLAG_log_dir"} {
974 if v, ok := c.environ.Get(f); ok {
975 return v
976 }
977 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400978 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000979 return c.LogsDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400980 }
981 return c.OutDir()
982}
983
984func (c *configImpl) rbeStatsOutputDir() string {
Patrice Arruda62f1bf22020-07-07 12:48:26 +0000985 for _, f := range []string{"RBE_output_dir", "FLAG_output_dir"} {
986 if v, ok := c.environ.Get(f); ok {
987 return v
988 }
989 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000990 return c.rbeLogDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400991}
992
993func (c *configImpl) rbeLogPath() string {
994 for _, f := range []string{"RBE_log_path", "FLAG_log_path"} {
995 if v, ok := c.environ.Get(f); ok {
996 return v
997 }
998 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000999 return fmt.Sprintf("text://%v/reproxy_log.txt", c.rbeLogDir())
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001000}
1001
1002func (c *configImpl) rbeExecRoot() string {
1003 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1004 if v, ok := c.environ.Get(f); ok {
1005 return v
1006 }
1007 }
1008 wd, err := os.Getwd()
1009 if err != nil {
1010 return ""
1011 }
1012 return wd
1013}
1014
1015func (c *configImpl) rbeDir() string {
1016 if v, ok := c.environ.Get("RBE_DIR"); ok {
1017 return v
1018 }
1019 return "prebuilts/remoteexecution-client/live/"
1020}
1021
1022func (c *configImpl) rbeReproxy() string {
1023 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1024 if v, ok := c.environ.Get(f); ok {
1025 return v
1026 }
1027 }
1028 return filepath.Join(c.rbeDir(), "reproxy")
1029}
1030
1031func (c *configImpl) rbeAuth() (string, string) {
1032 credFlags := []string{"use_application_default_credentials", "use_gce_credentials", "credential_file"}
1033 for _, cf := range credFlags {
1034 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1035 if v, ok := c.environ.Get(f); ok {
1036 v = strings.TrimSpace(v)
1037 if v != "" && v != "false" && v != "0" {
1038 return "RBE_" + cf, v
1039 }
1040 }
1041 }
1042 }
1043 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001044}
1045
Colin Cross9016b912019-11-11 14:57:42 -08001046func (c *configImpl) UseRemoteBuild() bool {
1047 return c.UseGoma() || c.UseRBE()
1048}
1049
Dan Willemsen1e704462016-08-21 15:17:17 -07001050// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001051// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001052// still limited by Parallel()
1053func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001054 if !c.UseRemoteBuild() {
1055 return 0
1056 }
1057 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1058 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001059 }
1060 return 500
1061}
1062
1063func (c *configImpl) SetKatiArgs(args []string) {
1064 c.katiArgs = args
1065}
1066
1067func (c *configImpl) SetNinjaArgs(args []string) {
1068 c.ninjaArgs = args
1069}
1070
1071func (c *configImpl) SetKatiSuffix(suffix string) {
1072 c.katiSuffix = suffix
1073}
1074
Dan Willemsene0879fc2017-08-04 15:06:27 -07001075func (c *configImpl) LastKatiSuffixFile() string {
1076 return filepath.Join(c.OutDir(), "last_kati_suffix")
1077}
1078
1079func (c *configImpl) HasKatiSuffix() bool {
1080 return c.katiSuffix != ""
1081}
1082
Dan Willemsen1e704462016-08-21 15:17:17 -07001083func (c *configImpl) KatiEnvFile() string {
1084 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1085}
1086
Dan Willemsen29971232018-09-26 14:58:30 -07001087func (c *configImpl) KatiBuildNinjaFile() string {
1088 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001089}
1090
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001091func (c *configImpl) KatiPackageNinjaFile() string {
1092 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1093}
1094
Dan Willemsen1e704462016-08-21 15:17:17 -07001095func (c *configImpl) SoongNinjaFile() string {
1096 return filepath.Join(c.SoongOutDir(), "build.ninja")
1097}
1098
1099func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001100 if c.katiSuffix == "" {
1101 return filepath.Join(c.OutDir(), "combined.ninja")
1102 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001103 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1104}
1105
1106func (c *configImpl) SoongAndroidMk() string {
1107 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1108}
1109
1110func (c *configImpl) SoongMakeVarsMk() string {
1111 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1112}
1113
Dan Willemsenf052f782017-05-18 15:29:04 -07001114func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001115 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001116}
1117
Dan Willemsen02781d52017-05-12 19:28:13 -07001118func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001119 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1120}
1121
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001122func (c *configImpl) KatiPackageMkDir() string {
1123 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1124}
1125
Dan Willemsenf052f782017-05-18 15:29:04 -07001126func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001127 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001128}
1129
1130func (c *configImpl) HostOut() string {
1131 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1132}
1133
1134// This probably needs to be multi-valued, so not exporting it for now
1135func (c *configImpl) hostCrossOut() string {
1136 if runtime.GOOS == "linux" {
1137 return filepath.Join(c.hostOutRoot(), "windows-x86")
1138 } else {
1139 return ""
1140 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001141}
1142
Dan Willemsen1e704462016-08-21 15:17:17 -07001143func (c *configImpl) HostPrebuiltTag() string {
1144 if runtime.GOOS == "linux" {
1145 return "linux-x86"
1146 } else if runtime.GOOS == "darwin" {
1147 return "darwin-x86"
1148 } else {
1149 panic("Unsupported OS")
1150 }
1151}
Dan Willemsenf173d592017-04-27 14:28:00 -07001152
Dan Willemsen8122bd52017-10-12 20:20:41 -07001153func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001154 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1155 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001156 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1157 if _, err := os.Stat(asan); err == nil {
1158 return asan
1159 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001160 }
1161 }
1162 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1163}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001164
1165func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1166 c.brokenDupRules = val
1167}
1168
1169func (c *configImpl) BuildBrokenDupRules() bool {
1170 return c.brokenDupRules
1171}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001172
Dan Willemsen25e6f092019-04-09 10:22:43 -07001173func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1174 c.brokenUsesNetwork = val
1175}
1176
1177func (c *configImpl) BuildBrokenUsesNetwork() bool {
1178 return c.brokenUsesNetwork
1179}
1180
Dan Willemsene3336352020-01-02 19:10:38 -08001181func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1182 c.brokenNinjaEnvVars = val
1183}
1184
1185func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1186 return c.brokenNinjaEnvVars
1187}
1188
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001189func (c *configImpl) SetTargetDeviceDir(dir string) {
1190 c.targetDeviceDir = dir
1191}
1192
1193func (c *configImpl) TargetDeviceDir() string {
1194 return c.targetDeviceDir
1195}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001196
Patrice Arruda219eef32020-06-01 17:29:30 +00001197func (c *configImpl) BuildDateTime() string {
1198 return c.buildDateTime
1199}
1200
1201func (c *configImpl) MetricsUploaderApp() string {
1202 if p, ok := c.environ.Get("ANDROID_ENABLE_METRICS_UPLOAD"); ok {
1203 return p
1204 }
1205 return ""
1206}
Patrice Arruda83842d72020-12-08 19:42:08 +00001207
1208// LogsDir returns the logs directory where build log and metrics
1209// files are located. By default, the logs directory is the out
1210// directory. If the argument dist is specified, the logs directory
1211// is <dist_dir>/logs.
1212func (c *configImpl) LogsDir() string {
1213 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001214 // Always write logs to the real dist dir, even if Bazel is using a rigged dist dir for other files
1215 return filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001216 }
1217 return c.OutDir()
1218}
1219
1220// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1221// where the bazel profiles are located.
1222func (c *configImpl) BazelMetricsDir() string {
1223 return filepath.Join(c.LogsDir(), "bazel_metrics")
1224}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001225
1226func (c *configImpl) SetEmptyNinjaFile(v bool) {
1227 c.emptyNinjaFile = v
1228}
1229
1230func (c *configImpl) EmptyNinjaFile() bool {
1231 return c.emptyNinjaFile
1232}