blob: 7651a0fdf2aa3dfac30e7d013e47d4d1467da942 [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
Spandan Das394aa322022-11-03 17:02:10 +000085 searchApiDir bool // Scan the Android.bp files generated in out/api_surfaces
Dan Willemsen1e704462016-08-21 15:17:17 -070086
87 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070088 katiArgs []string
89 ninjaArgs []string
90 katiSuffix string
91 targetDevice string
92 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +000093 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -070094
Dan Willemsen2bb82d02019-12-27 09:35:42 -080095 // Autodetected
96 totalRAM uint64
97
Dan Willemsene3336352020-01-02 19:10:38 -080098 brokenDupRules bool
99 brokenUsesNetwork bool
100 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -0700101
102 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000103
MarkDacekb78465d2022-10-18 20:10:16 +0000104 bazelProdMode bool
105 bazelDevMode bool
106 bazelStagingMode bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000107
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700108 // Set by multiproduct_kati
109 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700110
111 metricsUploader string
MarkDacekd06db5d2022-11-29 00:47:59 +0000112
113 bazelForceEnabledModules string
Dan Willemsen1e704462016-08-21 15:17:17 -0700114}
115
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800116const srcDirFileCheck = "build/soong/root.bp"
117
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700118var buildFiles = []string{"Android.mk", "Android.bp"}
119
Patrice Arruda13848222019-04-22 17:12:02 -0700120type BuildAction uint
121
122const (
123 // Builds all of the modules and their dependencies of a specified directory, relative to the root
124 // directory of the source tree.
125 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
126
127 // Builds all of the modules and their dependencies of a list of specified directories. All specified
128 // directories are relative to the root directory of the source tree.
129 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700130
131 // Build a list of specified modules. If none was specified, simply build the whole source tree.
132 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700133)
134
135// checkTopDir validates that the current directory is at the root directory of the source tree.
136func checkTopDir(ctx Context) {
137 if _, err := os.Stat(srcDirFileCheck); err != nil {
138 if os.IsNotExist(err) {
139 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
140 }
141 ctx.Fatalln("Error verifying tree state:", err)
142 }
143}
144
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500145// fetchEnvConfig optionally fetches environment config from an
146// experiments system to control Soong features dynamically.
147func fetchEnvConfig(ctx Context, config *configImpl, envConfigName string) error {
David Goldsmith62243a32022-04-08 13:42:04 +0000148 configName := envConfigName + "." + jsonSuffix
Kousik Kumarc75e1292022-07-07 02:20:51 +0000149 expConfigFetcher := &smpb.ExpConfigFetcher{Filename: &configName}
David Goldsmith62243a32022-04-08 13:42:04 +0000150 defer func() {
151 ctx.Metrics.ExpConfigFetcher(expConfigFetcher)
152 }()
Kousik Kumarc75e1292022-07-07 02:20:51 +0000153 if !config.GoogleProdCredsExist() {
154 status := smpb.ExpConfigFetcher_MISSING_GCERT
155 expConfigFetcher.Status = &status
156 return nil
157 }
David Goldsmith62243a32022-04-08 13:42:04 +0000158
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500159 s, err := os.Stat(configFetcher)
160 if err != nil {
161 if os.IsNotExist(err) {
162 return nil
163 }
164 return err
165 }
166 if s.Mode()&0111 == 0 {
David Goldsmith62243a32022-04-08 13:42:04 +0000167 status := smpb.ExpConfigFetcher_ERROR
168 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500169 return fmt.Errorf("configuration fetcher binary %v is not executable: %v", configFetcher, s.Mode())
170 }
171
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500172 tCtx, cancel := context.WithTimeout(ctx, envConfigFetchTimeout)
173 defer cancel()
David Goldsmith62243a32022-04-08 13:42:04 +0000174 fetchStart := time.Now()
175 cmd := exec.CommandContext(tCtx, configFetcher, "-output_config_dir", config.OutDir(),
176 "-output_config_name", configName)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500177 if err := cmd.Start(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000178 status := smpb.ExpConfigFetcher_ERROR
179 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500180 return err
181 }
182
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500183 if err := cmd.Wait(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000184 status := smpb.ExpConfigFetcher_ERROR
185 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500186 return err
187 }
David Goldsmith62243a32022-04-08 13:42:04 +0000188 fetchEnd := time.Now()
189 expConfigFetcher.Micros = proto.Uint64(uint64(fetchEnd.Sub(fetchStart).Microseconds()))
190 outConfigFilePath := filepath.Join(config.OutDir(), configName)
191 expConfigFetcher.Filename = proto.String(outConfigFilePath)
192 if _, err := os.Stat(outConfigFilePath); err == nil {
193 status := smpb.ExpConfigFetcher_CONFIG
194 expConfigFetcher.Status = &status
195 } else {
196 status := smpb.ExpConfigFetcher_NO_CONFIG
197 expConfigFetcher.Status = &status
198 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500199 return nil
200}
201
202func loadEnvConfig(ctx Context, config *configImpl) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500203 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
204 if bc == "" {
205 return nil
206 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500207
208 if err := fetchEnvConfig(ctx, config, bc); err != nil {
Kousik Kumar595fb1c2022-06-24 16:49:52 +0000209 ctx.Verbosef("Failed to fetch config file: %v\n", err)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500210 }
211
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500212 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500213 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500214 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500215 envConfigDir,
216 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500217 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500218 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
219 envVarsJSON, err := ioutil.ReadFile(cfgFile)
220 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500221 continue
222 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500223 ctx.Verbosef("Loading config file %v\n", cfgFile)
224 var envVars map[string]map[string]string
225 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
226 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
227 continue
228 }
229 for k, v := range envVars["env"] {
230 if os.Getenv(k) != "" {
231 continue
232 }
233 config.environ.Set(k, v)
234 }
235 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
236 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500237 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500238
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500239 return nil
240}
241
Chris Parsonsb6e96902022-10-31 20:08:45 -0400242func defaultBazelProdMode(cfg *configImpl) bool {
MarkDacekd06db5d2022-11-29 00:47:59 +0000243 // Environment flag to disable Bazel for users which experience
Chris Parsonsb6e96902022-10-31 20:08:45 -0400244 // broken bazel-handled builds, or significant performance regressions.
245 if cfg.IsBazelMixedBuildForceDisabled() {
246 return false
247 }
248 // Darwin-host builds are currently untested with Bazel.
249 if runtime.GOOS == "darwin" {
250 return false
251 }
Chris Parsons035e03a2022-11-01 14:25:45 -0400252 return true
Chris Parsonsb6e96902022-10-31 20:08:45 -0400253}
254
Dan Willemsen1e704462016-08-21 15:17:17 -0700255func NewConfig(ctx Context, args ...string) Config {
256 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000257 environ: OsEnvironment(),
258 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700259 }
260
Patrice Arruda90109172020-07-28 18:07:27 +0000261 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700262 ret.parallel = runtime.NumCPU() + 2
263 ret.keepGoing = 1
264
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800265 ret.totalRAM = detectTotalRAM(ctx)
266
Dan Willemsen9b587492017-07-10 22:13:00 -0700267 ret.parseArgs(ctx, args)
268
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800269 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700270 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
271 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
272 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800273 outDir := "out"
274 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
275 if wd, err := os.Getwd(); err != nil {
276 ctx.Fatalln("Failed to get working directory:", err)
277 } else {
278 outDir = filepath.Join(baseDir, filepath.Base(wd))
279 }
280 }
281 ret.environ.Set("OUT_DIR", outDir)
282 }
283
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500284 // loadEnvConfig needs to know what the OUT_DIR is, so it should
285 // be called after we determine the appropriate out directory.
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500286 if err := loadEnvConfig(ctx, ret); err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500287 ctx.Fatalln("Failed to parse env config files: %v", err)
288 }
289
Dan Willemsen2d31a442018-10-20 21:33:41 -0700290 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
291 ret.distDir = filepath.Clean(distDir)
292 } else {
293 ret.distDir = filepath.Join(ret.OutDir(), "dist")
294 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700295
Spandan Das05063612021-06-25 01:39:04 +0000296 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
297 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
298 }
299
Dan Willemsen1e704462016-08-21 15:17:17 -0700300 ret.environ.Unset(
301 // We're already using it
302 "USE_SOONG_UI",
303
304 // We should never use GOROOT/GOPATH from the shell environment
305 "GOROOT",
306 "GOPATH",
307
308 // These should only come from Soong, not the environment.
309 "CLANG",
310 "CLANG_CXX",
311 "CCC_CC",
312 "CCC_CXX",
313
314 // Used by the goma compiler wrapper, but should only be set by
315 // gomacc
316 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800317
318 // We handle this above
319 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700320
Dan Willemsen2d31a442018-10-20 21:33:41 -0700321 // This is handled above too, and set for individual commands later
322 "DIST_DIR",
323
Dan Willemsen68a09852017-04-18 13:56:57 -0700324 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000325 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700326 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700327 "DISPLAY",
328 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700329 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700330 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700331
332 // Drop make flags
333 "MAKEFLAGS",
334 "MAKELEVEL",
335 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700336
337 // Set in envsetup.sh, reset in makefiles
338 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700339
340 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
341 "ANDROID_BUILD_TOP",
342 "ANDROID_HOST_OUT",
343 "ANDROID_PRODUCT_OUT",
344 "ANDROID_HOST_OUT_TESTCASES",
345 "ANDROID_TARGET_OUT_TESTCASES",
346 "ANDROID_TOOLCHAIN",
347 "ANDROID_TOOLCHAIN_2ND_ARCH",
348 "ANDROID_DEV_SCRIPTS",
349 "ANDROID_EMULATOR_PREBUILTS",
350 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700351 )
352
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400353 if ret.UseGoma() || ret.ForceUseGoma() {
354 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
355 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400356 }
357
Dan Willemsen1e704462016-08-21 15:17:17 -0700358 // Tell python not to spam the source tree with .pyc files.
359 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
360
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400361 tmpDir := absPath(ctx, ret.TempDir())
362 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800363
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700364 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
365 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
366 "llvm-binutils-stable/llvm-symbolizer")
367 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
368
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800369 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700370 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800371
Yu Liu6e13b402021-07-27 14:29:06 -0700372 srcDir := absPath(ctx, ".")
373 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700374 ctx.Println("You are building in a directory whose absolute path contains a space character:")
375 ctx.Println()
376 ctx.Printf("%q\n", srcDir)
377 ctx.Println()
378 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700379 }
380
Yu Liu6e13b402021-07-27 14:29:06 -0700381 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
382
Dan Willemsendb8457c2017-05-12 16:38:17 -0700383 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700384 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
385 ctx.Println()
386 ctx.Printf("%q\n", outDir)
387 ctx.Println()
388 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700389 }
390
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000391 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700392 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
393 ctx.Println()
394 ctx.Printf("%q\n", distDir)
395 ctx.Println()
396 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700397 }
398
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700399 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000400 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
401 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100402 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800403 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700404 javaHome := func() string {
405 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
406 return override
407 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000408 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
409 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 +0100410 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000411 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
412 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
413 }
414 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700415 }()
416 absJavaHome := absPath(ctx, javaHome)
417
Dan Willemsened869522018-01-08 14:58:46 -0800418 ret.configureLocale(ctx)
419
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700420 newPath := []string{filepath.Join(absJavaHome, "bin")}
421 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
422 newPath = append(newPath, path)
423 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100424
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700425 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
426 ret.environ.Set("JAVA_HOME", absJavaHome)
427 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000428 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
429 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100430 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700431 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
432
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800433 outDir := ret.OutDir()
434 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800435 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800436 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800437 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800438 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800439 }
Colin Cross28f527c2019-11-26 16:19:04 -0800440
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800441 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
442
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400443 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400444 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400445 ret.environ.Set(k, v)
446 }
447 }
448
Patrice Arruda83842d72020-12-08 19:42:08 +0000449 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800450 if err := os.RemoveAll(bpd); err != nil {
451 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
452 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000453
Patrice Arruda96850362020-08-11 20:41:11 +0000454 c := Config{ret}
455 storeConfigMetrics(ctx, c)
456 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700457}
458
Patrice Arruda13848222019-04-22 17:12:02 -0700459// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
460// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700461func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
462 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700463}
464
Patrice Arruda96850362020-08-11 20:41:11 +0000465// storeConfigMetrics selects a set of configuration information and store in
466// the metrics system for further analysis.
467func storeConfigMetrics(ctx Context, config Config) {
468 if ctx.Metrics == nil {
469 return
470 }
471
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400472 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000473
474 s := &smpb.SystemResourceInfo{
475 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
476 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
477 }
478 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000479}
480
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400481func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700482 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400483 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
484 UseGoma: proto.Bool(config.UseGoma()),
485 UseRbe: proto.Bool(config.UseRBE()),
486 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
487 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400488 }
Yu Liue737a992021-10-04 13:21:41 -0700489 c.Targets = append(c.Targets, config.arguments...)
490
491 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400492}
493
Patrice Arruda13848222019-04-22 17:12:02 -0700494// getConfigArgs processes the command arguments based on the build action and creates a set of new
495// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700496func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700497 // The next block of code verifies that the current directory is the root directory of the source
498 // tree. It then finds the relative path of dir based on the root directory of the source tree
499 // and verify that dir is inside of the source tree.
500 checkTopDir(ctx)
501 topDir, err := os.Getwd()
502 if err != nil {
503 ctx.Fatalf("Error retrieving top directory: %v", err)
504 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700505 dir, err = filepath.EvalSymlinks(dir)
506 if err != nil {
507 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
508 }
Patrice Arruda13848222019-04-22 17:12:02 -0700509 dir, err = filepath.Abs(dir)
510 if err != nil {
511 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
512 }
513 relDir, err := filepath.Rel(topDir, dir)
514 if err != nil {
515 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
516 }
517 // If there are ".." in the path, it's not in the source tree.
518 if strings.Contains(relDir, "..") {
519 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
520 }
521
522 configArgs := args[:]
523
524 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
525 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
526 targetNamePrefix := "MODULES-IN-"
527 if inList("GET-INSTALL-PATH", configArgs) {
528 targetNamePrefix = "GET-INSTALL-PATH-IN-"
529 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
530 }
531
Patrice Arruda13848222019-04-22 17:12:02 -0700532 var targets []string
533
534 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700535 case BUILD_MODULES:
536 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700537 case BUILD_MODULES_IN_A_DIRECTORY:
538 // If dir is the root source tree, all the modules are built of the source tree are built so
539 // no need to find the build file.
540 if topDir == dir {
541 break
542 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700543
Patrice Arruda13848222019-04-22 17:12:02 -0700544 buildFile := findBuildFile(ctx, relDir)
545 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700546 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700547 }
Patrice Arruda13848222019-04-22 17:12:02 -0700548 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
549 case BUILD_MODULES_IN_DIRECTORIES:
550 newConfigArgs, dirs := splitArgs(configArgs)
551 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700552 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700553 }
554
555 // Tidy only override all other specified targets.
556 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
557 if tidyOnly == "true" || tidyOnly == "1" {
558 configArgs = append(configArgs, "tidy_only")
559 } else {
560 configArgs = append(configArgs, targets...)
561 }
562
563 return configArgs
564}
565
566// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
567func convertToTarget(dir string, targetNamePrefix string) string {
568 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
569}
570
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700571// hasBuildFile returns true if dir contains an Android build file.
572func hasBuildFile(ctx Context, dir string) bool {
573 for _, buildFile := range buildFiles {
574 _, err := os.Stat(filepath.Join(dir, buildFile))
575 if err == nil {
576 return true
577 }
578 if !os.IsNotExist(err) {
579 ctx.Fatalf("Error retrieving the build file stats: %v", err)
580 }
581 }
582 return false
583}
584
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700585// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
586// in the current and any sub directory of dir. If a build file is not found, traverse the path
587// up by one directory and repeat again until either a build file is found or reached to the root
588// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
589// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700590func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700591 // If the string is empty or ".", assume it is top directory of the source tree.
592 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700593 return ""
594 }
595
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700596 found := false
597 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
598 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
599 if err != nil {
600 return err
601 }
602 if found {
603 return filepath.SkipDir
604 }
605 if info.IsDir() {
606 return nil
607 }
608 for _, buildFile := range buildFiles {
609 if info.Name() == buildFile {
610 found = true
611 return filepath.SkipDir
612 }
613 }
614 return nil
615 })
616 if err != nil {
617 ctx.Fatalf("Error finding Android build file: %v", err)
618 }
619
620 if found {
621 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700622 }
623 }
624
625 return ""
626}
627
628// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
629func splitArgs(args []string) (newArgs []string, dirs []string) {
630 specialArgs := map[string]bool{
631 "showcommands": true,
632 "snod": true,
633 "dist": true,
634 "checkbuild": true,
635 }
636
637 newArgs = []string{}
638 dirs = []string{}
639
640 for _, arg := range args {
641 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
642 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
643 newArgs = append(newArgs, arg)
644 continue
645 }
646
647 if _, ok := specialArgs[arg]; ok {
648 newArgs = append(newArgs, arg)
649 continue
650 }
651
652 dirs = append(dirs, arg)
653 }
654
655 return newArgs, dirs
656}
657
658// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
659// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
660// source root tree where the build action command was invoked. Each directory is validated if the
661// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700662func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700663 for _, dir := range dirs {
664 // The directory may have specified specific modules to build. ":" is the separator to separate
665 // the directory and the list of modules.
666 s := strings.Split(dir, ":")
667 l := len(s)
668 if l > 2 { // more than one ":" was specified.
669 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
670 }
671
672 dir = filepath.Join(relDir, s[0])
673 if _, err := os.Stat(dir); err != nil {
674 ctx.Fatalf("couldn't find directory %s", dir)
675 }
676
677 // Verify that if there are any targets specified after ":". Each target is separated by ",".
678 var newTargets []string
679 if l == 2 && s[1] != "" {
680 newTargets = strings.Split(s[1], ",")
681 if inList("", newTargets) {
682 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
683 }
684 }
685
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700686 // If there are specified targets to build in dir, an android build file must exist for the one
687 // shot build. For the non-targets case, find the appropriate build file and build all the
688 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700689 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700690 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700691 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
692 }
693 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700694 buildFile := findBuildFile(ctx, dir)
695 if buildFile == "" {
696 ctx.Fatalf("Build file not found for %s directory", dir)
697 }
698 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700699 }
700
Patrice Arruda13848222019-04-22 17:12:02 -0700701 targets = append(targets, newTargets...)
702 }
703
Dan Willemsence41e942019-07-29 23:39:30 -0700704 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700705}
706
Dan Willemsen9b587492017-07-10 22:13:00 -0700707func (c *configImpl) parseArgs(ctx Context, args []string) {
708 for i := 0; i < len(args); i++ {
709 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100710 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700711 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200712 } else if arg == "--empty-ninja-file" {
713 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100714 } else if arg == "--skip-ninja" {
715 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700716 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700717 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
718 // but it does run a Kati ninja file if the .kati_enabled marker file was created
719 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000720 c.skipConfig = true
721 c.skipKati = true
722 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100723 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000724 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100725 } else if arg == "--soong-only" {
726 c.skipKati = true
727 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200728 } else if arg == "--config-only" {
729 c.skipKati = true
730 c.skipKatiNinja = true
731 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700732 } else if arg == "--skip-config" {
733 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700734 } else if arg == "--skip-soong-tests" {
735 c.skipSoongTests = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500736 } else if arg == "--mk-metrics" {
737 c.reportMkMetrics = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400738 } else if arg == "--bazel-mode" {
739 c.bazelProdMode = true
740 } else if arg == "--bazel-mode-dev" {
741 c.bazelDevMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000742 } else if arg == "--bazel-mode-staging" {
743 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000744 } else if arg == "--search-api-dir" {
745 c.searchApiDir = true
MarkDacekb96561e2022-12-02 04:34:43 +0000746 } else if strings.HasPrefix(arg, "--build-command=") {
747 buildCmd := strings.TrimPrefix(arg, "--build-command=")
748 // remove quotations
749 buildCmd = strings.TrimPrefix(buildCmd, "\"")
750 buildCmd = strings.TrimSuffix(buildCmd, "\"")
751 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000752 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
753 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700754 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700755 parseArgNum := func(def int) int {
756 if len(arg) > 2 {
757 p, err := strconv.ParseUint(arg[2:], 10, 31)
758 if err != nil {
759 ctx.Fatalf("Failed to parse %q: %v", arg, err)
760 }
761 return int(p)
762 } else if i+1 < len(args) {
763 p, err := strconv.ParseUint(args[i+1], 10, 31)
764 if err == nil {
765 i++
766 return int(p)
767 }
768 }
769 return def
770 }
771
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700772 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700773 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700774 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700775 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700776 } else {
777 ctx.Fatalln("Unknown option:", arg)
778 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700779 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700780 if k == "OUT_DIR" {
781 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
782 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700783 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700784 } else if arg == "dist" {
785 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200786 } else if arg == "json-module-graph" {
787 c.jsonModuleGraph = true
788 } else if arg == "bp2build" {
789 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000790 } else if arg == "api_bp2build" {
791 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200792 } else if arg == "queryview" {
793 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200794 } else if arg == "soong_docs" {
795 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700796 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700797 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800798 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700799 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700800 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700801 }
802 }
Chris Parsonsb6e96902022-10-31 20:08:45 -0400803 if (!c.bazelProdMode) && (!c.bazelDevMode) && (!c.bazelStagingMode) {
804 c.bazelProdMode = defaultBazelProdMode(c)
805 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700806}
807
Dan Willemsened869522018-01-08 14:58:46 -0800808func (c *configImpl) configureLocale(ctx Context) {
809 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
810 output, err := cmd.Output()
811
812 var locales []string
813 if err == nil {
814 locales = strings.Split(string(output), "\n")
815 } else {
816 // If we're unable to list the locales, let's assume en_US.UTF-8
817 locales = []string{"en_US.UTF-8"}
818 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
819 }
820
821 // gettext uses LANGUAGE, which is passed directly through
822
823 // For LANG and LC_*, only preserve the evaluated version of
824 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800825 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800826 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800827 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800828 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800829 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800830 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800831 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800832 }
833
834 c.environ.UnsetWithPrefix("LC_")
835
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800836 if userLang != "" {
837 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800838 }
839
840 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
841 // for others)
842 if inList("C.UTF-8", locales) {
843 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500844 } else if inList("C.utf8", locales) {
845 // These normalize to the same thing
846 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800847 } else if inList("en_US.UTF-8", locales) {
848 c.environ.Set("LANG", "en_US.UTF-8")
849 } else if inList("en_US.utf8", locales) {
850 // These normalize to the same thing
851 c.environ.Set("LANG", "en_US.UTF-8")
852 } else {
853 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
854 }
855}
856
Dan Willemsen1e704462016-08-21 15:17:17 -0700857func (c *configImpl) Environment() *Environment {
858 return c.environ
859}
860
861func (c *configImpl) Arguments() []string {
862 return c.arguments
863}
864
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200865func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200866 if len(c.Arguments()) > 0 {
867 // Explicit targets requested that are not special targets like b2pbuild
868 // or the JSON module graph
869 return true
870 }
871
Spandan Das5af0bd32022-09-28 20:43:08 +0000872 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200873 // Command line was empty, the default Ninja target is built
874 return true
875 }
876
Liz Kammer88677422021-12-15 15:03:19 -0500877 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
878 if c.Dist() && !c.Bp2Build() {
879 return true
880 }
881
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200882 // build.ninja doesn't need to be generated
883 return false
884}
885
Dan Willemsen1e704462016-08-21 15:17:17 -0700886func (c *configImpl) OutDir() string {
887 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700888 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700889 }
890 return "out"
891}
892
Dan Willemsen8a073a82017-02-04 17:30:44 -0800893func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400894 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000895}
896
897func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700898 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800899}
900
Dan Willemsen1e704462016-08-21 15:17:17 -0700901func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000902 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700903 return c.arguments
904 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700905 return c.ninjaArgs
906}
907
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500908func (c *configImpl) BazelOutDir() string {
909 return filepath.Join(c.OutDir(), "bazel")
910}
911
Liz Kammer2af5ea82022-11-11 14:21:03 -0500912func (c *configImpl) bazelOutputBase() string {
913 return filepath.Join(c.BazelOutDir(), "output")
914}
915
Dan Willemsen1e704462016-08-21 15:17:17 -0700916func (c *configImpl) SoongOutDir() string {
917 return filepath.Join(c.OutDir(), "soong")
918}
919
Spandan Das394aa322022-11-03 17:02:10 +0000920func (c *configImpl) ApiSurfacesOutDir() string {
921 return filepath.Join(c.OutDir(), "api_surfaces")
922}
923
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200924func (c *configImpl) PrebuiltOS() string {
925 switch runtime.GOOS {
926 case "linux":
927 return "linux-x86"
928 case "darwin":
929 return "darwin-x86"
930 default:
931 panic("Unknown GOOS")
932 }
933}
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100934
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200935func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -0700936 if c.SkipKatiNinja() {
937 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
938 } else {
939 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
940 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200941}
942
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200943func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100944 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200945}
946
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200947func (c *configImpl) UsedEnvFile(tag string) string {
948 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
949}
950
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000951func (c *configImpl) Bp2BuildFilesMarkerFile() string {
952 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
953}
954
955func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100956 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200957}
958
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200959func (c *configImpl) SoongDocsHtml() string {
960 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
961}
962
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200963func (c *configImpl) QueryviewMarkerFile() string {
964 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
965}
966
Spandan Das5af0bd32022-09-28 20:43:08 +0000967func (c *configImpl) ApiBp2buildMarkerFile() string {
968 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
969}
970
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200971func (c *configImpl) ModuleGraphFile() string {
972 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
973}
974
kgui67007242022-01-25 13:50:25 +0800975func (c *configImpl) ModuleActionsFile() string {
976 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
977}
978
Jeff Gastonefc1b412017-03-29 17:29:06 -0700979func (c *configImpl) TempDir() string {
980 return shared.TempDirForOutDir(c.SoongOutDir())
981}
982
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700983func (c *configImpl) FileListDir() string {
984 return filepath.Join(c.OutDir(), ".module_paths")
985}
986
Dan Willemsen1e704462016-08-21 15:17:17 -0700987func (c *configImpl) KatiSuffix() string {
988 if c.katiSuffix != "" {
989 return c.katiSuffix
990 }
991 panic("SetKatiSuffix has not been called")
992}
993
Colin Cross37193492017-11-16 17:55:00 -0800994// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
995// user is interested in additional checks at the expense of build time.
996func (c *configImpl) Checkbuild() bool {
997 return c.checkbuild
998}
999
Dan Willemsen8a073a82017-02-04 17:30:44 -08001000func (c *configImpl) Dist() bool {
1001 return c.dist
1002}
1003
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001004func (c *configImpl) JsonModuleGraph() bool {
1005 return c.jsonModuleGraph
1006}
1007
1008func (c *configImpl) Bp2Build() bool {
1009 return c.bp2build
1010}
1011
Spandan Das5af0bd32022-09-28 20:43:08 +00001012func (c *configImpl) ApiBp2build() bool {
1013 return c.apiBp2build
1014}
1015
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001016func (c *configImpl) Queryview() bool {
1017 return c.queryview
1018}
1019
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001020func (c *configImpl) SoongDocs() bool {
1021 return c.soongDocs
1022}
1023
Dan Willemsen1e704462016-08-21 15:17:17 -07001024func (c *configImpl) IsVerbose() bool {
1025 return c.verbose
1026}
1027
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001028func (c *configImpl) SkipKati() bool {
1029 return c.skipKati
1030}
1031
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001032func (c *configImpl) SkipKatiNinja() bool {
1033 return c.skipKatiNinja
1034}
1035
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001036func (c *configImpl) SkipSoong() bool {
1037 return c.skipSoong
1038}
1039
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001040func (c *configImpl) SkipNinja() bool {
1041 return c.skipNinja
1042}
1043
Anton Hansson5a7861a2021-06-04 10:09:01 +01001044func (c *configImpl) SetSkipNinja(v bool) {
1045 c.skipNinja = v
1046}
1047
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001048func (c *configImpl) SkipConfig() bool {
1049 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001050}
1051
Dan Willemsen1e704462016-08-21 15:17:17 -07001052func (c *configImpl) TargetProduct() string {
1053 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1054 return v
1055 }
1056 panic("TARGET_PRODUCT is not defined")
1057}
1058
Dan Willemsen02781d52017-05-12 19:28:13 -07001059func (c *configImpl) TargetDevice() string {
1060 return c.targetDevice
1061}
1062
1063func (c *configImpl) SetTargetDevice(device string) {
1064 c.targetDevice = device
1065}
1066
1067func (c *configImpl) TargetBuildVariant() string {
1068 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1069 return v
1070 }
1071 panic("TARGET_BUILD_VARIANT is not defined")
1072}
1073
Dan Willemsen1e704462016-08-21 15:17:17 -07001074func (c *configImpl) KatiArgs() []string {
1075 return c.katiArgs
1076}
1077
1078func (c *configImpl) Parallel() int {
1079 return c.parallel
1080}
1081
Colin Cross8b8bec32019-11-15 13:18:43 -08001082func (c *configImpl) HighmemParallel() int {
1083 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1084 return i
1085 }
1086
1087 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1088 parallel := c.Parallel()
1089 if c.UseRemoteBuild() {
1090 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1091 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1092 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1093 // Return 1/16th of the size of the local pool, rounding up.
1094 return (parallel + 15) / 16
1095 } else if c.totalRAM == 0 {
1096 // Couldn't detect the total RAM, don't restrict highmem processes.
1097 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001098 } else if c.totalRAM <= 16*1024*1024*1024 {
1099 // Less than 16GB of ram, restrict to 1 highmem processes
1100 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001101 } else if c.totalRAM <= 32*1024*1024*1024 {
1102 // Less than 32GB of ram, restrict to 2 highmem processes
1103 return 2
1104 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1105 // If less than 8GB total RAM per process, reduce the number of highmem processes
1106 return p
1107 }
1108 // No restriction on highmem processes
1109 return parallel
1110}
1111
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001112func (c *configImpl) TotalRAM() uint64 {
1113 return c.totalRAM
1114}
1115
Kousik Kumarec478642020-09-21 13:39:24 -04001116// ForceUseGoma determines whether we should override Goma deprecation
1117// and use Goma for the current build or not.
1118func (c *configImpl) ForceUseGoma() bool {
1119 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1120 v = strings.TrimSpace(v)
1121 if v != "" && v != "false" {
1122 return true
1123 }
1124 }
1125 return false
1126}
1127
Dan Willemsen1e704462016-08-21 15:17:17 -07001128func (c *configImpl) UseGoma() bool {
1129 if v, ok := c.environ.Get("USE_GOMA"); ok {
1130 v = strings.TrimSpace(v)
1131 if v != "" && v != "false" {
1132 return true
1133 }
1134 }
1135 return false
1136}
1137
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001138func (c *configImpl) StartGoma() bool {
1139 if !c.UseGoma() {
1140 return false
1141 }
1142
1143 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1144 v = strings.TrimSpace(v)
1145 if v != "" && v != "false" {
1146 return false
1147 }
1148 }
1149 return true
1150}
1151
Ramy Medhatbbf25672019-07-17 12:30:04 +00001152func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001153 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001154 v = strings.TrimSpace(v)
1155 if v != "" && v != "false" {
1156 return true
1157 }
1158 }
1159 return false
1160}
1161
Chris Parsonsef615e52022-08-18 22:04:11 -04001162func (c *configImpl) BazelBuildEnabled() bool {
MarkDacekb78465d2022-10-18 20:10:16 +00001163 return c.bazelProdMode || c.bazelDevMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001164}
1165
Ramy Medhatbbf25672019-07-17 12:30:04 +00001166func (c *configImpl) StartRBE() bool {
1167 if !c.UseRBE() {
1168 return false
1169 }
1170
1171 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1172 v = strings.TrimSpace(v)
1173 if v != "" && v != "false" {
1174 return false
1175 }
1176 }
1177 return true
1178}
1179
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001180func (c *configImpl) rbeProxyLogsDir() string {
1181 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001182 if v, ok := c.environ.Get(f); ok {
1183 return v
1184 }
1185 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001186 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1187 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001188}
1189
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001190func (c *configImpl) shouldCleanupRBELogsDir() bool {
1191 // Perform a log directory cleanup only when the log directory
1192 // is auto created by the build rather than user-specified.
1193 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1194 if _, ok := c.environ.Get(f); ok {
1195 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001196 }
1197 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001198 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001199}
1200
1201func (c *configImpl) rbeExecRoot() string {
1202 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1203 if v, ok := c.environ.Get(f); ok {
1204 return v
1205 }
1206 }
1207 wd, err := os.Getwd()
1208 if err != nil {
1209 return ""
1210 }
1211 return wd
1212}
1213
1214func (c *configImpl) rbeDir() string {
1215 if v, ok := c.environ.Get("RBE_DIR"); ok {
1216 return v
1217 }
1218 return "prebuilts/remoteexecution-client/live/"
1219}
1220
1221func (c *configImpl) rbeReproxy() string {
1222 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1223 if v, ok := c.environ.Get(f); ok {
1224 return v
1225 }
1226 }
1227 return filepath.Join(c.rbeDir(), "reproxy")
1228}
1229
1230func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001231 credFlags := []string{
1232 "use_application_default_credentials",
1233 "use_gce_credentials",
1234 "credential_file",
1235 "use_google_prod_creds",
1236 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001237 for _, cf := range credFlags {
1238 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1239 if v, ok := c.environ.Get(f); ok {
1240 v = strings.TrimSpace(v)
1241 if v != "" && v != "false" && v != "0" {
1242 return "RBE_" + cf, v
1243 }
1244 }
1245 }
1246 }
1247 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001248}
1249
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001250func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1251 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1252 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1253
1254 name := filepath.Join(dir, base)
1255 if len(name) < maxNameLen {
1256 return name, nil
1257 }
1258
1259 name = filepath.Join("/tmp", base)
1260 if len(name) < maxNameLen {
1261 return name, nil
1262 }
1263
1264 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1265}
1266
Kousik Kumar7bc78192022-04-27 14:52:56 -04001267// IsGooglerEnvironment returns true if the current build is running
1268// on a Google developer machine and false otherwise.
1269func (c *configImpl) IsGooglerEnvironment() bool {
1270 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1271 if v, ok := c.environ.Get(cf); ok {
1272 return v == "googler"
1273 }
1274 return false
1275}
1276
1277// GoogleProdCredsExist determine whether credentials exist on the
1278// Googler machine to use remote execution.
1279func (c *configImpl) GoogleProdCredsExist() bool {
1280 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1281 return false
1282 }
1283 return true
1284}
1285
1286// UseRemoteBuild indicates whether to use a remote build acceleration system
1287// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001288func (c *configImpl) UseRemoteBuild() bool {
1289 return c.UseGoma() || c.UseRBE()
1290}
1291
Kousik Kumar7bc78192022-04-27 14:52:56 -04001292// StubbyExists checks whether the stubby binary exists on the machine running
1293// the build.
1294func (c *configImpl) StubbyExists() bool {
1295 if _, err := exec.LookPath("stubby"); err != nil {
1296 return false
1297 }
1298 return true
1299}
1300
Dan Willemsen1e704462016-08-21 15:17:17 -07001301// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001302// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001303// still limited by Parallel()
1304func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001305 if !c.UseRemoteBuild() {
1306 return 0
1307 }
1308 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1309 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001310 }
1311 return 500
1312}
1313
1314func (c *configImpl) SetKatiArgs(args []string) {
1315 c.katiArgs = args
1316}
1317
1318func (c *configImpl) SetNinjaArgs(args []string) {
1319 c.ninjaArgs = args
1320}
1321
1322func (c *configImpl) SetKatiSuffix(suffix string) {
1323 c.katiSuffix = suffix
1324}
1325
Dan Willemsene0879fc2017-08-04 15:06:27 -07001326func (c *configImpl) LastKatiSuffixFile() string {
1327 return filepath.Join(c.OutDir(), "last_kati_suffix")
1328}
1329
1330func (c *configImpl) HasKatiSuffix() bool {
1331 return c.katiSuffix != ""
1332}
1333
Dan Willemsen1e704462016-08-21 15:17:17 -07001334func (c *configImpl) KatiEnvFile() string {
1335 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1336}
1337
Dan Willemsen29971232018-09-26 14:58:30 -07001338func (c *configImpl) KatiBuildNinjaFile() string {
1339 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001340}
1341
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001342func (c *configImpl) KatiPackageNinjaFile() string {
1343 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1344}
1345
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001346func (c *configImpl) SoongVarsFile() string {
1347 return filepath.Join(c.SoongOutDir(), "soong.variables")
1348}
1349
Dan Willemsen1e704462016-08-21 15:17:17 -07001350func (c *configImpl) SoongNinjaFile() string {
1351 return filepath.Join(c.SoongOutDir(), "build.ninja")
1352}
1353
1354func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001355 if c.katiSuffix == "" {
1356 return filepath.Join(c.OutDir(), "combined.ninja")
1357 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001358 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1359}
1360
1361func (c *configImpl) SoongAndroidMk() string {
1362 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1363}
1364
1365func (c *configImpl) SoongMakeVarsMk() string {
1366 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1367}
1368
Dan Willemsenf052f782017-05-18 15:29:04 -07001369func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001370 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001371}
1372
Dan Willemsen02781d52017-05-12 19:28:13 -07001373func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001374 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1375}
1376
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001377func (c *configImpl) KatiPackageMkDir() string {
1378 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1379}
1380
Dan Willemsenf052f782017-05-18 15:29:04 -07001381func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001382 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001383}
1384
1385func (c *configImpl) HostOut() string {
1386 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1387}
1388
1389// This probably needs to be multi-valued, so not exporting it for now
1390func (c *configImpl) hostCrossOut() string {
1391 if runtime.GOOS == "linux" {
1392 return filepath.Join(c.hostOutRoot(), "windows-x86")
1393 } else {
1394 return ""
1395 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001396}
1397
Dan Willemsen1e704462016-08-21 15:17:17 -07001398func (c *configImpl) HostPrebuiltTag() string {
1399 if runtime.GOOS == "linux" {
1400 return "linux-x86"
1401 } else if runtime.GOOS == "darwin" {
1402 return "darwin-x86"
1403 } else {
1404 panic("Unsupported OS")
1405 }
1406}
Dan Willemsenf173d592017-04-27 14:28:00 -07001407
Dan Willemsen8122bd52017-10-12 20:20:41 -07001408func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001409 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1410 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001411 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1412 if _, err := os.Stat(asan); err == nil {
1413 return asan
1414 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001415 }
1416 }
1417 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1418}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001419
1420func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1421 c.brokenDupRules = val
1422}
1423
1424func (c *configImpl) BuildBrokenDupRules() bool {
1425 return c.brokenDupRules
1426}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001427
Dan Willemsen25e6f092019-04-09 10:22:43 -07001428func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1429 c.brokenUsesNetwork = val
1430}
1431
1432func (c *configImpl) BuildBrokenUsesNetwork() bool {
1433 return c.brokenUsesNetwork
1434}
1435
Dan Willemsene3336352020-01-02 19:10:38 -08001436func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1437 c.brokenNinjaEnvVars = val
1438}
1439
1440func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1441 return c.brokenNinjaEnvVars
1442}
1443
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001444func (c *configImpl) SetTargetDeviceDir(dir string) {
1445 c.targetDeviceDir = dir
1446}
1447
1448func (c *configImpl) TargetDeviceDir() string {
1449 return c.targetDeviceDir
1450}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001451
Patrice Arruda219eef32020-06-01 17:29:30 +00001452func (c *configImpl) BuildDateTime() string {
1453 return c.buildDateTime
1454}
1455
1456func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001457 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001458}
Patrice Arruda83842d72020-12-08 19:42:08 +00001459
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001460// LogsDir returns the absolute path to the logs directory where build log and
1461// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001462// directory. If the argument dist is specified, the logs directory
1463// is <dist_dir>/logs.
1464func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001465 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001466 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001467 // 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 -05001468 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001469 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001470 absDir, err := filepath.Abs(dir)
1471 if err != nil {
1472 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1473 os.Exit(1)
1474 }
1475 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001476}
1477
1478// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1479// where the bazel profiles are located.
1480func (c *configImpl) BazelMetricsDir() string {
1481 return filepath.Join(c.LogsDir(), "bazel_metrics")
1482}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001483
Chris Parsons53f68ae2022-03-03 12:01:40 -05001484// MkFileMetrics returns the file path for make-related metrics.
1485func (c *configImpl) MkMetrics() string {
1486 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1487}
1488
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001489func (c *configImpl) SetEmptyNinjaFile(v bool) {
1490 c.emptyNinjaFile = v
1491}
1492
1493func (c *configImpl) EmptyNinjaFile() bool {
1494 return c.emptyNinjaFile
1495}
Yu Liu6e13b402021-07-27 14:29:06 -07001496
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001497func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1498 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1499}
1500
MarkDacekd06db5d2022-11-29 00:47:59 +00001501func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1502 return c.bazelForceEnabledModules
1503}
1504
Yu Liu6e13b402021-07-27 14:29:06 -07001505func GetMetricsUploader(topDir string, env *Environment) string {
1506 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1507 metricsUploader := filepath.Join(topDir, p)
1508 if _, err := os.Stat(metricsUploader); err == nil {
1509 return metricsUploader
1510 }
1511 }
1512
1513 return ""
1514}