blob: de10112bf93374e2da199f3abfe96a1ae2381183 [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 (
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050018 "context"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050019 "encoding/json"
Ramy Medhat0fc67eb2020-08-12 01:26:23 -040020 "fmt"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050021 "io/ioutil"
Kousik Kumar4c180ad2022-05-27 07:48:37 -040022 "math/rand"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080023 "os"
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050024 "os/exec"
Dan Willemsen1e704462016-08-21 15:17:17 -070025 "path/filepath"
26 "runtime"
27 "strconv"
28 "strings"
Kousik Kumar4c180ad2022-05-27 07:48:37 -040029 "syscall"
Nan Zhang2e6a4ff2018-02-14 13:27:26 -080030 "time"
Jeff Gastonefc1b412017-03-29 17:29:06 -070031
32 "android/soong/shared"
Kousik Kumarec478642020-09-21 13:39:24 -040033
Dan Willemsen4591b642021-05-24 14:24:12 -070034 "google.golang.org/protobuf/proto"
Patrice Arruda96850362020-08-11 20:41:11 +000035
36 smpb "android/soong/ui/metrics/metrics_proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070037)
38
Kousik Kumar3ff037e2022-01-25 22:11:01 -050039const (
Chris Parsons53f68ae2022-03-03 12:01:40 -050040 envConfigDir = "vendor/google/tools/soong_config"
41 jsonSuffix = "json"
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050042
Chris Parsons53f68ae2022-03-03 12:01:40 -050043 configFetcher = "vendor/google/tools/soong/expconfigfetcher"
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050044 envConfigFetchTimeout = 10 * time.Second
Kousik Kumar3ff037e2022-01-25 22:11:01 -050045)
46
Kousik Kumar4c180ad2022-05-27 07:48:37 -040047var (
48 rbeRandPrefix int
49)
50
51func init() {
52 rand.Seed(time.Now().UnixNano())
53 rbeRandPrefix = rand.Intn(1000)
54}
55
Dan Willemsen1e704462016-08-21 15:17:17 -070056type Config struct{ *configImpl }
57
58type configImpl struct {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020059 // Some targets that are implemented in soong_build
60 // (bp2build, json-module-graph) are not here and have their own bits below.
Colin Cross28f527c2019-11-26 16:19:04 -080061 arguments []string
62 goma bool
63 environ *Environment
64 distDir string
65 buildDateTime string
Dan Willemsen1e704462016-08-21 15:17:17 -070066
67 // From the arguments
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020068 parallel int
69 keepGoing int
70 verbose bool
71 checkbuild bool
72 dist bool
73 jsonModuleGraph bool
Spandan Das5af0bd32022-09-28 20:43:08 +000074 apiBp2build bool // Generate BUILD files for Soong modules that contribute APIs
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020075 bp2build bool
Lukacs T. Berki3a821692021-09-06 17:08:02 +020076 queryview bool
Chris Parsons53f68ae2022-03-03 12:01:40 -050077 reportMkMetrics bool // Collect and report mk2bp migration progress metrics.
Lukacs T. Berkic6012f32021-09-06 18:31:46 +020078 soongDocs bool
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020079 skipConfig bool
80 skipKati bool
81 skipKatiNinja bool
82 skipSoong bool
83 skipNinja bool
84 skipSoongTests bool
Dan Willemsen1e704462016-08-21 15:17:17 -070085
86 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070087 katiArgs []string
88 ninjaArgs []string
89 katiSuffix string
90 targetDevice string
91 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +000092 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -070093
Dan Willemsen2bb82d02019-12-27 09:35:42 -080094 // Autodetected
95 totalRAM uint64
96
Dan Willemsene3336352020-01-02 19:10:38 -080097 brokenDupRules bool
98 brokenUsesNetwork bool
99 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -0700100
101 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000102
MarkDacekb78465d2022-10-18 20:10:16 +0000103 bazelProdMode bool
104 bazelDevMode bool
105 bazelStagingMode bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000106
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700107 // Set by multiproduct_kati
108 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700109
110 metricsUploader string
Dan Willemsen1e704462016-08-21 15:17:17 -0700111}
112
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800113const srcDirFileCheck = "build/soong/root.bp"
114
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700115var buildFiles = []string{"Android.mk", "Android.bp"}
116
Patrice Arruda13848222019-04-22 17:12:02 -0700117type BuildAction uint
118
119const (
120 // Builds all of the modules and their dependencies of a specified directory, relative to the root
121 // directory of the source tree.
122 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
123
124 // Builds all of the modules and their dependencies of a list of specified directories. All specified
125 // directories are relative to the root directory of the source tree.
126 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700127
128 // Build a list of specified modules. If none was specified, simply build the whole source tree.
129 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700130)
131
132// checkTopDir validates that the current directory is at the root directory of the source tree.
133func checkTopDir(ctx Context) {
134 if _, err := os.Stat(srcDirFileCheck); err != nil {
135 if os.IsNotExist(err) {
136 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
137 }
138 ctx.Fatalln("Error verifying tree state:", err)
139 }
140}
141
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500142// fetchEnvConfig optionally fetches environment config from an
143// experiments system to control Soong features dynamically.
144func fetchEnvConfig(ctx Context, config *configImpl, envConfigName string) error {
David Goldsmith62243a32022-04-08 13:42:04 +0000145 configName := envConfigName + "." + jsonSuffix
Kousik Kumarc75e1292022-07-07 02:20:51 +0000146 expConfigFetcher := &smpb.ExpConfigFetcher{Filename: &configName}
David Goldsmith62243a32022-04-08 13:42:04 +0000147 defer func() {
148 ctx.Metrics.ExpConfigFetcher(expConfigFetcher)
149 }()
Kousik Kumarc75e1292022-07-07 02:20:51 +0000150 if !config.GoogleProdCredsExist() {
151 status := smpb.ExpConfigFetcher_MISSING_GCERT
152 expConfigFetcher.Status = &status
153 return nil
154 }
David Goldsmith62243a32022-04-08 13:42:04 +0000155
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500156 s, err := os.Stat(configFetcher)
157 if err != nil {
158 if os.IsNotExist(err) {
159 return nil
160 }
161 return err
162 }
163 if s.Mode()&0111 == 0 {
David Goldsmith62243a32022-04-08 13:42:04 +0000164 status := smpb.ExpConfigFetcher_ERROR
165 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500166 return fmt.Errorf("configuration fetcher binary %v is not executable: %v", configFetcher, s.Mode())
167 }
168
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500169 tCtx, cancel := context.WithTimeout(ctx, envConfigFetchTimeout)
170 defer cancel()
David Goldsmith62243a32022-04-08 13:42:04 +0000171 fetchStart := time.Now()
172 cmd := exec.CommandContext(tCtx, configFetcher, "-output_config_dir", config.OutDir(),
173 "-output_config_name", configName)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500174 if err := cmd.Start(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000175 status := smpb.ExpConfigFetcher_ERROR
176 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500177 return err
178 }
179
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500180 if err := cmd.Wait(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000181 status := smpb.ExpConfigFetcher_ERROR
182 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500183 return err
184 }
David Goldsmith62243a32022-04-08 13:42:04 +0000185 fetchEnd := time.Now()
186 expConfigFetcher.Micros = proto.Uint64(uint64(fetchEnd.Sub(fetchStart).Microseconds()))
187 outConfigFilePath := filepath.Join(config.OutDir(), configName)
188 expConfigFetcher.Filename = proto.String(outConfigFilePath)
189 if _, err := os.Stat(outConfigFilePath); err == nil {
190 status := smpb.ExpConfigFetcher_CONFIG
191 expConfigFetcher.Status = &status
192 } else {
193 status := smpb.ExpConfigFetcher_NO_CONFIG
194 expConfigFetcher.Status = &status
195 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500196 return nil
197}
198
199func loadEnvConfig(ctx Context, config *configImpl) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500200 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
201 if bc == "" {
202 return nil
203 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500204
205 if err := fetchEnvConfig(ctx, config, bc); err != nil {
Kousik Kumar595fb1c2022-06-24 16:49:52 +0000206 ctx.Verbosef("Failed to fetch config file: %v\n", err)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500207 }
208
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500209 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500210 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500211 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500212 envConfigDir,
213 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500214 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500215 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
216 envVarsJSON, err := ioutil.ReadFile(cfgFile)
217 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500218 continue
219 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500220 ctx.Verbosef("Loading config file %v\n", cfgFile)
221 var envVars map[string]map[string]string
222 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
223 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
224 continue
225 }
226 for k, v := range envVars["env"] {
227 if os.Getenv(k) != "" {
228 continue
229 }
230 config.environ.Set(k, v)
231 }
232 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
233 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500234 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500235
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500236 return nil
237}
238
Chris Parsonsb6e96902022-10-31 20:08:45 -0400239func defaultBazelProdMode(cfg *configImpl) bool {
240 // Envirnoment flag to disable Bazel for users which experience
241 // broken bazel-handled builds, or significant performance regressions.
242 if cfg.IsBazelMixedBuildForceDisabled() {
243 return false
244 }
245 // Darwin-host builds are currently untested with Bazel.
246 if runtime.GOOS == "darwin" {
247 return false
248 }
Chris Parsons035e03a2022-11-01 14:25:45 -0400249 return true
Chris Parsonsb6e96902022-10-31 20:08:45 -0400250}
251
Dan Willemsen1e704462016-08-21 15:17:17 -0700252func NewConfig(ctx Context, args ...string) Config {
253 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000254 environ: OsEnvironment(),
255 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700256 }
257
Patrice Arruda90109172020-07-28 18:07:27 +0000258 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700259 ret.parallel = runtime.NumCPU() + 2
260 ret.keepGoing = 1
261
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800262 ret.totalRAM = detectTotalRAM(ctx)
263
Dan Willemsen9b587492017-07-10 22:13:00 -0700264 ret.parseArgs(ctx, args)
265
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800266 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700267 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
268 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
269 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800270 outDir := "out"
271 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
272 if wd, err := os.Getwd(); err != nil {
273 ctx.Fatalln("Failed to get working directory:", err)
274 } else {
275 outDir = filepath.Join(baseDir, filepath.Base(wd))
276 }
277 }
278 ret.environ.Set("OUT_DIR", outDir)
279 }
280
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500281 // loadEnvConfig needs to know what the OUT_DIR is, so it should
282 // be called after we determine the appropriate out directory.
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500283 if err := loadEnvConfig(ctx, ret); err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500284 ctx.Fatalln("Failed to parse env config files: %v", err)
285 }
286
Dan Willemsen2d31a442018-10-20 21:33:41 -0700287 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
288 ret.distDir = filepath.Clean(distDir)
289 } else {
290 ret.distDir = filepath.Join(ret.OutDir(), "dist")
291 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700292
Spandan Das05063612021-06-25 01:39:04 +0000293 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
294 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
295 }
296
Dan Willemsen1e704462016-08-21 15:17:17 -0700297 ret.environ.Unset(
298 // We're already using it
299 "USE_SOONG_UI",
300
301 // We should never use GOROOT/GOPATH from the shell environment
302 "GOROOT",
303 "GOPATH",
304
305 // These should only come from Soong, not the environment.
306 "CLANG",
307 "CLANG_CXX",
308 "CCC_CC",
309 "CCC_CXX",
310
311 // Used by the goma compiler wrapper, but should only be set by
312 // gomacc
313 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800314
315 // We handle this above
316 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700317
Dan Willemsen2d31a442018-10-20 21:33:41 -0700318 // This is handled above too, and set for individual commands later
319 "DIST_DIR",
320
Dan Willemsen68a09852017-04-18 13:56:57 -0700321 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000322 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700323 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700324 "DISPLAY",
325 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700326 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700327 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700328
329 // Drop make flags
330 "MAKEFLAGS",
331 "MAKELEVEL",
332 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700333
334 // Set in envsetup.sh, reset in makefiles
335 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700336
337 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
338 "ANDROID_BUILD_TOP",
339 "ANDROID_HOST_OUT",
340 "ANDROID_PRODUCT_OUT",
341 "ANDROID_HOST_OUT_TESTCASES",
342 "ANDROID_TARGET_OUT_TESTCASES",
343 "ANDROID_TOOLCHAIN",
344 "ANDROID_TOOLCHAIN_2ND_ARCH",
345 "ANDROID_DEV_SCRIPTS",
346 "ANDROID_EMULATOR_PREBUILTS",
347 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700348 )
349
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400350 if ret.UseGoma() || ret.ForceUseGoma() {
351 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
352 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400353 }
354
Dan Willemsen1e704462016-08-21 15:17:17 -0700355 // Tell python not to spam the source tree with .pyc files.
356 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
357
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400358 tmpDir := absPath(ctx, ret.TempDir())
359 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800360
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700361 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
362 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
363 "llvm-binutils-stable/llvm-symbolizer")
364 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
365
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800366 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700367 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800368
Yu Liu6e13b402021-07-27 14:29:06 -0700369 srcDir := absPath(ctx, ".")
370 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700371 ctx.Println("You are building in a directory whose absolute path contains a space character:")
372 ctx.Println()
373 ctx.Printf("%q\n", srcDir)
374 ctx.Println()
375 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700376 }
377
Yu Liu6e13b402021-07-27 14:29:06 -0700378 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
379
Dan Willemsendb8457c2017-05-12 16:38:17 -0700380 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700381 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
382 ctx.Println()
383 ctx.Printf("%q\n", outDir)
384 ctx.Println()
385 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700386 }
387
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000388 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700389 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
390 ctx.Println()
391 ctx.Printf("%q\n", distDir)
392 ctx.Println()
393 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700394 }
395
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700396 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000397 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
398 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100399 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800400 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700401 javaHome := func() string {
402 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
403 return override
404 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000405 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
406 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 +0100407 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000408 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
409 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
410 }
411 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700412 }()
413 absJavaHome := absPath(ctx, javaHome)
414
Dan Willemsened869522018-01-08 14:58:46 -0800415 ret.configureLocale(ctx)
416
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700417 newPath := []string{filepath.Join(absJavaHome, "bin")}
418 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
419 newPath = append(newPath, path)
420 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100421
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700422 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
423 ret.environ.Set("JAVA_HOME", absJavaHome)
424 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000425 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
426 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100427 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700428 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
429
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800430 outDir := ret.OutDir()
431 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800432 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800433 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800434 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800435 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800436 }
Colin Cross28f527c2019-11-26 16:19:04 -0800437
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800438 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
439
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400440 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400441 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400442 ret.environ.Set(k, v)
443 }
444 }
445
Patrice Arruda83842d72020-12-08 19:42:08 +0000446 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800447 if err := os.RemoveAll(bpd); err != nil {
448 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
449 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000450
Patrice Arruda96850362020-08-11 20:41:11 +0000451 c := Config{ret}
452 storeConfigMetrics(ctx, c)
453 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700454}
455
Patrice Arruda13848222019-04-22 17:12:02 -0700456// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
457// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700458func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
459 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700460}
461
Patrice Arruda96850362020-08-11 20:41:11 +0000462// storeConfigMetrics selects a set of configuration information and store in
463// the metrics system for further analysis.
464func storeConfigMetrics(ctx Context, config Config) {
465 if ctx.Metrics == nil {
466 return
467 }
468
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400469 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000470
471 s := &smpb.SystemResourceInfo{
472 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
473 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
474 }
475 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000476}
477
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400478func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700479 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400480 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
481 UseGoma: proto.Bool(config.UseGoma()),
482 UseRbe: proto.Bool(config.UseRBE()),
483 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
484 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400485 }
Yu Liue737a992021-10-04 13:21:41 -0700486 c.Targets = append(c.Targets, config.arguments...)
487
488 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400489}
490
Patrice Arruda13848222019-04-22 17:12:02 -0700491// getConfigArgs processes the command arguments based on the build action and creates a set of new
492// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700493func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700494 // The next block of code verifies that the current directory is the root directory of the source
495 // tree. It then finds the relative path of dir based on the root directory of the source tree
496 // and verify that dir is inside of the source tree.
497 checkTopDir(ctx)
498 topDir, err := os.Getwd()
499 if err != nil {
500 ctx.Fatalf("Error retrieving top directory: %v", err)
501 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700502 dir, err = filepath.EvalSymlinks(dir)
503 if err != nil {
504 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
505 }
Patrice Arruda13848222019-04-22 17:12:02 -0700506 dir, err = filepath.Abs(dir)
507 if err != nil {
508 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
509 }
510 relDir, err := filepath.Rel(topDir, dir)
511 if err != nil {
512 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
513 }
514 // If there are ".." in the path, it's not in the source tree.
515 if strings.Contains(relDir, "..") {
516 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
517 }
518
519 configArgs := args[:]
520
521 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
522 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
523 targetNamePrefix := "MODULES-IN-"
524 if inList("GET-INSTALL-PATH", configArgs) {
525 targetNamePrefix = "GET-INSTALL-PATH-IN-"
526 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
527 }
528
Patrice Arruda13848222019-04-22 17:12:02 -0700529 var targets []string
530
531 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700532 case BUILD_MODULES:
533 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700534 case BUILD_MODULES_IN_A_DIRECTORY:
535 // If dir is the root source tree, all the modules are built of the source tree are built so
536 // no need to find the build file.
537 if topDir == dir {
538 break
539 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700540
Patrice Arruda13848222019-04-22 17:12:02 -0700541 buildFile := findBuildFile(ctx, relDir)
542 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700543 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700544 }
Patrice Arruda13848222019-04-22 17:12:02 -0700545 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
546 case BUILD_MODULES_IN_DIRECTORIES:
547 newConfigArgs, dirs := splitArgs(configArgs)
548 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700549 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700550 }
551
552 // Tidy only override all other specified targets.
553 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
554 if tidyOnly == "true" || tidyOnly == "1" {
555 configArgs = append(configArgs, "tidy_only")
556 } else {
557 configArgs = append(configArgs, targets...)
558 }
559
560 return configArgs
561}
562
563// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
564func convertToTarget(dir string, targetNamePrefix string) string {
565 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
566}
567
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700568// hasBuildFile returns true if dir contains an Android build file.
569func hasBuildFile(ctx Context, dir string) bool {
570 for _, buildFile := range buildFiles {
571 _, err := os.Stat(filepath.Join(dir, buildFile))
572 if err == nil {
573 return true
574 }
575 if !os.IsNotExist(err) {
576 ctx.Fatalf("Error retrieving the build file stats: %v", err)
577 }
578 }
579 return false
580}
581
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700582// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
583// in the current and any sub directory of dir. If a build file is not found, traverse the path
584// up by one directory and repeat again until either a build file is found or reached to the root
585// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
586// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700587func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700588 // If the string is empty or ".", assume it is top directory of the source tree.
589 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700590 return ""
591 }
592
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700593 found := false
594 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
595 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
596 if err != nil {
597 return err
598 }
599 if found {
600 return filepath.SkipDir
601 }
602 if info.IsDir() {
603 return nil
604 }
605 for _, buildFile := range buildFiles {
606 if info.Name() == buildFile {
607 found = true
608 return filepath.SkipDir
609 }
610 }
611 return nil
612 })
613 if err != nil {
614 ctx.Fatalf("Error finding Android build file: %v", err)
615 }
616
617 if found {
618 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700619 }
620 }
621
622 return ""
623}
624
625// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
626func splitArgs(args []string) (newArgs []string, dirs []string) {
627 specialArgs := map[string]bool{
628 "showcommands": true,
629 "snod": true,
630 "dist": true,
631 "checkbuild": true,
632 }
633
634 newArgs = []string{}
635 dirs = []string{}
636
637 for _, arg := range args {
638 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
639 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
640 newArgs = append(newArgs, arg)
641 continue
642 }
643
644 if _, ok := specialArgs[arg]; ok {
645 newArgs = append(newArgs, arg)
646 continue
647 }
648
649 dirs = append(dirs, arg)
650 }
651
652 return newArgs, dirs
653}
654
655// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
656// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
657// source root tree where the build action command was invoked. Each directory is validated if the
658// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700659func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700660 for _, dir := range dirs {
661 // The directory may have specified specific modules to build. ":" is the separator to separate
662 // the directory and the list of modules.
663 s := strings.Split(dir, ":")
664 l := len(s)
665 if l > 2 { // more than one ":" was specified.
666 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
667 }
668
669 dir = filepath.Join(relDir, s[0])
670 if _, err := os.Stat(dir); err != nil {
671 ctx.Fatalf("couldn't find directory %s", dir)
672 }
673
674 // Verify that if there are any targets specified after ":". Each target is separated by ",".
675 var newTargets []string
676 if l == 2 && s[1] != "" {
677 newTargets = strings.Split(s[1], ",")
678 if inList("", newTargets) {
679 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
680 }
681 }
682
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700683 // If there are specified targets to build in dir, an android build file must exist for the one
684 // shot build. For the non-targets case, find the appropriate build file and build all the
685 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700686 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700687 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700688 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
689 }
690 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700691 buildFile := findBuildFile(ctx, dir)
692 if buildFile == "" {
693 ctx.Fatalf("Build file not found for %s directory", dir)
694 }
695 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700696 }
697
Patrice Arruda13848222019-04-22 17:12:02 -0700698 targets = append(targets, newTargets...)
699 }
700
Dan Willemsence41e942019-07-29 23:39:30 -0700701 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700702}
703
Dan Willemsen9b587492017-07-10 22:13:00 -0700704func (c *configImpl) parseArgs(ctx Context, args []string) {
705 for i := 0; i < len(args); i++ {
706 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100707 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700708 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200709 } else if arg == "--empty-ninja-file" {
710 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100711 } else if arg == "--skip-ninja" {
712 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700713 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700714 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
715 // but it does run a Kati ninja file if the .kati_enabled marker file was created
716 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000717 c.skipConfig = true
718 c.skipKati = true
719 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100720 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000721 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100722 } else if arg == "--soong-only" {
723 c.skipKati = true
724 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200725 } else if arg == "--config-only" {
726 c.skipKati = true
727 c.skipKatiNinja = true
728 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700729 } else if arg == "--skip-config" {
730 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700731 } else if arg == "--skip-soong-tests" {
732 c.skipSoongTests = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500733 } else if arg == "--mk-metrics" {
734 c.reportMkMetrics = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400735 } else if arg == "--bazel-mode" {
736 c.bazelProdMode = true
737 } else if arg == "--bazel-mode-dev" {
738 c.bazelDevMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000739 } else if arg == "--bazel-mode-staging" {
740 c.bazelStagingMode = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700741 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700742 parseArgNum := func(def int) int {
743 if len(arg) > 2 {
744 p, err := strconv.ParseUint(arg[2:], 10, 31)
745 if err != nil {
746 ctx.Fatalf("Failed to parse %q: %v", arg, err)
747 }
748 return int(p)
749 } else if i+1 < len(args) {
750 p, err := strconv.ParseUint(args[i+1], 10, 31)
751 if err == nil {
752 i++
753 return int(p)
754 }
755 }
756 return def
757 }
758
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700759 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700760 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700761 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700762 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700763 } else {
764 ctx.Fatalln("Unknown option:", arg)
765 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700766 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700767 if k == "OUT_DIR" {
768 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
769 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700770 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700771 } else if arg == "dist" {
772 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200773 } else if arg == "json-module-graph" {
774 c.jsonModuleGraph = true
775 } else if arg == "bp2build" {
776 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000777 } else if arg == "api_bp2build" {
778 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200779 } else if arg == "queryview" {
780 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200781 } else if arg == "soong_docs" {
782 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700783 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700784 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800785 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700786 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700787 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700788 }
789 }
Chris Parsonsb6e96902022-10-31 20:08:45 -0400790 if (!c.bazelProdMode) && (!c.bazelDevMode) && (!c.bazelStagingMode) {
791 c.bazelProdMode = defaultBazelProdMode(c)
792 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700793}
794
Dan Willemsened869522018-01-08 14:58:46 -0800795func (c *configImpl) configureLocale(ctx Context) {
796 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
797 output, err := cmd.Output()
798
799 var locales []string
800 if err == nil {
801 locales = strings.Split(string(output), "\n")
802 } else {
803 // If we're unable to list the locales, let's assume en_US.UTF-8
804 locales = []string{"en_US.UTF-8"}
805 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
806 }
807
808 // gettext uses LANGUAGE, which is passed directly through
809
810 // For LANG and LC_*, only preserve the evaluated version of
811 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800812 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800813 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800814 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800815 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800816 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800817 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800818 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800819 }
820
821 c.environ.UnsetWithPrefix("LC_")
822
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800823 if userLang != "" {
824 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800825 }
826
827 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
828 // for others)
829 if inList("C.UTF-8", locales) {
830 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500831 } else if inList("C.utf8", locales) {
832 // These normalize to the same thing
833 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800834 } else if inList("en_US.UTF-8", locales) {
835 c.environ.Set("LANG", "en_US.UTF-8")
836 } else if inList("en_US.utf8", locales) {
837 // These normalize to the same thing
838 c.environ.Set("LANG", "en_US.UTF-8")
839 } else {
840 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
841 }
842}
843
Dan Willemsen1e704462016-08-21 15:17:17 -0700844func (c *configImpl) Environment() *Environment {
845 return c.environ
846}
847
848func (c *configImpl) Arguments() []string {
849 return c.arguments
850}
851
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200852func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200853 if len(c.Arguments()) > 0 {
854 // Explicit targets requested that are not special targets like b2pbuild
855 // or the JSON module graph
856 return true
857 }
858
Spandan Das5af0bd32022-09-28 20:43:08 +0000859 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200860 // Command line was empty, the default Ninja target is built
861 return true
862 }
863
Liz Kammer88677422021-12-15 15:03:19 -0500864 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
865 if c.Dist() && !c.Bp2Build() {
866 return true
867 }
868
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200869 // build.ninja doesn't need to be generated
870 return false
871}
872
Dan Willemsen1e704462016-08-21 15:17:17 -0700873func (c *configImpl) OutDir() string {
874 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700875 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700876 }
877 return "out"
878}
879
Dan Willemsen8a073a82017-02-04 17:30:44 -0800880func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400881 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000882}
883
884func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700885 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800886}
887
Dan Willemsen1e704462016-08-21 15:17:17 -0700888func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000889 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700890 return c.arguments
891 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700892 return c.ninjaArgs
893}
894
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500895func (c *configImpl) BazelOutDir() string {
896 return filepath.Join(c.OutDir(), "bazel")
897}
898
Dan Willemsen1e704462016-08-21 15:17:17 -0700899func (c *configImpl) SoongOutDir() string {
900 return filepath.Join(c.OutDir(), "soong")
901}
902
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200903func (c *configImpl) PrebuiltOS() string {
904 switch runtime.GOOS {
905 case "linux":
906 return "linux-x86"
907 case "darwin":
908 return "darwin-x86"
909 default:
910 panic("Unknown GOOS")
911 }
912}
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100913
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200914func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -0700915 if c.SkipKatiNinja() {
916 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
917 } else {
918 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
919 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200920}
921
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200922func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100923 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200924}
925
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200926func (c *configImpl) UsedEnvFile(tag string) string {
927 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
928}
929
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000930func (c *configImpl) Bp2BuildFilesMarkerFile() string {
931 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
932}
933
934func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100935 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200936}
937
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200938func (c *configImpl) SoongDocsHtml() string {
939 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
940}
941
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200942func (c *configImpl) QueryviewMarkerFile() string {
943 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
944}
945
Spandan Das5af0bd32022-09-28 20:43:08 +0000946func (c *configImpl) ApiBp2buildMarkerFile() string {
947 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
948}
949
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200950func (c *configImpl) ModuleGraphFile() string {
951 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
952}
953
kgui67007242022-01-25 13:50:25 +0800954func (c *configImpl) ModuleActionsFile() string {
955 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
956}
957
Jeff Gastonefc1b412017-03-29 17:29:06 -0700958func (c *configImpl) TempDir() string {
959 return shared.TempDirForOutDir(c.SoongOutDir())
960}
961
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700962func (c *configImpl) FileListDir() string {
963 return filepath.Join(c.OutDir(), ".module_paths")
964}
965
Dan Willemsen1e704462016-08-21 15:17:17 -0700966func (c *configImpl) KatiSuffix() string {
967 if c.katiSuffix != "" {
968 return c.katiSuffix
969 }
970 panic("SetKatiSuffix has not been called")
971}
972
Colin Cross37193492017-11-16 17:55:00 -0800973// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
974// user is interested in additional checks at the expense of build time.
975func (c *configImpl) Checkbuild() bool {
976 return c.checkbuild
977}
978
Dan Willemsen8a073a82017-02-04 17:30:44 -0800979func (c *configImpl) Dist() bool {
980 return c.dist
981}
982
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200983func (c *configImpl) JsonModuleGraph() bool {
984 return c.jsonModuleGraph
985}
986
987func (c *configImpl) Bp2Build() bool {
988 return c.bp2build
989}
990
Spandan Das5af0bd32022-09-28 20:43:08 +0000991func (c *configImpl) ApiBp2build() bool {
992 return c.apiBp2build
993}
994
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200995func (c *configImpl) Queryview() bool {
996 return c.queryview
997}
998
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200999func (c *configImpl) SoongDocs() bool {
1000 return c.soongDocs
1001}
1002
Dan Willemsen1e704462016-08-21 15:17:17 -07001003func (c *configImpl) IsVerbose() bool {
1004 return c.verbose
1005}
1006
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001007func (c *configImpl) SkipKati() bool {
1008 return c.skipKati
1009}
1010
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001011func (c *configImpl) SkipKatiNinja() bool {
1012 return c.skipKatiNinja
1013}
1014
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001015func (c *configImpl) SkipSoong() bool {
1016 return c.skipSoong
1017}
1018
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001019func (c *configImpl) SkipNinja() bool {
1020 return c.skipNinja
1021}
1022
Anton Hansson5a7861a2021-06-04 10:09:01 +01001023func (c *configImpl) SetSkipNinja(v bool) {
1024 c.skipNinja = v
1025}
1026
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001027func (c *configImpl) SkipConfig() bool {
1028 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001029}
1030
Dan Willemsen1e704462016-08-21 15:17:17 -07001031func (c *configImpl) TargetProduct() string {
1032 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1033 return v
1034 }
1035 panic("TARGET_PRODUCT is not defined")
1036}
1037
Dan Willemsen02781d52017-05-12 19:28:13 -07001038func (c *configImpl) TargetDevice() string {
1039 return c.targetDevice
1040}
1041
1042func (c *configImpl) SetTargetDevice(device string) {
1043 c.targetDevice = device
1044}
1045
1046func (c *configImpl) TargetBuildVariant() string {
1047 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1048 return v
1049 }
1050 panic("TARGET_BUILD_VARIANT is not defined")
1051}
1052
Dan Willemsen1e704462016-08-21 15:17:17 -07001053func (c *configImpl) KatiArgs() []string {
1054 return c.katiArgs
1055}
1056
1057func (c *configImpl) Parallel() int {
1058 return c.parallel
1059}
1060
Colin Cross8b8bec32019-11-15 13:18:43 -08001061func (c *configImpl) HighmemParallel() int {
1062 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1063 return i
1064 }
1065
1066 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1067 parallel := c.Parallel()
1068 if c.UseRemoteBuild() {
1069 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1070 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1071 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1072 // Return 1/16th of the size of the local pool, rounding up.
1073 return (parallel + 15) / 16
1074 } else if c.totalRAM == 0 {
1075 // Couldn't detect the total RAM, don't restrict highmem processes.
1076 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001077 } else if c.totalRAM <= 16*1024*1024*1024 {
1078 // Less than 16GB of ram, restrict to 1 highmem processes
1079 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001080 } else if c.totalRAM <= 32*1024*1024*1024 {
1081 // Less than 32GB of ram, restrict to 2 highmem processes
1082 return 2
1083 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1084 // If less than 8GB total RAM per process, reduce the number of highmem processes
1085 return p
1086 }
1087 // No restriction on highmem processes
1088 return parallel
1089}
1090
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001091func (c *configImpl) TotalRAM() uint64 {
1092 return c.totalRAM
1093}
1094
Kousik Kumarec478642020-09-21 13:39:24 -04001095// ForceUseGoma determines whether we should override Goma deprecation
1096// and use Goma for the current build or not.
1097func (c *configImpl) ForceUseGoma() bool {
1098 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1099 v = strings.TrimSpace(v)
1100 if v != "" && v != "false" {
1101 return true
1102 }
1103 }
1104 return false
1105}
1106
Dan Willemsen1e704462016-08-21 15:17:17 -07001107func (c *configImpl) UseGoma() bool {
1108 if v, ok := c.environ.Get("USE_GOMA"); ok {
1109 v = strings.TrimSpace(v)
1110 if v != "" && v != "false" {
1111 return true
1112 }
1113 }
1114 return false
1115}
1116
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001117func (c *configImpl) StartGoma() bool {
1118 if !c.UseGoma() {
1119 return false
1120 }
1121
1122 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1123 v = strings.TrimSpace(v)
1124 if v != "" && v != "false" {
1125 return false
1126 }
1127 }
1128 return true
1129}
1130
Ramy Medhatbbf25672019-07-17 12:30:04 +00001131func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001132 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001133 v = strings.TrimSpace(v)
1134 if v != "" && v != "false" {
1135 return true
1136 }
1137 }
1138 return false
1139}
1140
Chris Parsonsef615e52022-08-18 22:04:11 -04001141func (c *configImpl) BazelBuildEnabled() bool {
MarkDacekb78465d2022-10-18 20:10:16 +00001142 return c.bazelProdMode || c.bazelDevMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001143}
1144
Ramy Medhatbbf25672019-07-17 12:30:04 +00001145func (c *configImpl) StartRBE() bool {
1146 if !c.UseRBE() {
1147 return false
1148 }
1149
1150 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1151 v = strings.TrimSpace(v)
1152 if v != "" && v != "false" {
1153 return false
1154 }
1155 }
1156 return true
1157}
1158
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001159func (c *configImpl) rbeProxyLogsDir() string {
1160 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001161 if v, ok := c.environ.Get(f); ok {
1162 return v
1163 }
1164 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001165 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1166 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001167}
1168
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001169func (c *configImpl) shouldCleanupRBELogsDir() bool {
1170 // Perform a log directory cleanup only when the log directory
1171 // is auto created by the build rather than user-specified.
1172 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1173 if _, ok := c.environ.Get(f); ok {
1174 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001175 }
1176 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001177 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001178}
1179
1180func (c *configImpl) rbeExecRoot() string {
1181 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1182 if v, ok := c.environ.Get(f); ok {
1183 return v
1184 }
1185 }
1186 wd, err := os.Getwd()
1187 if err != nil {
1188 return ""
1189 }
1190 return wd
1191}
1192
1193func (c *configImpl) rbeDir() string {
1194 if v, ok := c.environ.Get("RBE_DIR"); ok {
1195 return v
1196 }
1197 return "prebuilts/remoteexecution-client/live/"
1198}
1199
1200func (c *configImpl) rbeReproxy() string {
1201 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1202 if v, ok := c.environ.Get(f); ok {
1203 return v
1204 }
1205 }
1206 return filepath.Join(c.rbeDir(), "reproxy")
1207}
1208
1209func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001210 credFlags := []string{
1211 "use_application_default_credentials",
1212 "use_gce_credentials",
1213 "credential_file",
1214 "use_google_prod_creds",
1215 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001216 for _, cf := range credFlags {
1217 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1218 if v, ok := c.environ.Get(f); ok {
1219 v = strings.TrimSpace(v)
1220 if v != "" && v != "false" && v != "0" {
1221 return "RBE_" + cf, v
1222 }
1223 }
1224 }
1225 }
1226 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001227}
1228
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001229func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1230 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1231 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1232
1233 name := filepath.Join(dir, base)
1234 if len(name) < maxNameLen {
1235 return name, nil
1236 }
1237
1238 name = filepath.Join("/tmp", base)
1239 if len(name) < maxNameLen {
1240 return name, nil
1241 }
1242
1243 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1244}
1245
Kousik Kumar7bc78192022-04-27 14:52:56 -04001246// IsGooglerEnvironment returns true if the current build is running
1247// on a Google developer machine and false otherwise.
1248func (c *configImpl) IsGooglerEnvironment() bool {
1249 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1250 if v, ok := c.environ.Get(cf); ok {
1251 return v == "googler"
1252 }
1253 return false
1254}
1255
1256// GoogleProdCredsExist determine whether credentials exist on the
1257// Googler machine to use remote execution.
1258func (c *configImpl) GoogleProdCredsExist() bool {
1259 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1260 return false
1261 }
1262 return true
1263}
1264
1265// UseRemoteBuild indicates whether to use a remote build acceleration system
1266// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001267func (c *configImpl) UseRemoteBuild() bool {
1268 return c.UseGoma() || c.UseRBE()
1269}
1270
Kousik Kumar7bc78192022-04-27 14:52:56 -04001271// StubbyExists checks whether the stubby binary exists on the machine running
1272// the build.
1273func (c *configImpl) StubbyExists() bool {
1274 if _, err := exec.LookPath("stubby"); err != nil {
1275 return false
1276 }
1277 return true
1278}
1279
Dan Willemsen1e704462016-08-21 15:17:17 -07001280// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001281// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001282// still limited by Parallel()
1283func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001284 if !c.UseRemoteBuild() {
1285 return 0
1286 }
1287 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1288 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001289 }
1290 return 500
1291}
1292
1293func (c *configImpl) SetKatiArgs(args []string) {
1294 c.katiArgs = args
1295}
1296
1297func (c *configImpl) SetNinjaArgs(args []string) {
1298 c.ninjaArgs = args
1299}
1300
1301func (c *configImpl) SetKatiSuffix(suffix string) {
1302 c.katiSuffix = suffix
1303}
1304
Dan Willemsene0879fc2017-08-04 15:06:27 -07001305func (c *configImpl) LastKatiSuffixFile() string {
1306 return filepath.Join(c.OutDir(), "last_kati_suffix")
1307}
1308
1309func (c *configImpl) HasKatiSuffix() bool {
1310 return c.katiSuffix != ""
1311}
1312
Dan Willemsen1e704462016-08-21 15:17:17 -07001313func (c *configImpl) KatiEnvFile() string {
1314 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1315}
1316
Dan Willemsen29971232018-09-26 14:58:30 -07001317func (c *configImpl) KatiBuildNinjaFile() string {
1318 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001319}
1320
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001321func (c *configImpl) KatiPackageNinjaFile() string {
1322 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1323}
1324
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001325func (c *configImpl) SoongVarsFile() string {
1326 return filepath.Join(c.SoongOutDir(), "soong.variables")
1327}
1328
Dan Willemsen1e704462016-08-21 15:17:17 -07001329func (c *configImpl) SoongNinjaFile() string {
1330 return filepath.Join(c.SoongOutDir(), "build.ninja")
1331}
1332
1333func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001334 if c.katiSuffix == "" {
1335 return filepath.Join(c.OutDir(), "combined.ninja")
1336 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001337 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1338}
1339
1340func (c *configImpl) SoongAndroidMk() string {
1341 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1342}
1343
1344func (c *configImpl) SoongMakeVarsMk() string {
1345 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1346}
1347
Dan Willemsenf052f782017-05-18 15:29:04 -07001348func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001349 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001350}
1351
Dan Willemsen02781d52017-05-12 19:28:13 -07001352func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001353 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1354}
1355
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001356func (c *configImpl) KatiPackageMkDir() string {
1357 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1358}
1359
Dan Willemsenf052f782017-05-18 15:29:04 -07001360func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001361 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001362}
1363
1364func (c *configImpl) HostOut() string {
1365 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1366}
1367
1368// This probably needs to be multi-valued, so not exporting it for now
1369func (c *configImpl) hostCrossOut() string {
1370 if runtime.GOOS == "linux" {
1371 return filepath.Join(c.hostOutRoot(), "windows-x86")
1372 } else {
1373 return ""
1374 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001375}
1376
Dan Willemsen1e704462016-08-21 15:17:17 -07001377func (c *configImpl) HostPrebuiltTag() string {
1378 if runtime.GOOS == "linux" {
1379 return "linux-x86"
1380 } else if runtime.GOOS == "darwin" {
1381 return "darwin-x86"
1382 } else {
1383 panic("Unsupported OS")
1384 }
1385}
Dan Willemsenf173d592017-04-27 14:28:00 -07001386
Dan Willemsen8122bd52017-10-12 20:20:41 -07001387func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001388 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1389 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001390 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1391 if _, err := os.Stat(asan); err == nil {
1392 return asan
1393 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001394 }
1395 }
1396 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1397}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001398
1399func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1400 c.brokenDupRules = val
1401}
1402
1403func (c *configImpl) BuildBrokenDupRules() bool {
1404 return c.brokenDupRules
1405}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001406
Dan Willemsen25e6f092019-04-09 10:22:43 -07001407func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1408 c.brokenUsesNetwork = val
1409}
1410
1411func (c *configImpl) BuildBrokenUsesNetwork() bool {
1412 return c.brokenUsesNetwork
1413}
1414
Dan Willemsene3336352020-01-02 19:10:38 -08001415func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1416 c.brokenNinjaEnvVars = val
1417}
1418
1419func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1420 return c.brokenNinjaEnvVars
1421}
1422
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001423func (c *configImpl) SetTargetDeviceDir(dir string) {
1424 c.targetDeviceDir = dir
1425}
1426
1427func (c *configImpl) TargetDeviceDir() string {
1428 return c.targetDeviceDir
1429}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001430
Patrice Arruda219eef32020-06-01 17:29:30 +00001431func (c *configImpl) BuildDateTime() string {
1432 return c.buildDateTime
1433}
1434
1435func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001436 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001437}
Patrice Arruda83842d72020-12-08 19:42:08 +00001438
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001439// LogsDir returns the absolute path to the logs directory where build log and
1440// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001441// directory. If the argument dist is specified, the logs directory
1442// is <dist_dir>/logs.
1443func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001444 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001445 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001446 // 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 -05001447 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001448 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001449 absDir, err := filepath.Abs(dir)
1450 if err != nil {
1451 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1452 os.Exit(1)
1453 }
1454 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001455}
1456
1457// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1458// where the bazel profiles are located.
1459func (c *configImpl) BazelMetricsDir() string {
1460 return filepath.Join(c.LogsDir(), "bazel_metrics")
1461}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001462
Chris Parsons53f68ae2022-03-03 12:01:40 -05001463// MkFileMetrics returns the file path for make-related metrics.
1464func (c *configImpl) MkMetrics() string {
1465 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1466}
1467
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001468func (c *configImpl) SetEmptyNinjaFile(v bool) {
1469 c.emptyNinjaFile = v
1470}
1471
1472func (c *configImpl) EmptyNinjaFile() bool {
1473 return c.emptyNinjaFile
1474}
Yu Liu6e13b402021-07-27 14:29:06 -07001475
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001476func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1477 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1478}
1479
Yu Liu6e13b402021-07-27 14:29:06 -07001480func GetMetricsUploader(topDir string, env *Environment) string {
1481 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1482 metricsUploader := filepath.Join(topDir, p)
1483 if _, err := os.Stat(metricsUploader); err == nil {
1484 return metricsUploader
1485 }
1486 }
1487
1488 return ""
1489}