blob: b6d0d2747efcefdd21bcac84d3e893d8d35d070c [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
Yu Liu6e13b402021-07-27 14:29:06 -070086
87 metricsUploader string
Dan Willemsen1e704462016-08-21 15:17:17 -070088}
89
Dan Willemsenc2af0be2017-01-20 14:10:01 -080090const srcDirFileCheck = "build/soong/root.bp"
91
Patrice Arruda9450d0b2019-07-08 11:06:46 -070092var buildFiles = []string{"Android.mk", "Android.bp"}
93
Patrice Arruda13848222019-04-22 17:12:02 -070094type BuildAction uint
95
96const (
97 // Builds all of the modules and their dependencies of a specified directory, relative to the root
98 // directory of the source tree.
99 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
100
101 // Builds all of the modules and their dependencies of a list of specified directories. All specified
102 // directories are relative to the root directory of the source tree.
103 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700104
105 // Build a list of specified modules. If none was specified, simply build the whole source tree.
106 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700107)
108
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400109type bazelBuildMode int
110
111// Bazel-related build modes.
112const (
113 // Don't use bazel at all.
114 noBazel bazelBuildMode = iota
115
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400116 // Generate synthetic build files and incorporate these files into a build which
117 // partially uses Bazel. Build metadata may come from Android.bp or BUILD files.
118 mixedBuild
119)
120
Patrice Arruda13848222019-04-22 17:12:02 -0700121// checkTopDir validates that the current directory is at the root directory of the source tree.
122func checkTopDir(ctx Context) {
123 if _, err := os.Stat(srcDirFileCheck); err != nil {
124 if os.IsNotExist(err) {
125 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
126 }
127 ctx.Fatalln("Error verifying tree state:", err)
128 }
129}
130
Dan Willemsen1e704462016-08-21 15:17:17 -0700131func NewConfig(ctx Context, args ...string) Config {
132 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000133 environ: OsEnvironment(),
134 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700135 }
136
Patrice Arruda90109172020-07-28 18:07:27 +0000137 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700138 ret.parallel = runtime.NumCPU() + 2
139 ret.keepGoing = 1
140
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800141 ret.totalRAM = detectTotalRAM(ctx)
142
Dan Willemsen9b587492017-07-10 22:13:00 -0700143 ret.parseArgs(ctx, args)
144
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800145 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700146 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
147 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
148 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800149 outDir := "out"
150 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
151 if wd, err := os.Getwd(); err != nil {
152 ctx.Fatalln("Failed to get working directory:", err)
153 } else {
154 outDir = filepath.Join(baseDir, filepath.Base(wd))
155 }
156 }
157 ret.environ.Set("OUT_DIR", outDir)
158 }
159
Dan Willemsen2d31a442018-10-20 21:33:41 -0700160 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
161 ret.distDir = filepath.Clean(distDir)
162 } else {
163 ret.distDir = filepath.Join(ret.OutDir(), "dist")
164 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700165
Spandan Das05063612021-06-25 01:39:04 +0000166 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
167 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
168 }
169
Dan Willemsen1e704462016-08-21 15:17:17 -0700170 ret.environ.Unset(
171 // We're already using it
172 "USE_SOONG_UI",
173
174 // We should never use GOROOT/GOPATH from the shell environment
175 "GOROOT",
176 "GOPATH",
177
178 // These should only come from Soong, not the environment.
179 "CLANG",
180 "CLANG_CXX",
181 "CCC_CC",
182 "CCC_CXX",
183
184 // Used by the goma compiler wrapper, but should only be set by
185 // gomacc
186 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800187
188 // We handle this above
189 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700190
Dan Willemsen2d31a442018-10-20 21:33:41 -0700191 // This is handled above too, and set for individual commands later
192 "DIST_DIR",
193
Dan Willemsen68a09852017-04-18 13:56:57 -0700194 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000195 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700196 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700197 "DISPLAY",
198 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700199 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700200 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700201
202 // Drop make flags
203 "MAKEFLAGS",
204 "MAKELEVEL",
205 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700206
207 // Set in envsetup.sh, reset in makefiles
208 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700209
210 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
211 "ANDROID_BUILD_TOP",
212 "ANDROID_HOST_OUT",
213 "ANDROID_PRODUCT_OUT",
214 "ANDROID_HOST_OUT_TESTCASES",
215 "ANDROID_TARGET_OUT_TESTCASES",
216 "ANDROID_TOOLCHAIN",
217 "ANDROID_TOOLCHAIN_2ND_ARCH",
218 "ANDROID_DEV_SCRIPTS",
219 "ANDROID_EMULATOR_PREBUILTS",
220 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700221 )
222
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400223 if ret.UseGoma() || ret.ForceUseGoma() {
224 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
225 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400226 }
227
Dan Willemsen1e704462016-08-21 15:17:17 -0700228 // Tell python not to spam the source tree with .pyc files.
229 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
230
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400231 tmpDir := absPath(ctx, ret.TempDir())
232 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800233
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700234 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
235 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
236 "llvm-binutils-stable/llvm-symbolizer")
237 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
238
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800239 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700240 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800241
Yu Liu6e13b402021-07-27 14:29:06 -0700242 srcDir := absPath(ctx, ".")
243 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700244 ctx.Println("You are building in a directory whose absolute path contains a space character:")
245 ctx.Println()
246 ctx.Printf("%q\n", srcDir)
247 ctx.Println()
248 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700249 }
250
Yu Liu6e13b402021-07-27 14:29:06 -0700251 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
252
Dan Willemsendb8457c2017-05-12 16:38:17 -0700253 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700254 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
255 ctx.Println()
256 ctx.Printf("%q\n", outDir)
257 ctx.Println()
258 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700259 }
260
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000261 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700262 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
263 ctx.Println()
264 ctx.Printf("%q\n", distDir)
265 ctx.Println()
266 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700267 }
268
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700269 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000270 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
271 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100272 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700273 javaHome := func() string {
274 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
275 return override
276 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000277 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
278 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 +0100279 }
Pete Gillinabbcdda2019-10-28 16:15:33 +0000280 return java11Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700281 }()
282 absJavaHome := absPath(ctx, javaHome)
283
Dan Willemsened869522018-01-08 14:58:46 -0800284 ret.configureLocale(ctx)
285
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700286 newPath := []string{filepath.Join(absJavaHome, "bin")}
287 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
288 newPath = append(newPath, path)
289 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100290
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700291 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
292 ret.environ.Set("JAVA_HOME", absJavaHome)
293 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000294 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
295 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100296 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700297 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
298
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800299 outDir := ret.OutDir()
300 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800301 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800302 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800303 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800304 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800305 }
Colin Cross28f527c2019-11-26 16:19:04 -0800306
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800307 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
308
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400309 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400310 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400311 ret.environ.Set(k, v)
312 }
313 }
314
Patrice Arruda83842d72020-12-08 19:42:08 +0000315 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800316 if err := os.RemoveAll(bpd); err != nil {
317 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
318 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000319
320 ret.useBazel = ret.environ.IsEnvTrue("USE_BAZEL")
321
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800322 if ret.UseBazel() {
323 if err := os.MkdirAll(bpd, 0777); err != nil {
324 ctx.Fatalf("Failed to create bazel profile directory %q: %v", bpd, err)
325 }
326 }
327
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000328 if ret.UseBazel() {
329 ret.riggedDistDirForBazel = filepath.Join(ret.OutDir(), "dist")
330 } else {
331 // Not rigged
332 ret.riggedDistDirForBazel = ret.distDir
333 }
334
Patrice Arruda96850362020-08-11 20:41:11 +0000335 c := Config{ret}
336 storeConfigMetrics(ctx, c)
337 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700338}
339
Patrice Arruda13848222019-04-22 17:12:02 -0700340// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
341// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700342func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
343 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700344}
345
Patrice Arruda96850362020-08-11 20:41:11 +0000346// storeConfigMetrics selects a set of configuration information and store in
347// the metrics system for further analysis.
348func storeConfigMetrics(ctx Context, config Config) {
349 if ctx.Metrics == nil {
350 return
351 }
352
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400353 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000354
355 s := &smpb.SystemResourceInfo{
356 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
357 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
358 }
359 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000360}
361
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400362func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700363 c := &smpb.BuildConfig{
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400364 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
365 UseGoma: proto.Bool(config.UseGoma()),
366 UseRbe: proto.Bool(config.UseRBE()),
367 BazelAsNinja: proto.Bool(config.UseBazel()),
368 BazelMixedBuild: proto.Bool(config.bazelBuildMode() == mixedBuild),
369 }
Yu Liue737a992021-10-04 13:21:41 -0700370 c.Targets = append(c.Targets, config.arguments...)
371
372 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400373}
374
Patrice Arruda13848222019-04-22 17:12:02 -0700375// getConfigArgs processes the command arguments based on the build action and creates a set of new
376// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700377func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700378 // The next block of code verifies that the current directory is the root directory of the source
379 // tree. It then finds the relative path of dir based on the root directory of the source tree
380 // and verify that dir is inside of the source tree.
381 checkTopDir(ctx)
382 topDir, err := os.Getwd()
383 if err != nil {
384 ctx.Fatalf("Error retrieving top directory: %v", err)
385 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700386 dir, err = filepath.EvalSymlinks(dir)
387 if err != nil {
388 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
389 }
Patrice Arruda13848222019-04-22 17:12:02 -0700390 dir, err = filepath.Abs(dir)
391 if err != nil {
392 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
393 }
394 relDir, err := filepath.Rel(topDir, dir)
395 if err != nil {
396 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
397 }
398 // If there are ".." in the path, it's not in the source tree.
399 if strings.Contains(relDir, "..") {
400 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
401 }
402
403 configArgs := args[:]
404
405 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
406 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
407 targetNamePrefix := "MODULES-IN-"
408 if inList("GET-INSTALL-PATH", configArgs) {
409 targetNamePrefix = "GET-INSTALL-PATH-IN-"
410 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
411 }
412
Patrice Arruda13848222019-04-22 17:12:02 -0700413 var targets []string
414
415 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700416 case BUILD_MODULES:
417 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700418 case BUILD_MODULES_IN_A_DIRECTORY:
419 // If dir is the root source tree, all the modules are built of the source tree are built so
420 // no need to find the build file.
421 if topDir == dir {
422 break
423 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700424
Patrice Arruda13848222019-04-22 17:12:02 -0700425 buildFile := findBuildFile(ctx, relDir)
426 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700427 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700428 }
Patrice Arruda13848222019-04-22 17:12:02 -0700429 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
430 case BUILD_MODULES_IN_DIRECTORIES:
431 newConfigArgs, dirs := splitArgs(configArgs)
432 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700433 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700434 }
435
436 // Tidy only override all other specified targets.
437 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
438 if tidyOnly == "true" || tidyOnly == "1" {
439 configArgs = append(configArgs, "tidy_only")
440 } else {
441 configArgs = append(configArgs, targets...)
442 }
443
444 return configArgs
445}
446
447// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
448func convertToTarget(dir string, targetNamePrefix string) string {
449 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
450}
451
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700452// hasBuildFile returns true if dir contains an Android build file.
453func hasBuildFile(ctx Context, dir string) bool {
454 for _, buildFile := range buildFiles {
455 _, err := os.Stat(filepath.Join(dir, buildFile))
456 if err == nil {
457 return true
458 }
459 if !os.IsNotExist(err) {
460 ctx.Fatalf("Error retrieving the build file stats: %v", err)
461 }
462 }
463 return false
464}
465
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700466// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
467// in the current and any sub directory of dir. If a build file is not found, traverse the path
468// up by one directory and repeat again until either a build file is found or reached to the root
469// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
470// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700471func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700472 // If the string is empty or ".", assume it is top directory of the source tree.
473 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700474 return ""
475 }
476
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700477 found := false
478 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
479 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
480 if err != nil {
481 return err
482 }
483 if found {
484 return filepath.SkipDir
485 }
486 if info.IsDir() {
487 return nil
488 }
489 for _, buildFile := range buildFiles {
490 if info.Name() == buildFile {
491 found = true
492 return filepath.SkipDir
493 }
494 }
495 return nil
496 })
497 if err != nil {
498 ctx.Fatalf("Error finding Android build file: %v", err)
499 }
500
501 if found {
502 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700503 }
504 }
505
506 return ""
507}
508
509// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
510func splitArgs(args []string) (newArgs []string, dirs []string) {
511 specialArgs := map[string]bool{
512 "showcommands": true,
513 "snod": true,
514 "dist": true,
515 "checkbuild": true,
516 }
517
518 newArgs = []string{}
519 dirs = []string{}
520
521 for _, arg := range args {
522 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
523 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
524 newArgs = append(newArgs, arg)
525 continue
526 }
527
528 if _, ok := specialArgs[arg]; ok {
529 newArgs = append(newArgs, arg)
530 continue
531 }
532
533 dirs = append(dirs, arg)
534 }
535
536 return newArgs, dirs
537}
538
539// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
540// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
541// source root tree where the build action command was invoked. Each directory is validated if the
542// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700543func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700544 for _, dir := range dirs {
545 // The directory may have specified specific modules to build. ":" is the separator to separate
546 // the directory and the list of modules.
547 s := strings.Split(dir, ":")
548 l := len(s)
549 if l > 2 { // more than one ":" was specified.
550 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
551 }
552
553 dir = filepath.Join(relDir, s[0])
554 if _, err := os.Stat(dir); err != nil {
555 ctx.Fatalf("couldn't find directory %s", dir)
556 }
557
558 // Verify that if there are any targets specified after ":". Each target is separated by ",".
559 var newTargets []string
560 if l == 2 && s[1] != "" {
561 newTargets = strings.Split(s[1], ",")
562 if inList("", newTargets) {
563 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
564 }
565 }
566
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700567 // If there are specified targets to build in dir, an android build file must exist for the one
568 // shot build. For the non-targets case, find the appropriate build file and build all the
569 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700570 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700571 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700572 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
573 }
574 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700575 buildFile := findBuildFile(ctx, dir)
576 if buildFile == "" {
577 ctx.Fatalf("Build file not found for %s directory", dir)
578 }
579 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700580 }
581
Patrice Arruda13848222019-04-22 17:12:02 -0700582 targets = append(targets, newTargets...)
583 }
584
Dan Willemsence41e942019-07-29 23:39:30 -0700585 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700586}
587
Dan Willemsen9b587492017-07-10 22:13:00 -0700588func (c *configImpl) parseArgs(ctx Context, args []string) {
589 for i := 0; i < len(args); i++ {
590 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100591 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700592 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200593 } else if arg == "--empty-ninja-file" {
594 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100595 } else if arg == "--skip-ninja" {
596 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700597 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700598 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
599 // but it does run a Kati ninja file if the .kati_enabled marker file was created
600 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000601 c.skipConfig = true
602 c.skipKati = true
603 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100604 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000605 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100606 } else if arg == "--soong-only" {
607 c.skipKati = true
608 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200609 } else if arg == "--config-only" {
610 c.skipKati = true
611 c.skipKatiNinja = true
612 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700613 } else if arg == "--skip-config" {
614 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700615 } else if arg == "--skip-soong-tests" {
616 c.skipSoongTests = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700617 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700618 parseArgNum := func(def int) int {
619 if len(arg) > 2 {
620 p, err := strconv.ParseUint(arg[2:], 10, 31)
621 if err != nil {
622 ctx.Fatalf("Failed to parse %q: %v", arg, err)
623 }
624 return int(p)
625 } else if i+1 < len(args) {
626 p, err := strconv.ParseUint(args[i+1], 10, 31)
627 if err == nil {
628 i++
629 return int(p)
630 }
631 }
632 return def
633 }
634
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700635 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700636 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700637 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700638 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700639 } else {
640 ctx.Fatalln("Unknown option:", arg)
641 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700642 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700643 if k == "OUT_DIR" {
644 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
645 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700646 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700647 } else if arg == "dist" {
648 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200649 } else if arg == "json-module-graph" {
650 c.jsonModuleGraph = true
651 } else if arg == "bp2build" {
652 c.bp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200653 } else if arg == "queryview" {
654 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200655 } else if arg == "soong_docs" {
656 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700657 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700658 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800659 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700660 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700661 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700662 }
663 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700664}
665
Dan Willemsened869522018-01-08 14:58:46 -0800666func (c *configImpl) configureLocale(ctx Context) {
667 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
668 output, err := cmd.Output()
669
670 var locales []string
671 if err == nil {
672 locales = strings.Split(string(output), "\n")
673 } else {
674 // If we're unable to list the locales, let's assume en_US.UTF-8
675 locales = []string{"en_US.UTF-8"}
676 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
677 }
678
679 // gettext uses LANGUAGE, which is passed directly through
680
681 // For LANG and LC_*, only preserve the evaluated version of
682 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800683 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800684 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800685 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800686 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800687 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800688 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800689 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800690 }
691
692 c.environ.UnsetWithPrefix("LC_")
693
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800694 if userLang != "" {
695 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800696 }
697
698 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
699 // for others)
700 if inList("C.UTF-8", locales) {
701 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500702 } else if inList("C.utf8", locales) {
703 // These normalize to the same thing
704 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800705 } else if inList("en_US.UTF-8", locales) {
706 c.environ.Set("LANG", "en_US.UTF-8")
707 } else if inList("en_US.utf8", locales) {
708 // These normalize to the same thing
709 c.environ.Set("LANG", "en_US.UTF-8")
710 } else {
711 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
712 }
713}
714
Dan Willemsen1e704462016-08-21 15:17:17 -0700715func (c *configImpl) Environment() *Environment {
716 return c.environ
717}
718
719func (c *configImpl) Arguments() []string {
720 return c.arguments
721}
722
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200723func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200724 if len(c.Arguments()) > 0 {
725 // Explicit targets requested that are not special targets like b2pbuild
726 // or the JSON module graph
727 return true
728 }
729
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200730 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200731 // Command line was empty, the default Ninja target is built
732 return true
733 }
734
Liz Kammer88677422021-12-15 15:03:19 -0500735 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
736 if c.Dist() && !c.Bp2Build() {
737 return true
738 }
739
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200740 // build.ninja doesn't need to be generated
741 return false
742}
743
Dan Willemsen1e704462016-08-21 15:17:17 -0700744func (c *configImpl) OutDir() string {
745 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700746 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700747 }
748 return "out"
749}
750
Dan Willemsen8a073a82017-02-04 17:30:44 -0800751func (c *configImpl) DistDir() string {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000752 if c.UseBazel() {
753 return c.riggedDistDirForBazel
754 } else {
755 return c.distDir
756 }
757}
758
759func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700760 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800761}
762
Dan Willemsen1e704462016-08-21 15:17:17 -0700763func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000764 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700765 return c.arguments
766 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700767 return c.ninjaArgs
768}
769
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500770func (c *configImpl) BazelOutDir() string {
771 return filepath.Join(c.OutDir(), "bazel")
772}
773
Dan Willemsen1e704462016-08-21 15:17:17 -0700774func (c *configImpl) SoongOutDir() string {
775 return filepath.Join(c.OutDir(), "soong")
776}
777
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200778func (c *configImpl) PrebuiltOS() string {
779 switch runtime.GOOS {
780 case "linux":
781 return "linux-x86"
782 case "darwin":
783 return "darwin-x86"
784 default:
785 panic("Unknown GOOS")
786 }
787}
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100788
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200789func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -0700790 if c.SkipKatiNinja() {
791 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
792 } else {
793 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
794 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200795}
796
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200797func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100798 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200799}
800
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200801func (c *configImpl) UsedEnvFile(tag string) string {
802 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
803}
804
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200805func (c *configImpl) Bp2BuildMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100806 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200807}
808
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200809func (c *configImpl) SoongDocsHtml() string {
810 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
811}
812
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200813func (c *configImpl) QueryviewMarkerFile() string {
814 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
815}
816
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200817func (c *configImpl) ModuleGraphFile() string {
818 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
819}
820
Jeff Gastonefc1b412017-03-29 17:29:06 -0700821func (c *configImpl) TempDir() string {
822 return shared.TempDirForOutDir(c.SoongOutDir())
823}
824
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700825func (c *configImpl) FileListDir() string {
826 return filepath.Join(c.OutDir(), ".module_paths")
827}
828
Dan Willemsen1e704462016-08-21 15:17:17 -0700829func (c *configImpl) KatiSuffix() string {
830 if c.katiSuffix != "" {
831 return c.katiSuffix
832 }
833 panic("SetKatiSuffix has not been called")
834}
835
Colin Cross37193492017-11-16 17:55:00 -0800836// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
837// user is interested in additional checks at the expense of build time.
838func (c *configImpl) Checkbuild() bool {
839 return c.checkbuild
840}
841
Dan Willemsen8a073a82017-02-04 17:30:44 -0800842func (c *configImpl) Dist() bool {
843 return c.dist
844}
845
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200846func (c *configImpl) JsonModuleGraph() bool {
847 return c.jsonModuleGraph
848}
849
850func (c *configImpl) Bp2Build() bool {
851 return c.bp2build
852}
853
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200854func (c *configImpl) Queryview() bool {
855 return c.queryview
856}
857
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200858func (c *configImpl) SoongDocs() bool {
859 return c.soongDocs
860}
861
Dan Willemsen1e704462016-08-21 15:17:17 -0700862func (c *configImpl) IsVerbose() bool {
863 return c.verbose
864}
865
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000866func (c *configImpl) SkipKati() bool {
867 return c.skipKati
868}
869
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100870func (c *configImpl) SkipKatiNinja() bool {
871 return c.skipKatiNinja
872}
873
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200874func (c *configImpl) SkipSoong() bool {
875 return c.skipSoong
876}
877
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100878func (c *configImpl) SkipNinja() bool {
879 return c.skipNinja
880}
881
Anton Hansson5a7861a2021-06-04 10:09:01 +0100882func (c *configImpl) SetSkipNinja(v bool) {
883 c.skipNinja = v
884}
885
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000886func (c *configImpl) SkipConfig() bool {
887 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -0700888}
889
Dan Willemsen1e704462016-08-21 15:17:17 -0700890func (c *configImpl) TargetProduct() string {
891 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
892 return v
893 }
894 panic("TARGET_PRODUCT is not defined")
895}
896
Dan Willemsen02781d52017-05-12 19:28:13 -0700897func (c *configImpl) TargetDevice() string {
898 return c.targetDevice
899}
900
901func (c *configImpl) SetTargetDevice(device string) {
902 c.targetDevice = device
903}
904
905func (c *configImpl) TargetBuildVariant() string {
906 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
907 return v
908 }
909 panic("TARGET_BUILD_VARIANT is not defined")
910}
911
Dan Willemsen1e704462016-08-21 15:17:17 -0700912func (c *configImpl) KatiArgs() []string {
913 return c.katiArgs
914}
915
916func (c *configImpl) Parallel() int {
917 return c.parallel
918}
919
Colin Cross8b8bec32019-11-15 13:18:43 -0800920func (c *configImpl) HighmemParallel() int {
921 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
922 return i
923 }
924
925 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
926 parallel := c.Parallel()
927 if c.UseRemoteBuild() {
928 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
929 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
930 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
931 // Return 1/16th of the size of the local pool, rounding up.
932 return (parallel + 15) / 16
933 } else if c.totalRAM == 0 {
934 // Couldn't detect the total RAM, don't restrict highmem processes.
935 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -0700936 } else if c.totalRAM <= 16*1024*1024*1024 {
937 // Less than 16GB of ram, restrict to 1 highmem processes
938 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -0800939 } else if c.totalRAM <= 32*1024*1024*1024 {
940 // Less than 32GB of ram, restrict to 2 highmem processes
941 return 2
942 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
943 // If less than 8GB total RAM per process, reduce the number of highmem processes
944 return p
945 }
946 // No restriction on highmem processes
947 return parallel
948}
949
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800950func (c *configImpl) TotalRAM() uint64 {
951 return c.totalRAM
952}
953
Kousik Kumarec478642020-09-21 13:39:24 -0400954// ForceUseGoma determines whether we should override Goma deprecation
955// and use Goma for the current build or not.
956func (c *configImpl) ForceUseGoma() bool {
957 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
958 v = strings.TrimSpace(v)
959 if v != "" && v != "false" {
960 return true
961 }
962 }
963 return false
964}
965
Dan Willemsen1e704462016-08-21 15:17:17 -0700966func (c *configImpl) UseGoma() bool {
967 if v, ok := c.environ.Get("USE_GOMA"); ok {
968 v = strings.TrimSpace(v)
969 if v != "" && v != "false" {
970 return true
971 }
972 }
973 return false
974}
975
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +0900976func (c *configImpl) StartGoma() bool {
977 if !c.UseGoma() {
978 return false
979 }
980
981 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
982 v = strings.TrimSpace(v)
983 if v != "" && v != "false" {
984 return false
985 }
986 }
987 return true
988}
989
Ramy Medhatbbf25672019-07-17 12:30:04 +0000990func (c *configImpl) UseRBE() bool {
991 if v, ok := c.environ.Get("USE_RBE"); ok {
992 v = strings.TrimSpace(v)
993 if v != "" && v != "false" {
994 return true
995 }
996 }
997 return false
998}
999
Patrice Arruda0c1c4562020-11-11 13:01:25 -08001000func (c *configImpl) UseBazel() bool {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001001 return c.useBazel
Patrice Arruda0c1c4562020-11-11 13:01:25 -08001002}
1003
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001004func (c *configImpl) bazelBuildMode() bazelBuildMode {
1005 if c.Environment().IsEnvTrue("USE_BAZEL_ANALYSIS") {
1006 return mixedBuild
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001007 } else {
1008 return noBazel
1009 }
1010}
1011
Ramy Medhatbbf25672019-07-17 12:30:04 +00001012func (c *configImpl) StartRBE() bool {
1013 if !c.UseRBE() {
1014 return false
1015 }
1016
1017 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1018 v = strings.TrimSpace(v)
1019 if v != "" && v != "false" {
1020 return false
1021 }
1022 }
1023 return true
1024}
1025
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001026func (c *configImpl) rbeLogDir() string {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001027 for _, f := range []string{"RBE_log_dir", "FLAG_log_dir"} {
1028 if v, ok := c.environ.Get(f); ok {
1029 return v
1030 }
1031 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001032 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001033 return c.LogsDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001034 }
1035 return c.OutDir()
1036}
1037
1038func (c *configImpl) rbeStatsOutputDir() string {
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001039 for _, f := range []string{"RBE_output_dir", "FLAG_output_dir"} {
1040 if v, ok := c.environ.Get(f); ok {
1041 return v
1042 }
1043 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001044 return c.rbeLogDir()
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001045}
1046
1047func (c *configImpl) rbeLogPath() string {
1048 for _, f := range []string{"RBE_log_path", "FLAG_log_path"} {
1049 if v, ok := c.environ.Get(f); ok {
1050 return v
1051 }
1052 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001053 return fmt.Sprintf("text://%v/reproxy_log.txt", c.rbeLogDir())
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001054}
1055
1056func (c *configImpl) rbeExecRoot() string {
1057 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1058 if v, ok := c.environ.Get(f); ok {
1059 return v
1060 }
1061 }
1062 wd, err := os.Getwd()
1063 if err != nil {
1064 return ""
1065 }
1066 return wd
1067}
1068
1069func (c *configImpl) rbeDir() string {
1070 if v, ok := c.environ.Get("RBE_DIR"); ok {
1071 return v
1072 }
1073 return "prebuilts/remoteexecution-client/live/"
1074}
1075
1076func (c *configImpl) rbeReproxy() string {
1077 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1078 if v, ok := c.environ.Get(f); ok {
1079 return v
1080 }
1081 }
1082 return filepath.Join(c.rbeDir(), "reproxy")
1083}
1084
1085func (c *configImpl) rbeAuth() (string, string) {
1086 credFlags := []string{"use_application_default_credentials", "use_gce_credentials", "credential_file"}
1087 for _, cf := range credFlags {
1088 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1089 if v, ok := c.environ.Get(f); ok {
1090 v = strings.TrimSpace(v)
1091 if v != "" && v != "false" && v != "0" {
1092 return "RBE_" + cf, v
1093 }
1094 }
1095 }
1096 }
1097 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001098}
1099
Colin Cross9016b912019-11-11 14:57:42 -08001100func (c *configImpl) UseRemoteBuild() bool {
1101 return c.UseGoma() || c.UseRBE()
1102}
1103
Dan Willemsen1e704462016-08-21 15:17:17 -07001104// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001105// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001106// still limited by Parallel()
1107func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001108 if !c.UseRemoteBuild() {
1109 return 0
1110 }
1111 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1112 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001113 }
1114 return 500
1115}
1116
1117func (c *configImpl) SetKatiArgs(args []string) {
1118 c.katiArgs = args
1119}
1120
1121func (c *configImpl) SetNinjaArgs(args []string) {
1122 c.ninjaArgs = args
1123}
1124
1125func (c *configImpl) SetKatiSuffix(suffix string) {
1126 c.katiSuffix = suffix
1127}
1128
Dan Willemsene0879fc2017-08-04 15:06:27 -07001129func (c *configImpl) LastKatiSuffixFile() string {
1130 return filepath.Join(c.OutDir(), "last_kati_suffix")
1131}
1132
1133func (c *configImpl) HasKatiSuffix() bool {
1134 return c.katiSuffix != ""
1135}
1136
Dan Willemsen1e704462016-08-21 15:17:17 -07001137func (c *configImpl) KatiEnvFile() string {
1138 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1139}
1140
Dan Willemsen29971232018-09-26 14:58:30 -07001141func (c *configImpl) KatiBuildNinjaFile() string {
1142 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001143}
1144
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001145func (c *configImpl) KatiPackageNinjaFile() string {
1146 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1147}
1148
Dan Willemsen1e704462016-08-21 15:17:17 -07001149func (c *configImpl) SoongNinjaFile() string {
1150 return filepath.Join(c.SoongOutDir(), "build.ninja")
1151}
1152
1153func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001154 if c.katiSuffix == "" {
1155 return filepath.Join(c.OutDir(), "combined.ninja")
1156 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001157 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1158}
1159
1160func (c *configImpl) SoongAndroidMk() string {
1161 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1162}
1163
1164func (c *configImpl) SoongMakeVarsMk() string {
1165 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1166}
1167
Dan Willemsenf052f782017-05-18 15:29:04 -07001168func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001169 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001170}
1171
Dan Willemsen02781d52017-05-12 19:28:13 -07001172func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001173 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1174}
1175
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001176func (c *configImpl) KatiPackageMkDir() string {
1177 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1178}
1179
Dan Willemsenf052f782017-05-18 15:29:04 -07001180func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001181 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001182}
1183
1184func (c *configImpl) HostOut() string {
1185 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1186}
1187
1188// This probably needs to be multi-valued, so not exporting it for now
1189func (c *configImpl) hostCrossOut() string {
1190 if runtime.GOOS == "linux" {
1191 return filepath.Join(c.hostOutRoot(), "windows-x86")
1192 } else {
1193 return ""
1194 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001195}
1196
Dan Willemsen1e704462016-08-21 15:17:17 -07001197func (c *configImpl) HostPrebuiltTag() string {
1198 if runtime.GOOS == "linux" {
1199 return "linux-x86"
1200 } else if runtime.GOOS == "darwin" {
1201 return "darwin-x86"
1202 } else {
1203 panic("Unsupported OS")
1204 }
1205}
Dan Willemsenf173d592017-04-27 14:28:00 -07001206
Dan Willemsen8122bd52017-10-12 20:20:41 -07001207func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001208 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1209 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001210 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1211 if _, err := os.Stat(asan); err == nil {
1212 return asan
1213 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001214 }
1215 }
1216 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1217}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001218
1219func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1220 c.brokenDupRules = val
1221}
1222
1223func (c *configImpl) BuildBrokenDupRules() bool {
1224 return c.brokenDupRules
1225}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001226
Dan Willemsen25e6f092019-04-09 10:22:43 -07001227func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1228 c.brokenUsesNetwork = val
1229}
1230
1231func (c *configImpl) BuildBrokenUsesNetwork() bool {
1232 return c.brokenUsesNetwork
1233}
1234
Dan Willemsene3336352020-01-02 19:10:38 -08001235func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1236 c.brokenNinjaEnvVars = val
1237}
1238
1239func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1240 return c.brokenNinjaEnvVars
1241}
1242
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001243func (c *configImpl) SetTargetDeviceDir(dir string) {
1244 c.targetDeviceDir = dir
1245}
1246
1247func (c *configImpl) TargetDeviceDir() string {
1248 return c.targetDeviceDir
1249}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001250
Patrice Arruda219eef32020-06-01 17:29:30 +00001251func (c *configImpl) BuildDateTime() string {
1252 return c.buildDateTime
1253}
1254
1255func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001256 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001257}
Patrice Arruda83842d72020-12-08 19:42:08 +00001258
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001259// LogsDir returns the absolute path to the logs directory where build log and
1260// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001261// directory. If the argument dist is specified, the logs directory
1262// is <dist_dir>/logs.
1263func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001264 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001265 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001266 // Always write logs to the real dist dir, even if Bazel is using a rigged dist dir for other files
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001267 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001268 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001269 absDir, err := filepath.Abs(dir)
1270 if err != nil {
1271 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1272 os.Exit(1)
1273 }
1274 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001275}
1276
1277// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1278// where the bazel profiles are located.
1279func (c *configImpl) BazelMetricsDir() string {
1280 return filepath.Join(c.LogsDir(), "bazel_metrics")
1281}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001282
1283func (c *configImpl) SetEmptyNinjaFile(v bool) {
1284 c.emptyNinjaFile = v
1285}
1286
1287func (c *configImpl) EmptyNinjaFile() bool {
1288 return c.emptyNinjaFile
1289}
Yu Liu6e13b402021-07-27 14:29:06 -07001290
1291func GetMetricsUploader(topDir string, env *Environment) string {
1292 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1293 metricsUploader := filepath.Join(topDir, p)
1294 if _, err := os.Stat(metricsUploader); err == nil {
1295 return metricsUploader
1296 }
1297 }
1298
1299 return ""
1300}