blob: 35dacf2b81cd29d70de8b5d597ae1d20bd704fc3 [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 {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020036 // Some targets that are implemented in soong_build
37 // (bp2build, json-module-graph) are not here and have their own bits below.
Colin Cross28f527c2019-11-26 16:19:04 -080038 arguments []string
39 goma bool
40 environ *Environment
41 distDir string
42 buildDateTime string
Dan Willemsen1e704462016-08-21 15:17:17 -070043
44 // From the arguments
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020045 parallel int
46 keepGoing int
47 verbose bool
48 checkbuild bool
49 dist bool
50 jsonModuleGraph bool
51 bp2build bool
Lukacs T. Berki3a821692021-09-06 17:08:02 +020052 queryview bool
Lukacs T. Berkic6012f32021-09-06 18:31:46 +020053 soongDocs bool
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020054 skipConfig bool
55 skipKati bool
56 skipKatiNinja bool
57 skipSoong bool
58 skipNinja bool
59 skipSoongTests bool
Dan Willemsen1e704462016-08-21 15:17:17 -070060
61 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070062 katiArgs []string
63 ninjaArgs []string
64 katiSuffix string
65 targetDevice string
66 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +000067 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -070068
Dan Willemsen2bb82d02019-12-27 09:35:42 -080069 // Autodetected
70 totalRAM uint64
71
Dan Willemsene3336352020-01-02 19:10:38 -080072 brokenDupRules bool
73 brokenUsesNetwork bool
74 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -070075
76 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +000077
78 useBazel bool
79
80 // During Bazel execution, Bazel cannot write outside OUT_DIR.
81 // 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.
82 riggedDistDirForBazel string
Colin Crossf3bdbcb2021-06-01 11:43:55 -070083
84 // Set by multiproduct_kati
85 emptyNinjaFile bool
Dan Willemsen1e704462016-08-21 15:17:17 -070086}
87
Dan Willemsenc2af0be2017-01-20 14:10:01 -080088const srcDirFileCheck = "build/soong/root.bp"
89
Patrice Arruda9450d0b2019-07-08 11:06:46 -070090var buildFiles = []string{"Android.mk", "Android.bp"}
91
Patrice Arruda13848222019-04-22 17:12:02 -070092type BuildAction uint
93
94const (
95 // Builds all of the modules and their dependencies of a specified directory, relative to the root
96 // directory of the source tree.
97 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
98
99 // Builds all of the modules and their dependencies of a list of specified directories. All specified
100 // directories are relative to the root directory of the source tree.
101 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700102
103 // Build a list of specified modules. If none was specified, simply build the whole source tree.
104 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700105)
106
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400107type bazelBuildMode int
108
109// Bazel-related build modes.
110const (
111 // Don't use bazel at all.
112 noBazel bazelBuildMode = iota
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. Berkicef87b62021-08-10 15:01:13 +0200585 } else if arg == "--empty-ninja-file" {
586 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100587 } else if arg == "--skip-ninja" {
588 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700589 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700590 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
591 // but it does run a Kati ninja file if the .kati_enabled marker file was created
592 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000593 c.skipConfig = true
594 c.skipKati = true
595 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100596 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000597 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100598 } else if arg == "--soong-only" {
599 c.skipKati = true
600 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200601 } else if arg == "--config-only" {
602 c.skipKati = true
603 c.skipKatiNinja = true
604 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700605 } else if arg == "--skip-config" {
606 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700607 } else if arg == "--skip-soong-tests" {
608 c.skipSoongTests = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700609 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700610 parseArgNum := func(def int) int {
611 if len(arg) > 2 {
612 p, err := strconv.ParseUint(arg[2:], 10, 31)
613 if err != nil {
614 ctx.Fatalf("Failed to parse %q: %v", arg, err)
615 }
616 return int(p)
617 } else if i+1 < len(args) {
618 p, err := strconv.ParseUint(args[i+1], 10, 31)
619 if err == nil {
620 i++
621 return int(p)
622 }
623 }
624 return def
625 }
626
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700627 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700628 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700629 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700630 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700631 } else {
632 ctx.Fatalln("Unknown option:", arg)
633 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700634 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700635 if k == "OUT_DIR" {
636 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
637 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700638 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700639 } else if arg == "dist" {
640 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200641 } else if arg == "json-module-graph" {
642 c.jsonModuleGraph = true
643 } else if arg == "bp2build" {
644 c.bp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200645 } else if arg == "queryview" {
646 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200647 } else if arg == "soong_docs" {
648 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700649 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700650 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800651 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700652 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700653 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700654 }
655 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700656}
657
Dan Willemsened869522018-01-08 14:58:46 -0800658func (c *configImpl) configureLocale(ctx Context) {
659 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
660 output, err := cmd.Output()
661
662 var locales []string
663 if err == nil {
664 locales = strings.Split(string(output), "\n")
665 } else {
666 // If we're unable to list the locales, let's assume en_US.UTF-8
667 locales = []string{"en_US.UTF-8"}
668 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
669 }
670
671 // gettext uses LANGUAGE, which is passed directly through
672
673 // For LANG and LC_*, only preserve the evaluated version of
674 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800675 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800676 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800677 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800678 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800679 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800680 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800681 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800682 }
683
684 c.environ.UnsetWithPrefix("LC_")
685
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800686 if userLang != "" {
687 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800688 }
689
690 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
691 // for others)
692 if inList("C.UTF-8", locales) {
693 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500694 } else if inList("C.utf8", locales) {
695 // These normalize to the same thing
696 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800697 } else if inList("en_US.UTF-8", locales) {
698 c.environ.Set("LANG", "en_US.UTF-8")
699 } else if inList("en_US.utf8", locales) {
700 // These normalize to the same thing
701 c.environ.Set("LANG", "en_US.UTF-8")
702 } else {
703 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
704 }
705}
706
Dan Willemsen1e704462016-08-21 15:17:17 -0700707func (c *configImpl) Environment() *Environment {
708 return c.environ
709}
710
711func (c *configImpl) Arguments() []string {
712 return c.arguments
713}
714
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200715func (c *configImpl) SoongBuildInvocationNeeded() bool {
716 if c.Dist() {
717 return true
718 }
719
720 if len(c.Arguments()) > 0 {
721 // Explicit targets requested that are not special targets like b2pbuild
722 // or the JSON module graph
723 return true
724 }
725
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200726 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200727 // Command line was empty, the default Ninja target is built
728 return true
729 }
730
731 // build.ninja doesn't need to be generated
732 return false
733}
734
Dan Willemsen1e704462016-08-21 15:17:17 -0700735func (c *configImpl) OutDir() string {
736 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700737 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700738 }
739 return "out"
740}
741
Dan Willemsen8a073a82017-02-04 17:30:44 -0800742func (c *configImpl) DistDir() string {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000743 if c.UseBazel() {
744 return c.riggedDistDirForBazel
745 } else {
746 return c.distDir
747 }
748}
749
750func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700751 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800752}
753
Dan Willemsen1e704462016-08-21 15:17:17 -0700754func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000755 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700756 return c.arguments
757 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700758 return c.ninjaArgs
759}
760
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500761func (c *configImpl) BazelOutDir() string {
762 return filepath.Join(c.OutDir(), "bazel")
763}
764
Dan Willemsen1e704462016-08-21 15:17:17 -0700765func (c *configImpl) SoongOutDir() string {
766 return filepath.Join(c.OutDir(), "soong")
767}
768
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200769func (c *configImpl) PrebuiltOS() string {
770 switch runtime.GOOS {
771 case "linux":
772 return "linux-x86"
773 case "darwin":
774 return "darwin-x86"
775 default:
776 panic("Unknown GOOS")
777 }
778}
779func (c *configImpl) HostToolDir() string {
780 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
781}
782
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200783func (c *configImpl) NamedGlobFile(name string) string {
784 return shared.JoinPath(c.SoongOutDir(), ".bootstrap/build-globs."+name+".ninja")
785}
786
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200787func (c *configImpl) UsedEnvFile(tag string) string {
788 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
789}
790
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200791func (c *configImpl) MainNinjaFile() string {
792 return shared.JoinPath(c.SoongOutDir(), "build.ninja")
793}
794
795func (c *configImpl) Bp2BuildMarkerFile() string {
796 return shared.JoinPath(c.SoongOutDir(), ".bootstrap/bp2build_workspace_marker")
797}
798
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200799func (c *configImpl) SoongDocsHtml() string {
800 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
801}
802
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200803func (c *configImpl) QueryviewMarkerFile() string {
804 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
805}
806
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200807func (c *configImpl) ModuleGraphFile() string {
808 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
809}
810
Jeff Gastonefc1b412017-03-29 17:29:06 -0700811func (c *configImpl) TempDir() string {
812 return shared.TempDirForOutDir(c.SoongOutDir())
813}
814
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700815func (c *configImpl) FileListDir() string {
816 return filepath.Join(c.OutDir(), ".module_paths")
817}
818
Dan Willemsen1e704462016-08-21 15:17:17 -0700819func (c *configImpl) KatiSuffix() string {
820 if c.katiSuffix != "" {
821 return c.katiSuffix
822 }
823 panic("SetKatiSuffix has not been called")
824}
825
Colin Cross37193492017-11-16 17:55:00 -0800826// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
827// user is interested in additional checks at the expense of build time.
828func (c *configImpl) Checkbuild() bool {
829 return c.checkbuild
830}
831
Dan Willemsen8a073a82017-02-04 17:30:44 -0800832func (c *configImpl) Dist() bool {
833 return c.dist
834}
835
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200836func (c *configImpl) JsonModuleGraph() bool {
837 return c.jsonModuleGraph
838}
839
840func (c *configImpl) Bp2Build() bool {
841 return c.bp2build
842}
843
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200844func (c *configImpl) Queryview() bool {
845 return c.queryview
846}
847
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200848func (c *configImpl) SoongDocs() bool {
849 return c.soongDocs
850}
851
Dan Willemsen1e704462016-08-21 15:17:17 -0700852func (c *configImpl) IsVerbose() bool {
853 return c.verbose
854}
855
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000856func (c *configImpl) SkipKati() bool {
857 return c.skipKati
858}
859
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100860func (c *configImpl) SkipKatiNinja() bool {
861 return c.skipKatiNinja
862}
863
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200864func (c *configImpl) SkipSoong() bool {
865 return c.skipSoong
866}
867
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100868func (c *configImpl) SkipNinja() bool {
869 return c.skipNinja
870}
871
Anton Hansson5a7861a2021-06-04 10:09:01 +0100872func (c *configImpl) SetSkipNinja(v bool) {
873 c.skipNinja = v
874}
875
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000876func (c *configImpl) SkipConfig() bool {
877 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -0700878}
879
Dan Willemsen1e704462016-08-21 15:17:17 -0700880func (c *configImpl) TargetProduct() string {
881 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
882 return v
883 }
884 panic("TARGET_PRODUCT is not defined")
885}
886
Dan Willemsen02781d52017-05-12 19:28:13 -0700887func (c *configImpl) TargetDevice() string {
888 return c.targetDevice
889}
890
891func (c *configImpl) SetTargetDevice(device string) {
892 c.targetDevice = device
893}
894
895func (c *configImpl) TargetBuildVariant() string {
896 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
897 return v
898 }
899 panic("TARGET_BUILD_VARIANT is not defined")
900}
901
Dan Willemsen1e704462016-08-21 15:17:17 -0700902func (c *configImpl) KatiArgs() []string {
903 return c.katiArgs
904}
905
906func (c *configImpl) Parallel() int {
907 return c.parallel
908}
909
Colin Cross8b8bec32019-11-15 13:18:43 -0800910func (c *configImpl) HighmemParallel() int {
911 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
912 return i
913 }
914
915 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
916 parallel := c.Parallel()
917 if c.UseRemoteBuild() {
918 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
919 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
920 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
921 // Return 1/16th of the size of the local pool, rounding up.
922 return (parallel + 15) / 16
923 } else if c.totalRAM == 0 {
924 // Couldn't detect the total RAM, don't restrict highmem processes.
925 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -0700926 } else if c.totalRAM <= 16*1024*1024*1024 {
927 // Less than 16GB of ram, restrict to 1 highmem processes
928 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -0800929 } else if c.totalRAM <= 32*1024*1024*1024 {
930 // Less than 32GB of ram, restrict to 2 highmem processes
931 return 2
932 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
933 // If less than 8GB total RAM per process, reduce the number of highmem processes
934 return p
935 }
936 // No restriction on highmem processes
937 return parallel
938}
939
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800940func (c *configImpl) TotalRAM() uint64 {
941 return c.totalRAM
942}
943
Kousik Kumarec478642020-09-21 13:39:24 -0400944// ForceUseGoma determines whether we should override Goma deprecation
945// and use Goma for the current build or not.
946func (c *configImpl) ForceUseGoma() bool {
947 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
948 v = strings.TrimSpace(v)
949 if v != "" && v != "false" {
950 return true
951 }
952 }
953 return false
954}
955
Dan Willemsen1e704462016-08-21 15:17:17 -0700956func (c *configImpl) UseGoma() bool {
957 if v, ok := c.environ.Get("USE_GOMA"); ok {
958 v = strings.TrimSpace(v)
959 if v != "" && v != "false" {
960 return true
961 }
962 }
963 return false
964}
965
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +0900966func (c *configImpl) StartGoma() bool {
967 if !c.UseGoma() {
968 return false
969 }
970
971 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
972 v = strings.TrimSpace(v)
973 if v != "" && v != "false" {
974 return false
975 }
976 }
977 return true
978}
979
Ramy Medhatbbf25672019-07-17 12:30:04 +0000980func (c *configImpl) UseRBE() bool {
981 if v, ok := c.environ.Get("USE_RBE"); ok {
982 v = strings.TrimSpace(v)
983 if v != "" && v != "false" {
984 return true
985 }
986 }
987 return false
988}
989
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800990func (c *configImpl) UseBazel() bool {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000991 return c.useBazel
Patrice Arruda0c1c4562020-11-11 13:01:25 -0800992}
993
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400994func (c *configImpl) bazelBuildMode() bazelBuildMode {
995 if c.Environment().IsEnvTrue("USE_BAZEL_ANALYSIS") {
996 return mixedBuild
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400997 } else {
998 return noBazel
999 }
1000}
1001
Ramy Medhatbbf25672019-07-17 12:30:04 +00001002func (c *configImpl) StartRBE() bool {
1003 if !c.UseRBE() {
1004 return false
1005 }
1006
1007 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1008 v = strings.TrimSpace(v)
1009 if v != "" && v != "false" {
1010 return false
1011 }
1012 }
1013 return true
1014}
1015
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001016func (c *configImpl) rbeLogDir() string {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001017 for _, f := range []string{"RBE_log_dir", "FLAG_log_dir"} {
1018 if v, ok := c.environ.Get(f); ok {
1019 return v
1020 }
1021 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001022 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001023 return c.LogsDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001024 }
1025 return c.OutDir()
1026}
1027
1028func (c *configImpl) rbeStatsOutputDir() string {
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001029 for _, f := range []string{"RBE_output_dir", "FLAG_output_dir"} {
1030 if v, ok := c.environ.Get(f); ok {
1031 return v
1032 }
1033 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001034 return c.rbeLogDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001035}
1036
1037func (c *configImpl) rbeLogPath() string {
1038 for _, f := range []string{"RBE_log_path", "FLAG_log_path"} {
1039 if v, ok := c.environ.Get(f); ok {
1040 return v
1041 }
1042 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001043 return fmt.Sprintf("text://%v/reproxy_log.txt", c.rbeLogDir())
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001044}
1045
1046func (c *configImpl) rbeExecRoot() string {
1047 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1048 if v, ok := c.environ.Get(f); ok {
1049 return v
1050 }
1051 }
1052 wd, err := os.Getwd()
1053 if err != nil {
1054 return ""
1055 }
1056 return wd
1057}
1058
1059func (c *configImpl) rbeDir() string {
1060 if v, ok := c.environ.Get("RBE_DIR"); ok {
1061 return v
1062 }
1063 return "prebuilts/remoteexecution-client/live/"
1064}
1065
1066func (c *configImpl) rbeReproxy() string {
1067 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1068 if v, ok := c.environ.Get(f); ok {
1069 return v
1070 }
1071 }
1072 return filepath.Join(c.rbeDir(), "reproxy")
1073}
1074
1075func (c *configImpl) rbeAuth() (string, string) {
1076 credFlags := []string{"use_application_default_credentials", "use_gce_credentials", "credential_file"}
1077 for _, cf := range credFlags {
1078 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1079 if v, ok := c.environ.Get(f); ok {
1080 v = strings.TrimSpace(v)
1081 if v != "" && v != "false" && v != "0" {
1082 return "RBE_" + cf, v
1083 }
1084 }
1085 }
1086 }
1087 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001088}
1089
Colin Cross9016b912019-11-11 14:57:42 -08001090func (c *configImpl) UseRemoteBuild() bool {
1091 return c.UseGoma() || c.UseRBE()
1092}
1093
Dan Willemsen1e704462016-08-21 15:17:17 -07001094// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001095// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001096// still limited by Parallel()
1097func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001098 if !c.UseRemoteBuild() {
1099 return 0
1100 }
1101 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1102 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001103 }
1104 return 500
1105}
1106
1107func (c *configImpl) SetKatiArgs(args []string) {
1108 c.katiArgs = args
1109}
1110
1111func (c *configImpl) SetNinjaArgs(args []string) {
1112 c.ninjaArgs = args
1113}
1114
1115func (c *configImpl) SetKatiSuffix(suffix string) {
1116 c.katiSuffix = suffix
1117}
1118
Dan Willemsene0879fc2017-08-04 15:06:27 -07001119func (c *configImpl) LastKatiSuffixFile() string {
1120 return filepath.Join(c.OutDir(), "last_kati_suffix")
1121}
1122
1123func (c *configImpl) HasKatiSuffix() bool {
1124 return c.katiSuffix != ""
1125}
1126
Dan Willemsen1e704462016-08-21 15:17:17 -07001127func (c *configImpl) KatiEnvFile() string {
1128 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1129}
1130
Dan Willemsen29971232018-09-26 14:58:30 -07001131func (c *configImpl) KatiBuildNinjaFile() string {
1132 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001133}
1134
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001135func (c *configImpl) KatiPackageNinjaFile() string {
1136 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1137}
1138
Dan Willemsen1e704462016-08-21 15:17:17 -07001139func (c *configImpl) SoongNinjaFile() string {
1140 return filepath.Join(c.SoongOutDir(), "build.ninja")
1141}
1142
1143func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001144 if c.katiSuffix == "" {
1145 return filepath.Join(c.OutDir(), "combined.ninja")
1146 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001147 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1148}
1149
1150func (c *configImpl) SoongAndroidMk() string {
1151 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1152}
1153
1154func (c *configImpl) SoongMakeVarsMk() string {
1155 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1156}
1157
Dan Willemsenf052f782017-05-18 15:29:04 -07001158func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001159 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001160}
1161
Dan Willemsen02781d52017-05-12 19:28:13 -07001162func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001163 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1164}
1165
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001166func (c *configImpl) KatiPackageMkDir() string {
1167 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1168}
1169
Dan Willemsenf052f782017-05-18 15:29:04 -07001170func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001171 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001172}
1173
1174func (c *configImpl) HostOut() string {
1175 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1176}
1177
1178// This probably needs to be multi-valued, so not exporting it for now
1179func (c *configImpl) hostCrossOut() string {
1180 if runtime.GOOS == "linux" {
1181 return filepath.Join(c.hostOutRoot(), "windows-x86")
1182 } else {
1183 return ""
1184 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001185}
1186
Dan Willemsen1e704462016-08-21 15:17:17 -07001187func (c *configImpl) HostPrebuiltTag() string {
1188 if runtime.GOOS == "linux" {
1189 return "linux-x86"
1190 } else if runtime.GOOS == "darwin" {
1191 return "darwin-x86"
1192 } else {
1193 panic("Unsupported OS")
1194 }
1195}
Dan Willemsenf173d592017-04-27 14:28:00 -07001196
Dan Willemsen8122bd52017-10-12 20:20:41 -07001197func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001198 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1199 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001200 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1201 if _, err := os.Stat(asan); err == nil {
1202 return asan
1203 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001204 }
1205 }
1206 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1207}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001208
1209func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1210 c.brokenDupRules = val
1211}
1212
1213func (c *configImpl) BuildBrokenDupRules() bool {
1214 return c.brokenDupRules
1215}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001216
Dan Willemsen25e6f092019-04-09 10:22:43 -07001217func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1218 c.brokenUsesNetwork = val
1219}
1220
1221func (c *configImpl) BuildBrokenUsesNetwork() bool {
1222 return c.brokenUsesNetwork
1223}
1224
Dan Willemsene3336352020-01-02 19:10:38 -08001225func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1226 c.brokenNinjaEnvVars = val
1227}
1228
1229func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1230 return c.brokenNinjaEnvVars
1231}
1232
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001233func (c *configImpl) SetTargetDeviceDir(dir string) {
1234 c.targetDeviceDir = dir
1235}
1236
1237func (c *configImpl) TargetDeviceDir() string {
1238 return c.targetDeviceDir
1239}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001240
Patrice Arruda219eef32020-06-01 17:29:30 +00001241func (c *configImpl) BuildDateTime() string {
1242 return c.buildDateTime
1243}
1244
1245func (c *configImpl) MetricsUploaderApp() string {
1246 if p, ok := c.environ.Get("ANDROID_ENABLE_METRICS_UPLOAD"); ok {
1247 return p
1248 }
1249 return ""
1250}
Patrice Arruda83842d72020-12-08 19:42:08 +00001251
1252// LogsDir returns the logs directory where build log and metrics
1253// files are located. By default, the logs directory is the out
1254// directory. If the argument dist is specified, the logs directory
1255// is <dist_dir>/logs.
1256func (c *configImpl) LogsDir() string {
1257 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001258 // Always write logs to the real dist dir, even if Bazel is using a rigged dist dir for other files
1259 return filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001260 }
1261 return c.OutDir()
1262}
1263
1264// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1265// where the bazel profiles are located.
1266func (c *configImpl) BazelMetricsDir() string {
1267 return filepath.Join(c.LogsDir(), "bazel_metrics")
1268}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001269
1270func (c *configImpl) SetEmptyNinjaFile(v bool) {
1271 c.emptyNinjaFile = v
1272}
1273
1274func (c *configImpl) EmptyNinjaFile() bool {
1275 return c.emptyNinjaFile
1276}