blob: b38f2309213ae43378506241e6dc75d7919b1601 [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 }
249 // TODO(b/255364055): Flip this to true to enable bazel-mode by default
250 // for all users that don't opt out with BUILD_BROKEN_DISABLE_BAZEL.
251 return false
252}
253
Dan Willemsen1e704462016-08-21 15:17:17 -0700254func NewConfig(ctx Context, args ...string) Config {
255 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000256 environ: OsEnvironment(),
257 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700258 }
259
Patrice Arruda90109172020-07-28 18:07:27 +0000260 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700261 ret.parallel = runtime.NumCPU() + 2
262 ret.keepGoing = 1
263
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800264 ret.totalRAM = detectTotalRAM(ctx)
265
Dan Willemsen9b587492017-07-10 22:13:00 -0700266 ret.parseArgs(ctx, args)
267
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800268 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700269 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
270 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
271 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800272 outDir := "out"
273 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
274 if wd, err := os.Getwd(); err != nil {
275 ctx.Fatalln("Failed to get working directory:", err)
276 } else {
277 outDir = filepath.Join(baseDir, filepath.Base(wd))
278 }
279 }
280 ret.environ.Set("OUT_DIR", outDir)
281 }
282
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500283 // loadEnvConfig needs to know what the OUT_DIR is, so it should
284 // be called after we determine the appropriate out directory.
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500285 if err := loadEnvConfig(ctx, ret); err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500286 ctx.Fatalln("Failed to parse env config files: %v", err)
287 }
288
Dan Willemsen2d31a442018-10-20 21:33:41 -0700289 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
290 ret.distDir = filepath.Clean(distDir)
291 } else {
292 ret.distDir = filepath.Join(ret.OutDir(), "dist")
293 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700294
Spandan Das05063612021-06-25 01:39:04 +0000295 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
296 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
297 }
298
Dan Willemsen1e704462016-08-21 15:17:17 -0700299 ret.environ.Unset(
300 // We're already using it
301 "USE_SOONG_UI",
302
303 // We should never use GOROOT/GOPATH from the shell environment
304 "GOROOT",
305 "GOPATH",
306
307 // These should only come from Soong, not the environment.
308 "CLANG",
309 "CLANG_CXX",
310 "CCC_CC",
311 "CCC_CXX",
312
313 // Used by the goma compiler wrapper, but should only be set by
314 // gomacc
315 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800316
317 // We handle this above
318 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700319
Dan Willemsen2d31a442018-10-20 21:33:41 -0700320 // This is handled above too, and set for individual commands later
321 "DIST_DIR",
322
Dan Willemsen68a09852017-04-18 13:56:57 -0700323 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000324 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700325 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700326 "DISPLAY",
327 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700328 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700329 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700330
331 // Drop make flags
332 "MAKEFLAGS",
333 "MAKELEVEL",
334 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700335
336 // Set in envsetup.sh, reset in makefiles
337 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700338
339 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
340 "ANDROID_BUILD_TOP",
341 "ANDROID_HOST_OUT",
342 "ANDROID_PRODUCT_OUT",
343 "ANDROID_HOST_OUT_TESTCASES",
344 "ANDROID_TARGET_OUT_TESTCASES",
345 "ANDROID_TOOLCHAIN",
346 "ANDROID_TOOLCHAIN_2ND_ARCH",
347 "ANDROID_DEV_SCRIPTS",
348 "ANDROID_EMULATOR_PREBUILTS",
349 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700350 )
351
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400352 if ret.UseGoma() || ret.ForceUseGoma() {
353 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
354 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400355 }
356
Dan Willemsen1e704462016-08-21 15:17:17 -0700357 // Tell python not to spam the source tree with .pyc files.
358 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
359
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400360 tmpDir := absPath(ctx, ret.TempDir())
361 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800362
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700363 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
364 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
365 "llvm-binutils-stable/llvm-symbolizer")
366 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
367
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800368 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700369 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800370
Yu Liu6e13b402021-07-27 14:29:06 -0700371 srcDir := absPath(ctx, ".")
372 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700373 ctx.Println("You are building in a directory whose absolute path contains a space character:")
374 ctx.Println()
375 ctx.Printf("%q\n", srcDir)
376 ctx.Println()
377 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700378 }
379
Yu Liu6e13b402021-07-27 14:29:06 -0700380 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
381
Dan Willemsendb8457c2017-05-12 16:38:17 -0700382 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700383 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
384 ctx.Println()
385 ctx.Printf("%q\n", outDir)
386 ctx.Println()
387 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700388 }
389
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000390 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700391 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
392 ctx.Println()
393 ctx.Printf("%q\n", distDir)
394 ctx.Println()
395 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700396 }
397
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700398 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000399 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
400 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100401 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800402 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700403 javaHome := func() string {
404 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
405 return override
406 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000407 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
408 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 +0100409 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000410 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
411 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
412 }
413 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700414 }()
415 absJavaHome := absPath(ctx, javaHome)
416
Dan Willemsened869522018-01-08 14:58:46 -0800417 ret.configureLocale(ctx)
418
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700419 newPath := []string{filepath.Join(absJavaHome, "bin")}
420 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
421 newPath = append(newPath, path)
422 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100423
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700424 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
425 ret.environ.Set("JAVA_HOME", absJavaHome)
426 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000427 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
428 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100429 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700430 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
431
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800432 outDir := ret.OutDir()
433 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800434 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800435 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800436 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800437 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800438 }
Colin Cross28f527c2019-11-26 16:19:04 -0800439
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800440 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
441
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400442 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400443 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400444 ret.environ.Set(k, v)
445 }
446 }
447
Patrice Arruda83842d72020-12-08 19:42:08 +0000448 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800449 if err := os.RemoveAll(bpd); err != nil {
450 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
451 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000452
Patrice Arruda96850362020-08-11 20:41:11 +0000453 c := Config{ret}
454 storeConfigMetrics(ctx, c)
455 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700456}
457
Patrice Arruda13848222019-04-22 17:12:02 -0700458// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
459// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700460func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
461 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700462}
463
Patrice Arruda96850362020-08-11 20:41:11 +0000464// storeConfigMetrics selects a set of configuration information and store in
465// the metrics system for further analysis.
466func storeConfigMetrics(ctx Context, config Config) {
467 if ctx.Metrics == nil {
468 return
469 }
470
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400471 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000472
473 s := &smpb.SystemResourceInfo{
474 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
475 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
476 }
477 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000478}
479
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400480func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700481 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400482 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
483 UseGoma: proto.Bool(config.UseGoma()),
484 UseRbe: proto.Bool(config.UseRBE()),
485 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
486 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400487 }
Yu Liue737a992021-10-04 13:21:41 -0700488 c.Targets = append(c.Targets, config.arguments...)
489
490 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400491}
492
Patrice Arruda13848222019-04-22 17:12:02 -0700493// getConfigArgs processes the command arguments based on the build action and creates a set of new
494// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700495func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700496 // The next block of code verifies that the current directory is the root directory of the source
497 // tree. It then finds the relative path of dir based on the root directory of the source tree
498 // and verify that dir is inside of the source tree.
499 checkTopDir(ctx)
500 topDir, err := os.Getwd()
501 if err != nil {
502 ctx.Fatalf("Error retrieving top directory: %v", err)
503 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700504 dir, err = filepath.EvalSymlinks(dir)
505 if err != nil {
506 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
507 }
Patrice Arruda13848222019-04-22 17:12:02 -0700508 dir, err = filepath.Abs(dir)
509 if err != nil {
510 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
511 }
512 relDir, err := filepath.Rel(topDir, dir)
513 if err != nil {
514 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
515 }
516 // If there are ".." in the path, it's not in the source tree.
517 if strings.Contains(relDir, "..") {
518 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
519 }
520
521 configArgs := args[:]
522
523 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
524 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
525 targetNamePrefix := "MODULES-IN-"
526 if inList("GET-INSTALL-PATH", configArgs) {
527 targetNamePrefix = "GET-INSTALL-PATH-IN-"
528 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
529 }
530
Patrice Arruda13848222019-04-22 17:12:02 -0700531 var targets []string
532
533 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700534 case BUILD_MODULES:
535 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700536 case BUILD_MODULES_IN_A_DIRECTORY:
537 // If dir is the root source tree, all the modules are built of the source tree are built so
538 // no need to find the build file.
539 if topDir == dir {
540 break
541 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700542
Patrice Arruda13848222019-04-22 17:12:02 -0700543 buildFile := findBuildFile(ctx, relDir)
544 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700545 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700546 }
Patrice Arruda13848222019-04-22 17:12:02 -0700547 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
548 case BUILD_MODULES_IN_DIRECTORIES:
549 newConfigArgs, dirs := splitArgs(configArgs)
550 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700551 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700552 }
553
554 // Tidy only override all other specified targets.
555 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
556 if tidyOnly == "true" || tidyOnly == "1" {
557 configArgs = append(configArgs, "tidy_only")
558 } else {
559 configArgs = append(configArgs, targets...)
560 }
561
562 return configArgs
563}
564
565// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
566func convertToTarget(dir string, targetNamePrefix string) string {
567 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
568}
569
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700570// hasBuildFile returns true if dir contains an Android build file.
571func hasBuildFile(ctx Context, dir string) bool {
572 for _, buildFile := range buildFiles {
573 _, err := os.Stat(filepath.Join(dir, buildFile))
574 if err == nil {
575 return true
576 }
577 if !os.IsNotExist(err) {
578 ctx.Fatalf("Error retrieving the build file stats: %v", err)
579 }
580 }
581 return false
582}
583
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700584// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
585// in the current and any sub directory of dir. If a build file is not found, traverse the path
586// up by one directory and repeat again until either a build file is found or reached to the root
587// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
588// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700589func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700590 // If the string is empty or ".", assume it is top directory of the source tree.
591 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700592 return ""
593 }
594
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700595 found := false
596 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
597 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
598 if err != nil {
599 return err
600 }
601 if found {
602 return filepath.SkipDir
603 }
604 if info.IsDir() {
605 return nil
606 }
607 for _, buildFile := range buildFiles {
608 if info.Name() == buildFile {
609 found = true
610 return filepath.SkipDir
611 }
612 }
613 return nil
614 })
615 if err != nil {
616 ctx.Fatalf("Error finding Android build file: %v", err)
617 }
618
619 if found {
620 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700621 }
622 }
623
624 return ""
625}
626
627// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
628func splitArgs(args []string) (newArgs []string, dirs []string) {
629 specialArgs := map[string]bool{
630 "showcommands": true,
631 "snod": true,
632 "dist": true,
633 "checkbuild": true,
634 }
635
636 newArgs = []string{}
637 dirs = []string{}
638
639 for _, arg := range args {
640 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
641 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
642 newArgs = append(newArgs, arg)
643 continue
644 }
645
646 if _, ok := specialArgs[arg]; ok {
647 newArgs = append(newArgs, arg)
648 continue
649 }
650
651 dirs = append(dirs, arg)
652 }
653
654 return newArgs, dirs
655}
656
657// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
658// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
659// source root tree where the build action command was invoked. Each directory is validated if the
660// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700661func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700662 for _, dir := range dirs {
663 // The directory may have specified specific modules to build. ":" is the separator to separate
664 // the directory and the list of modules.
665 s := strings.Split(dir, ":")
666 l := len(s)
667 if l > 2 { // more than one ":" was specified.
668 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
669 }
670
671 dir = filepath.Join(relDir, s[0])
672 if _, err := os.Stat(dir); err != nil {
673 ctx.Fatalf("couldn't find directory %s", dir)
674 }
675
676 // Verify that if there are any targets specified after ":". Each target is separated by ",".
677 var newTargets []string
678 if l == 2 && s[1] != "" {
679 newTargets = strings.Split(s[1], ",")
680 if inList("", newTargets) {
681 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
682 }
683 }
684
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700685 // If there are specified targets to build in dir, an android build file must exist for the one
686 // shot build. For the non-targets case, find the appropriate build file and build all the
687 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700688 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700689 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700690 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
691 }
692 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700693 buildFile := findBuildFile(ctx, dir)
694 if buildFile == "" {
695 ctx.Fatalf("Build file not found for %s directory", dir)
696 }
697 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700698 }
699
Patrice Arruda13848222019-04-22 17:12:02 -0700700 targets = append(targets, newTargets...)
701 }
702
Dan Willemsence41e942019-07-29 23:39:30 -0700703 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700704}
705
Dan Willemsen9b587492017-07-10 22:13:00 -0700706func (c *configImpl) parseArgs(ctx Context, args []string) {
707 for i := 0; i < len(args); i++ {
708 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100709 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700710 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200711 } else if arg == "--empty-ninja-file" {
712 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100713 } else if arg == "--skip-ninja" {
714 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700715 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700716 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
717 // but it does run a Kati ninja file if the .kati_enabled marker file was created
718 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000719 c.skipConfig = true
720 c.skipKati = true
721 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100722 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000723 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100724 } else if arg == "--soong-only" {
725 c.skipKati = true
726 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200727 } else if arg == "--config-only" {
728 c.skipKati = true
729 c.skipKatiNinja = true
730 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700731 } else if arg == "--skip-config" {
732 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700733 } else if arg == "--skip-soong-tests" {
734 c.skipSoongTests = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500735 } else if arg == "--mk-metrics" {
736 c.reportMkMetrics = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400737 } else if arg == "--bazel-mode" {
738 c.bazelProdMode = true
739 } else if arg == "--bazel-mode-dev" {
740 c.bazelDevMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000741 } else if arg == "--bazel-mode-staging" {
742 c.bazelStagingMode = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700743 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700744 parseArgNum := func(def int) int {
745 if len(arg) > 2 {
746 p, err := strconv.ParseUint(arg[2:], 10, 31)
747 if err != nil {
748 ctx.Fatalf("Failed to parse %q: %v", arg, err)
749 }
750 return int(p)
751 } else if i+1 < len(args) {
752 p, err := strconv.ParseUint(args[i+1], 10, 31)
753 if err == nil {
754 i++
755 return int(p)
756 }
757 }
758 return def
759 }
760
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700761 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700762 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700763 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700764 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700765 } else {
766 ctx.Fatalln("Unknown option:", arg)
767 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700768 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700769 if k == "OUT_DIR" {
770 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
771 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700772 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700773 } else if arg == "dist" {
774 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200775 } else if arg == "json-module-graph" {
776 c.jsonModuleGraph = true
777 } else if arg == "bp2build" {
778 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000779 } else if arg == "api_bp2build" {
780 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200781 } else if arg == "queryview" {
782 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200783 } else if arg == "soong_docs" {
784 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700785 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700786 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800787 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700788 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700789 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700790 }
791 }
Chris Parsonsb6e96902022-10-31 20:08:45 -0400792 if (!c.bazelProdMode) && (!c.bazelDevMode) && (!c.bazelStagingMode) {
793 c.bazelProdMode = defaultBazelProdMode(c)
794 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700795}
796
Dan Willemsened869522018-01-08 14:58:46 -0800797func (c *configImpl) configureLocale(ctx Context) {
798 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
799 output, err := cmd.Output()
800
801 var locales []string
802 if err == nil {
803 locales = strings.Split(string(output), "\n")
804 } else {
805 // If we're unable to list the locales, let's assume en_US.UTF-8
806 locales = []string{"en_US.UTF-8"}
807 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
808 }
809
810 // gettext uses LANGUAGE, which is passed directly through
811
812 // For LANG and LC_*, only preserve the evaluated version of
813 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800814 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800815 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800816 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800817 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800818 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800819 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800820 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800821 }
822
823 c.environ.UnsetWithPrefix("LC_")
824
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800825 if userLang != "" {
826 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800827 }
828
829 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
830 // for others)
831 if inList("C.UTF-8", locales) {
832 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500833 } else if inList("C.utf8", locales) {
834 // These normalize to the same thing
835 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800836 } else if inList("en_US.UTF-8", locales) {
837 c.environ.Set("LANG", "en_US.UTF-8")
838 } else if inList("en_US.utf8", locales) {
839 // These normalize to the same thing
840 c.environ.Set("LANG", "en_US.UTF-8")
841 } else {
842 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
843 }
844}
845
Dan Willemsen1e704462016-08-21 15:17:17 -0700846func (c *configImpl) Environment() *Environment {
847 return c.environ
848}
849
850func (c *configImpl) Arguments() []string {
851 return c.arguments
852}
853
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200854func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200855 if len(c.Arguments()) > 0 {
856 // Explicit targets requested that are not special targets like b2pbuild
857 // or the JSON module graph
858 return true
859 }
860
Spandan Das5af0bd32022-09-28 20:43:08 +0000861 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200862 // Command line was empty, the default Ninja target is built
863 return true
864 }
865
Liz Kammer88677422021-12-15 15:03:19 -0500866 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
867 if c.Dist() && !c.Bp2Build() {
868 return true
869 }
870
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200871 // build.ninja doesn't need to be generated
872 return false
873}
874
Dan Willemsen1e704462016-08-21 15:17:17 -0700875func (c *configImpl) OutDir() string {
876 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700877 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700878 }
879 return "out"
880}
881
Dan Willemsen8a073a82017-02-04 17:30:44 -0800882func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400883 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000884}
885
886func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700887 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800888}
889
Dan Willemsen1e704462016-08-21 15:17:17 -0700890func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000891 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700892 return c.arguments
893 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700894 return c.ninjaArgs
895}
896
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500897func (c *configImpl) BazelOutDir() string {
898 return filepath.Join(c.OutDir(), "bazel")
899}
900
Dan Willemsen1e704462016-08-21 15:17:17 -0700901func (c *configImpl) SoongOutDir() string {
902 return filepath.Join(c.OutDir(), "soong")
903}
904
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200905func (c *configImpl) PrebuiltOS() string {
906 switch runtime.GOOS {
907 case "linux":
908 return "linux-x86"
909 case "darwin":
910 return "darwin-x86"
911 default:
912 panic("Unknown GOOS")
913 }
914}
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100915
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200916func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -0700917 if c.SkipKatiNinja() {
918 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
919 } else {
920 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
921 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200922}
923
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200924func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100925 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200926}
927
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200928func (c *configImpl) UsedEnvFile(tag string) string {
929 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
930}
931
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000932func (c *configImpl) Bp2BuildFilesMarkerFile() string {
933 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
934}
935
936func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100937 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200938}
939
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200940func (c *configImpl) SoongDocsHtml() string {
941 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
942}
943
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200944func (c *configImpl) QueryviewMarkerFile() string {
945 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
946}
947
Spandan Das5af0bd32022-09-28 20:43:08 +0000948func (c *configImpl) ApiBp2buildMarkerFile() string {
949 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
950}
951
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200952func (c *configImpl) ModuleGraphFile() string {
953 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
954}
955
kgui67007242022-01-25 13:50:25 +0800956func (c *configImpl) ModuleActionsFile() string {
957 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
958}
959
Jeff Gastonefc1b412017-03-29 17:29:06 -0700960func (c *configImpl) TempDir() string {
961 return shared.TempDirForOutDir(c.SoongOutDir())
962}
963
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700964func (c *configImpl) FileListDir() string {
965 return filepath.Join(c.OutDir(), ".module_paths")
966}
967
Dan Willemsen1e704462016-08-21 15:17:17 -0700968func (c *configImpl) KatiSuffix() string {
969 if c.katiSuffix != "" {
970 return c.katiSuffix
971 }
972 panic("SetKatiSuffix has not been called")
973}
974
Colin Cross37193492017-11-16 17:55:00 -0800975// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
976// user is interested in additional checks at the expense of build time.
977func (c *configImpl) Checkbuild() bool {
978 return c.checkbuild
979}
980
Dan Willemsen8a073a82017-02-04 17:30:44 -0800981func (c *configImpl) Dist() bool {
982 return c.dist
983}
984
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200985func (c *configImpl) JsonModuleGraph() bool {
986 return c.jsonModuleGraph
987}
988
989func (c *configImpl) Bp2Build() bool {
990 return c.bp2build
991}
992
Spandan Das5af0bd32022-09-28 20:43:08 +0000993func (c *configImpl) ApiBp2build() bool {
994 return c.apiBp2build
995}
996
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200997func (c *configImpl) Queryview() bool {
998 return c.queryview
999}
1000
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001001func (c *configImpl) SoongDocs() bool {
1002 return c.soongDocs
1003}
1004
Dan Willemsen1e704462016-08-21 15:17:17 -07001005func (c *configImpl) IsVerbose() bool {
1006 return c.verbose
1007}
1008
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001009func (c *configImpl) SkipKati() bool {
1010 return c.skipKati
1011}
1012
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001013func (c *configImpl) SkipKatiNinja() bool {
1014 return c.skipKatiNinja
1015}
1016
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001017func (c *configImpl) SkipSoong() bool {
1018 return c.skipSoong
1019}
1020
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001021func (c *configImpl) SkipNinja() bool {
1022 return c.skipNinja
1023}
1024
Anton Hansson5a7861a2021-06-04 10:09:01 +01001025func (c *configImpl) SetSkipNinja(v bool) {
1026 c.skipNinja = v
1027}
1028
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001029func (c *configImpl) SkipConfig() bool {
1030 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001031}
1032
Dan Willemsen1e704462016-08-21 15:17:17 -07001033func (c *configImpl) TargetProduct() string {
1034 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1035 return v
1036 }
1037 panic("TARGET_PRODUCT is not defined")
1038}
1039
Dan Willemsen02781d52017-05-12 19:28:13 -07001040func (c *configImpl) TargetDevice() string {
1041 return c.targetDevice
1042}
1043
1044func (c *configImpl) SetTargetDevice(device string) {
1045 c.targetDevice = device
1046}
1047
1048func (c *configImpl) TargetBuildVariant() string {
1049 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1050 return v
1051 }
1052 panic("TARGET_BUILD_VARIANT is not defined")
1053}
1054
Dan Willemsen1e704462016-08-21 15:17:17 -07001055func (c *configImpl) KatiArgs() []string {
1056 return c.katiArgs
1057}
1058
1059func (c *configImpl) Parallel() int {
1060 return c.parallel
1061}
1062
Colin Cross8b8bec32019-11-15 13:18:43 -08001063func (c *configImpl) HighmemParallel() int {
1064 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1065 return i
1066 }
1067
1068 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1069 parallel := c.Parallel()
1070 if c.UseRemoteBuild() {
1071 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1072 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1073 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1074 // Return 1/16th of the size of the local pool, rounding up.
1075 return (parallel + 15) / 16
1076 } else if c.totalRAM == 0 {
1077 // Couldn't detect the total RAM, don't restrict highmem processes.
1078 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001079 } else if c.totalRAM <= 16*1024*1024*1024 {
1080 // Less than 16GB of ram, restrict to 1 highmem processes
1081 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001082 } else if c.totalRAM <= 32*1024*1024*1024 {
1083 // Less than 32GB of ram, restrict to 2 highmem processes
1084 return 2
1085 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1086 // If less than 8GB total RAM per process, reduce the number of highmem processes
1087 return p
1088 }
1089 // No restriction on highmem processes
1090 return parallel
1091}
1092
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001093func (c *configImpl) TotalRAM() uint64 {
1094 return c.totalRAM
1095}
1096
Kousik Kumarec478642020-09-21 13:39:24 -04001097// ForceUseGoma determines whether we should override Goma deprecation
1098// and use Goma for the current build or not.
1099func (c *configImpl) ForceUseGoma() bool {
1100 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1101 v = strings.TrimSpace(v)
1102 if v != "" && v != "false" {
1103 return true
1104 }
1105 }
1106 return false
1107}
1108
Dan Willemsen1e704462016-08-21 15:17:17 -07001109func (c *configImpl) UseGoma() bool {
1110 if v, ok := c.environ.Get("USE_GOMA"); ok {
1111 v = strings.TrimSpace(v)
1112 if v != "" && v != "false" {
1113 return true
1114 }
1115 }
1116 return false
1117}
1118
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001119func (c *configImpl) StartGoma() bool {
1120 if !c.UseGoma() {
1121 return false
1122 }
1123
1124 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1125 v = strings.TrimSpace(v)
1126 if v != "" && v != "false" {
1127 return false
1128 }
1129 }
1130 return true
1131}
1132
Ramy Medhatbbf25672019-07-17 12:30:04 +00001133func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001134 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001135 v = strings.TrimSpace(v)
1136 if v != "" && v != "false" {
1137 return true
1138 }
1139 }
1140 return false
1141}
1142
Chris Parsonsef615e52022-08-18 22:04:11 -04001143func (c *configImpl) BazelBuildEnabled() bool {
MarkDacekb78465d2022-10-18 20:10:16 +00001144 return c.bazelProdMode || c.bazelDevMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001145}
1146
Ramy Medhatbbf25672019-07-17 12:30:04 +00001147func (c *configImpl) StartRBE() bool {
1148 if !c.UseRBE() {
1149 return false
1150 }
1151
1152 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1153 v = strings.TrimSpace(v)
1154 if v != "" && v != "false" {
1155 return false
1156 }
1157 }
1158 return true
1159}
1160
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001161func (c *configImpl) rbeProxyLogsDir() string {
1162 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001163 if v, ok := c.environ.Get(f); ok {
1164 return v
1165 }
1166 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001167 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1168 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001169}
1170
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001171func (c *configImpl) shouldCleanupRBELogsDir() bool {
1172 // Perform a log directory cleanup only when the log directory
1173 // is auto created by the build rather than user-specified.
1174 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1175 if _, ok := c.environ.Get(f); ok {
1176 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001177 }
1178 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001179 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001180}
1181
1182func (c *configImpl) rbeExecRoot() string {
1183 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1184 if v, ok := c.environ.Get(f); ok {
1185 return v
1186 }
1187 }
1188 wd, err := os.Getwd()
1189 if err != nil {
1190 return ""
1191 }
1192 return wd
1193}
1194
1195func (c *configImpl) rbeDir() string {
1196 if v, ok := c.environ.Get("RBE_DIR"); ok {
1197 return v
1198 }
1199 return "prebuilts/remoteexecution-client/live/"
1200}
1201
1202func (c *configImpl) rbeReproxy() string {
1203 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1204 if v, ok := c.environ.Get(f); ok {
1205 return v
1206 }
1207 }
1208 return filepath.Join(c.rbeDir(), "reproxy")
1209}
1210
1211func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001212 credFlags := []string{
1213 "use_application_default_credentials",
1214 "use_gce_credentials",
1215 "credential_file",
1216 "use_google_prod_creds",
1217 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001218 for _, cf := range credFlags {
1219 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1220 if v, ok := c.environ.Get(f); ok {
1221 v = strings.TrimSpace(v)
1222 if v != "" && v != "false" && v != "0" {
1223 return "RBE_" + cf, v
1224 }
1225 }
1226 }
1227 }
1228 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001229}
1230
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001231func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1232 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1233 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1234
1235 name := filepath.Join(dir, base)
1236 if len(name) < maxNameLen {
1237 return name, nil
1238 }
1239
1240 name = filepath.Join("/tmp", base)
1241 if len(name) < maxNameLen {
1242 return name, nil
1243 }
1244
1245 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1246}
1247
Kousik Kumar7bc78192022-04-27 14:52:56 -04001248// IsGooglerEnvironment returns true if the current build is running
1249// on a Google developer machine and false otherwise.
1250func (c *configImpl) IsGooglerEnvironment() bool {
1251 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1252 if v, ok := c.environ.Get(cf); ok {
1253 return v == "googler"
1254 }
1255 return false
1256}
1257
1258// GoogleProdCredsExist determine whether credentials exist on the
1259// Googler machine to use remote execution.
1260func (c *configImpl) GoogleProdCredsExist() bool {
1261 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1262 return false
1263 }
1264 return true
1265}
1266
1267// UseRemoteBuild indicates whether to use a remote build acceleration system
1268// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001269func (c *configImpl) UseRemoteBuild() bool {
1270 return c.UseGoma() || c.UseRBE()
1271}
1272
Kousik Kumar7bc78192022-04-27 14:52:56 -04001273// StubbyExists checks whether the stubby binary exists on the machine running
1274// the build.
1275func (c *configImpl) StubbyExists() bool {
1276 if _, err := exec.LookPath("stubby"); err != nil {
1277 return false
1278 }
1279 return true
1280}
1281
Dan Willemsen1e704462016-08-21 15:17:17 -07001282// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001283// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001284// still limited by Parallel()
1285func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001286 if !c.UseRemoteBuild() {
1287 return 0
1288 }
1289 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1290 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001291 }
1292 return 500
1293}
1294
1295func (c *configImpl) SetKatiArgs(args []string) {
1296 c.katiArgs = args
1297}
1298
1299func (c *configImpl) SetNinjaArgs(args []string) {
1300 c.ninjaArgs = args
1301}
1302
1303func (c *configImpl) SetKatiSuffix(suffix string) {
1304 c.katiSuffix = suffix
1305}
1306
Dan Willemsene0879fc2017-08-04 15:06:27 -07001307func (c *configImpl) LastKatiSuffixFile() string {
1308 return filepath.Join(c.OutDir(), "last_kati_suffix")
1309}
1310
1311func (c *configImpl) HasKatiSuffix() bool {
1312 return c.katiSuffix != ""
1313}
1314
Dan Willemsen1e704462016-08-21 15:17:17 -07001315func (c *configImpl) KatiEnvFile() string {
1316 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1317}
1318
Dan Willemsen29971232018-09-26 14:58:30 -07001319func (c *configImpl) KatiBuildNinjaFile() string {
1320 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001321}
1322
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001323func (c *configImpl) KatiPackageNinjaFile() string {
1324 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1325}
1326
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001327func (c *configImpl) SoongVarsFile() string {
1328 return filepath.Join(c.SoongOutDir(), "soong.variables")
1329}
1330
Dan Willemsen1e704462016-08-21 15:17:17 -07001331func (c *configImpl) SoongNinjaFile() string {
1332 return filepath.Join(c.SoongOutDir(), "build.ninja")
1333}
1334
1335func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001336 if c.katiSuffix == "" {
1337 return filepath.Join(c.OutDir(), "combined.ninja")
1338 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001339 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1340}
1341
1342func (c *configImpl) SoongAndroidMk() string {
1343 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1344}
1345
1346func (c *configImpl) SoongMakeVarsMk() string {
1347 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1348}
1349
Dan Willemsenf052f782017-05-18 15:29:04 -07001350func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001351 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001352}
1353
Dan Willemsen02781d52017-05-12 19:28:13 -07001354func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001355 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1356}
1357
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001358func (c *configImpl) KatiPackageMkDir() string {
1359 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1360}
1361
Dan Willemsenf052f782017-05-18 15:29:04 -07001362func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001363 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001364}
1365
1366func (c *configImpl) HostOut() string {
1367 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1368}
1369
1370// This probably needs to be multi-valued, so not exporting it for now
1371func (c *configImpl) hostCrossOut() string {
1372 if runtime.GOOS == "linux" {
1373 return filepath.Join(c.hostOutRoot(), "windows-x86")
1374 } else {
1375 return ""
1376 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001377}
1378
Dan Willemsen1e704462016-08-21 15:17:17 -07001379func (c *configImpl) HostPrebuiltTag() string {
1380 if runtime.GOOS == "linux" {
1381 return "linux-x86"
1382 } else if runtime.GOOS == "darwin" {
1383 return "darwin-x86"
1384 } else {
1385 panic("Unsupported OS")
1386 }
1387}
Dan Willemsenf173d592017-04-27 14:28:00 -07001388
Dan Willemsen8122bd52017-10-12 20:20:41 -07001389func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001390 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1391 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001392 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1393 if _, err := os.Stat(asan); err == nil {
1394 return asan
1395 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001396 }
1397 }
1398 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1399}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001400
1401func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1402 c.brokenDupRules = val
1403}
1404
1405func (c *configImpl) BuildBrokenDupRules() bool {
1406 return c.brokenDupRules
1407}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001408
Dan Willemsen25e6f092019-04-09 10:22:43 -07001409func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1410 c.brokenUsesNetwork = val
1411}
1412
1413func (c *configImpl) BuildBrokenUsesNetwork() bool {
1414 return c.brokenUsesNetwork
1415}
1416
Dan Willemsene3336352020-01-02 19:10:38 -08001417func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1418 c.brokenNinjaEnvVars = val
1419}
1420
1421func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1422 return c.brokenNinjaEnvVars
1423}
1424
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001425func (c *configImpl) SetTargetDeviceDir(dir string) {
1426 c.targetDeviceDir = dir
1427}
1428
1429func (c *configImpl) TargetDeviceDir() string {
1430 return c.targetDeviceDir
1431}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001432
Patrice Arruda219eef32020-06-01 17:29:30 +00001433func (c *configImpl) BuildDateTime() string {
1434 return c.buildDateTime
1435}
1436
1437func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001438 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001439}
Patrice Arruda83842d72020-12-08 19:42:08 +00001440
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001441// LogsDir returns the absolute path to the logs directory where build log and
1442// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001443// directory. If the argument dist is specified, the logs directory
1444// is <dist_dir>/logs.
1445func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001446 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001447 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001448 // 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 -05001449 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001450 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001451 absDir, err := filepath.Abs(dir)
1452 if err != nil {
1453 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1454 os.Exit(1)
1455 }
1456 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001457}
1458
1459// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1460// where the bazel profiles are located.
1461func (c *configImpl) BazelMetricsDir() string {
1462 return filepath.Join(c.LogsDir(), "bazel_metrics")
1463}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001464
Chris Parsons53f68ae2022-03-03 12:01:40 -05001465// MkFileMetrics returns the file path for make-related metrics.
1466func (c *configImpl) MkMetrics() string {
1467 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1468}
1469
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001470func (c *configImpl) SetEmptyNinjaFile(v bool) {
1471 c.emptyNinjaFile = v
1472}
1473
1474func (c *configImpl) EmptyNinjaFile() bool {
1475 return c.emptyNinjaFile
1476}
Yu Liu6e13b402021-07-27 14:29:06 -07001477
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001478func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1479 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1480}
1481
Yu Liu6e13b402021-07-27 14:29:06 -07001482func GetMetricsUploader(topDir string, env *Environment) string {
1483 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1484 metricsUploader := filepath.Join(topDir, p)
1485 if _, err := os.Stat(metricsUploader); err == nil {
1486 return metricsUploader
1487 }
1488 }
1489
1490 return ""
1491}