blob: 2f5d578a02ea0ee3200831fea028205ad14ccb7a [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 Kumard93c67f2023-05-30 20:23:57 +000018 "context"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050019 "encoding/json"
Jeongik Chaa87506f2023-06-01 23:16:41 +090020 "errors"
Ramy Medhat0fc67eb2020-08-12 01:26:23 -040021 "fmt"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050022 "io/ioutil"
Kousik Kumar4c180ad2022-05-27 07:48:37 -040023 "math/rand"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080024 "os"
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050025 "os/exec"
Dan Willemsen1e704462016-08-21 15:17:17 -070026 "path/filepath"
27 "runtime"
28 "strconv"
29 "strings"
Kousik Kumar4c180ad2022-05-27 07:48:37 -040030 "syscall"
Nan Zhang2e6a4ff2018-02-14 13:27:26 -080031 "time"
Jeff Gastonefc1b412017-03-29 17:29:06 -070032
33 "android/soong/shared"
Kousik Kumarec478642020-09-21 13:39:24 -040034
Dan Willemsen4591b642021-05-24 14:24:12 -070035 "google.golang.org/protobuf/proto"
Patrice Arruda96850362020-08-11 20:41:11 +000036
37 smpb "android/soong/ui/metrics/metrics_proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070038)
39
Kousik Kumar3ff037e2022-01-25 22:11:01 -050040const (
Chris Parsons53f68ae2022-03-03 12:01:40 -050041 envConfigDir = "vendor/google/tools/soong_config"
42 jsonSuffix = "json"
Kousik Kumard93c67f2023-05-30 20:23:57 +000043
44 configFetcher = "vendor/google/tools/soong/expconfigfetcher"
Kousik Kumara3a2af62023-06-06 17:29:11 -040045 envConfigFetchTimeout = 20 * time.Second
Kousik Kumar3ff037e2022-01-25 22:11:01 -050046)
47
Kousik Kumar4c180ad2022-05-27 07:48:37 -040048var (
Kevin Dagostino096ab2f2023-03-03 19:47:17 +000049 rbeRandPrefix int
50 googleProdCredsExistCache bool
Kousik Kumar4c180ad2022-05-27 07:48:37 -040051)
52
53func init() {
54 rand.Seed(time.Now().UnixNano())
55 rbeRandPrefix = rand.Intn(1000)
56}
57
Dan Willemsen1e704462016-08-21 15:17:17 -070058type Config struct{ *configImpl }
59
60type configImpl struct {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020061 // Some targets that are implemented in soong_build
62 // (bp2build, json-module-graph) are not here and have their own bits below.
Colin Cross28f527c2019-11-26 16:19:04 -080063 arguments []string
64 goma bool
65 environ *Environment
66 distDir string
67 buildDateTime string
MarkDacek6614d9c2022-12-07 21:57:38 +000068 logsPrefix string
Dan Willemsen1e704462016-08-21 15:17:17 -070069
70 // From the arguments
MarkDacekf47e1422023-04-19 16:47:36 +000071 parallel int
72 keepGoing int
73 verbose bool
74 checkbuild bool
75 dist bool
76 jsonModuleGraph bool
77 apiBp2build bool // Generate BUILD files for Soong modules that contribute APIs
78 bp2build bool
79 queryview bool
80 reportMkMetrics bool // Collect and report mk2bp migration progress metrics.
81 soongDocs bool
82 multitreeBuild bool // This is a multitree build.
83 skipConfig bool
84 skipKati bool
85 skipKatiNinja bool
86 skipSoong bool
87 skipNinja bool
88 skipSoongTests bool
89 searchApiDir bool // Scan the Android.bp files generated in out/api_surfaces
90 skipMetricsUpload bool
91 buildStartedTime int64 // For metrics-upload-only - manually specify a build-started time
92 buildFromTextStub bool
MarkDacek396491e2023-06-14 19:41:18 +000093 ensureAllowlistIntegrity bool // For CI builds - make sure modules are mixed-built
94 bazelExitCode int32 // For b runs - necessary for updating NonZeroExit
95 besId string // For b runs, to identify the BuildEventService logs
Dan Willemsen1e704462016-08-21 15:17:17 -070096
97 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070098 katiArgs []string
99 ninjaArgs []string
100 katiSuffix string
101 targetDevice string
102 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +0000103 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -0700104
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800105 // Autodetected
106 totalRAM uint64
107
Dan Willemsene3336352020-01-02 19:10:38 -0800108 brokenDupRules bool
109 brokenUsesNetwork bool
110 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -0700111
112 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000113
MarkDacekb78465d2022-10-18 20:10:16 +0000114 bazelProdMode bool
MarkDacekb78465d2022-10-18 20:10:16 +0000115 bazelStagingMode bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000116
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700117 // Set by multiproduct_kati
118 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700119
120 metricsUploader string
MarkDacekd06db5d2022-11-29 00:47:59 +0000121
122 bazelForceEnabledModules string
Spandan Dasc5763832022-11-08 18:42:16 +0000123
Sam Delmerico98a73292023-02-21 11:50:29 -0500124 includeTags []string
125 sourceRootDirs []string
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900126
127 // Data source to write ninja weight list
128 ninjaWeightListSource NinjaWeightListSource
Dan Willemsen1e704462016-08-21 15:17:17 -0700129}
130
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900131type NinjaWeightListSource uint
132
133const (
134 // ninja doesn't use weight list.
135 NOT_USED NinjaWeightListSource = iota
136 // ninja uses weight list based on previous builds by ninja log
137 NINJA_LOG
138 // ninja thinks every task has the same weight.
139 EVENLY_DISTRIBUTED
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900140 // ninja uses an external custom weight list
141 EXTERNAL_FILE
Jeongik Chae114e602023-03-19 00:12:39 +0900142 // ninja uses a prioritized module list from Soong
143 HINT_FROM_SOONG
Jeongik Chaa87506f2023-06-01 23:16:41 +0900144 // If ninja log exists, use NINJA_LOG, if not, use HINT_FROM_SOONG instead.
145 // We can assume it is an incremental build if ninja log exists.
146 DEFAULT
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900147)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800148const srcDirFileCheck = "build/soong/root.bp"
149
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700150var buildFiles = []string{"Android.mk", "Android.bp"}
151
Patrice Arruda13848222019-04-22 17:12:02 -0700152type BuildAction uint
153
154const (
155 // Builds all of the modules and their dependencies of a specified directory, relative to the root
156 // directory of the source tree.
157 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
158
159 // Builds all of the modules and their dependencies of a list of specified directories. All specified
160 // directories are relative to the root directory of the source tree.
161 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700162
163 // Build a list of specified modules. If none was specified, simply build the whole source tree.
164 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700165)
166
167// checkTopDir validates that the current directory is at the root directory of the source tree.
168func checkTopDir(ctx Context) {
169 if _, err := os.Stat(srcDirFileCheck); err != nil {
170 if os.IsNotExist(err) {
171 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
172 }
173 ctx.Fatalln("Error verifying tree state:", err)
174 }
175}
176
Kousik Kumard93c67f2023-05-30 20:23:57 +0000177// fetchEnvConfig optionally fetches a configuration file that can then subsequently be
178// loaded into Soong environment to control certain aspects of build behavior (e.g., enabling RBE).
179// If a configuration file already exists on disk, the fetch is run in the background
180// so as to NOT block the rest of the build execution.
181func fetchEnvConfig(ctx Context, config *configImpl, envConfigName string) error {
182 configName := envConfigName + "." + jsonSuffix
183 expConfigFetcher := &smpb.ExpConfigFetcher{Filename: &configName}
184 defer func() {
185 ctx.Metrics.ExpConfigFetcher(expConfigFetcher)
186 }()
187 if !config.GoogleProdCredsExist() {
188 status := smpb.ExpConfigFetcher_MISSING_GCERT
189 expConfigFetcher.Status = &status
190 return nil
191 }
192
193 s, err := os.Stat(configFetcher)
194 if err != nil {
195 if os.IsNotExist(err) {
196 return nil
197 }
198 return err
199 }
200 if s.Mode()&0111 == 0 {
201 status := smpb.ExpConfigFetcher_ERROR
202 expConfigFetcher.Status = &status
203 return fmt.Errorf("configuration fetcher binary %v is not executable: %v", configFetcher, s.Mode())
204 }
205
206 configExists := false
207 outConfigFilePath := filepath.Join(config.OutDir(), configName)
208 if _, err := os.Stat(outConfigFilePath); err == nil {
209 configExists = true
210 }
211
212 tCtx, cancel := context.WithTimeout(ctx, envConfigFetchTimeout)
213 fetchStart := time.Now()
214 cmd := exec.CommandContext(tCtx, configFetcher, "-output_config_dir", config.OutDir(),
215 "-output_config_name", configName)
216 if err := cmd.Start(); err != nil {
217 status := smpb.ExpConfigFetcher_ERROR
218 expConfigFetcher.Status = &status
219 return err
220 }
221
222 fetchCfg := func() error {
223 if err := cmd.Wait(); err != nil {
224 status := smpb.ExpConfigFetcher_ERROR
225 expConfigFetcher.Status = &status
226 return err
227 }
228 fetchEnd := time.Now()
229 expConfigFetcher.Micros = proto.Uint64(uint64(fetchEnd.Sub(fetchStart).Microseconds()))
230 expConfigFetcher.Filename = proto.String(outConfigFilePath)
231
232 if _, err := os.Stat(outConfigFilePath); err != nil {
233 status := smpb.ExpConfigFetcher_NO_CONFIG
234 expConfigFetcher.Status = &status
235 return err
236 }
237 status := smpb.ExpConfigFetcher_CONFIG
238 expConfigFetcher.Status = &status
239 return nil
240 }
241
242 // If a config file does not exist, wait for the config file to be fetched. Otherwise
243 // fetch the config file in the background and return immediately.
244 if !configExists {
245 defer cancel()
246 return fetchCfg()
247 }
248
249 go func() {
250 defer cancel()
251 if err := fetchCfg(); err != nil {
252 ctx.Verbosef("Failed to fetch config file %v: %v\n", configName, err)
253 }
254 }()
255 return nil
256}
257
MarkDacek7901e582023-01-09 19:48:01 +0000258func loadEnvConfig(ctx Context, config *configImpl, bc string) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500259 if bc == "" {
260 return nil
261 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500262
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500263 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500264 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500265 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500266 envConfigDir,
267 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500268 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500269 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
270 envVarsJSON, err := ioutil.ReadFile(cfgFile)
271 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500272 continue
273 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500274 ctx.Verbosef("Loading config file %v\n", cfgFile)
275 var envVars map[string]map[string]string
276 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
277 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
278 continue
279 }
280 for k, v := range envVars["env"] {
281 if os.Getenv(k) != "" {
282 continue
283 }
284 config.environ.Set(k, v)
285 }
286 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
287 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500288 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500289
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500290 return nil
291}
292
Chris Parsonsb6e96902022-10-31 20:08:45 -0400293func defaultBazelProdMode(cfg *configImpl) bool {
MarkDacekd06db5d2022-11-29 00:47:59 +0000294 // Environment flag to disable Bazel for users which experience
Chris Parsonsb6e96902022-10-31 20:08:45 -0400295 // broken bazel-handled builds, or significant performance regressions.
296 if cfg.IsBazelMixedBuildForceDisabled() {
297 return false
298 }
299 // Darwin-host builds are currently untested with Bazel.
300 if runtime.GOOS == "darwin" {
301 return false
302 }
Chris Parsons035e03a2022-11-01 14:25:45 -0400303 return true
Chris Parsonsb6e96902022-10-31 20:08:45 -0400304}
305
MarkDacekd33c2fd2023-05-04 20:40:04 +0000306func UploadOnlyConfig(ctx Context, args ...string) Config {
MarkDacek6614d9c2022-12-07 21:57:38 +0000307 ret := &configImpl{
308 environ: OsEnvironment(),
309 sandboxConfig: &SandboxConfig{},
310 }
MarkDacekd33c2fd2023-05-04 20:40:04 +0000311 ret.parseArgs(ctx, args)
MarkDacek7901e582023-01-09 19:48:01 +0000312 srcDir := absPath(ctx, ".")
313 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
314 if err := loadEnvConfig(ctx, ret, bc); err != nil {
315 ctx.Fatalln("Failed to parse env config files: %v", err)
316 }
317 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
MarkDacek6614d9c2022-12-07 21:57:38 +0000318 return Config{ret}
319}
320
Dan Willemsen1e704462016-08-21 15:17:17 -0700321func NewConfig(ctx Context, args ...string) Config {
322 ret := &configImpl{
Jeongik Chaf2ecf762023-05-19 14:03:45 +0900323 environ: OsEnvironment(),
324 sandboxConfig: &SandboxConfig{},
Jeongik Chaa87506f2023-06-01 23:16:41 +0900325 ninjaWeightListSource: DEFAULT,
Dan Willemsen1e704462016-08-21 15:17:17 -0700326 }
327
Patrice Arruda90109172020-07-28 18:07:27 +0000328 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700329 ret.parallel = runtime.NumCPU() + 2
330 ret.keepGoing = 1
331
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800332 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700333 ret.parseArgs(ctx, args)
Jeongik Chae114e602023-03-19 00:12:39 +0900334
335 if ret.ninjaWeightListSource == HINT_FROM_SOONG {
Jeongik Chaa87506f2023-06-01 23:16:41 +0900336 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "always")
337 } else if ret.ninjaWeightListSource == DEFAULT {
338 defaultNinjaWeightListSource := NINJA_LOG
339 if _, err := os.Stat(filepath.Join(ret.OutDir(), ninjaLogFileName)); errors.Is(err, os.ErrNotExist) {
340 ctx.Verboseln("$OUT/.ninja_log doesn't exist, use HINT_FROM_SOONG instead")
341 defaultNinjaWeightListSource = HINT_FROM_SOONG
342 } else {
343 ctx.Verboseln("$OUT/.ninja_log exist, use NINJA_LOG")
344 }
345 ret.ninjaWeightListSource = defaultNinjaWeightListSource
346 // soong_build generates ninja hint depending on ninja log existence.
347 // Set it "depend" to avoid soong re-run due to env variable change.
348 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "depend")
Jeongik Chae114e602023-03-19 00:12:39 +0900349 }
Jeongik Chaa87506f2023-06-01 23:16:41 +0900350
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800351 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700352 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
353 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
354 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800355 outDir := "out"
356 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
357 if wd, err := os.Getwd(); err != nil {
358 ctx.Fatalln("Failed to get working directory:", err)
359 } else {
360 outDir = filepath.Join(baseDir, filepath.Base(wd))
361 }
362 }
363 ret.environ.Set("OUT_DIR", outDir)
364 }
365
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500366 // loadEnvConfig needs to know what the OUT_DIR is, so it should
367 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000368 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
369
370 if bc != "" {
Kousik Kumard93c67f2023-05-30 20:23:57 +0000371 if err := fetchEnvConfig(ctx, ret, bc); err != nil {
372 ctx.Verbosef("Failed to fetch config file: %v\n", err)
373 }
Kousik Kumarc8818332023-01-16 16:33:05 +0000374 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000375 ctx.Fatalln("Failed to parse env config files: %v", err)
376 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +0000377 if !ret.canSupportRBE() {
378 // Explicitly set USE_RBE env variable to false when we cannot run
379 // an RBE build to avoid ninja local execution pool issues.
380 ret.environ.Set("USE_RBE", "false")
381 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500382 }
383
Dan Willemsen2d31a442018-10-20 21:33:41 -0700384 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
385 ret.distDir = filepath.Clean(distDir)
386 } else {
387 ret.distDir = filepath.Join(ret.OutDir(), "dist")
388 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700389
Spandan Das05063612021-06-25 01:39:04 +0000390 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
391 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
392 }
393
Dan Willemsen1e704462016-08-21 15:17:17 -0700394 ret.environ.Unset(
395 // We're already using it
396 "USE_SOONG_UI",
397
398 // We should never use GOROOT/GOPATH from the shell environment
399 "GOROOT",
400 "GOPATH",
401
402 // These should only come from Soong, not the environment.
403 "CLANG",
404 "CLANG_CXX",
405 "CCC_CC",
406 "CCC_CXX",
407
408 // Used by the goma compiler wrapper, but should only be set by
409 // gomacc
410 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800411
412 // We handle this above
413 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700414
Dan Willemsen2d31a442018-10-20 21:33:41 -0700415 // This is handled above too, and set for individual commands later
416 "DIST_DIR",
417
Dan Willemsen68a09852017-04-18 13:56:57 -0700418 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000419 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700420 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700421 "DISPLAY",
422 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000423 "JAVAC",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700424 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700425 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700426
427 // Drop make flags
428 "MAKEFLAGS",
429 "MAKELEVEL",
430 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700431
432 // Set in envsetup.sh, reset in makefiles
433 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700434
435 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
436 "ANDROID_BUILD_TOP",
437 "ANDROID_HOST_OUT",
438 "ANDROID_PRODUCT_OUT",
439 "ANDROID_HOST_OUT_TESTCASES",
440 "ANDROID_TARGET_OUT_TESTCASES",
441 "ANDROID_TOOLCHAIN",
442 "ANDROID_TOOLCHAIN_2ND_ARCH",
443 "ANDROID_DEV_SCRIPTS",
444 "ANDROID_EMULATOR_PREBUILTS",
445 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700446 )
447
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400448 if ret.UseGoma() || ret.ForceUseGoma() {
449 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
450 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400451 }
452
Dan Willemsen1e704462016-08-21 15:17:17 -0700453 // Tell python not to spam the source tree with .pyc files.
454 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
455
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400456 tmpDir := absPath(ctx, ret.TempDir())
457 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800458
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700459 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
460 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
461 "llvm-binutils-stable/llvm-symbolizer")
462 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
463
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800464 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700465 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800466
Yu Liu6e13b402021-07-27 14:29:06 -0700467 srcDir := absPath(ctx, ".")
468 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700469 ctx.Println("You are building in a directory whose absolute path contains a space character:")
470 ctx.Println()
471 ctx.Printf("%q\n", srcDir)
472 ctx.Println()
473 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700474 }
475
Yu Liu6e13b402021-07-27 14:29:06 -0700476 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
477
Dan Willemsendb8457c2017-05-12 16:38:17 -0700478 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700479 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
480 ctx.Println()
481 ctx.Printf("%q\n", outDir)
482 ctx.Println()
483 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700484 }
485
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000486 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700487 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
488 ctx.Println()
489 ctx.Printf("%q\n", distDir)
490 ctx.Println()
491 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700492 }
493
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700494 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000495 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
496 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100497 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800498 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700499 javaHome := func() string {
500 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
501 return override
502 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000503 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
504 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 +0100505 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000506 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
507 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
508 }
509 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700510 }()
511 absJavaHome := absPath(ctx, javaHome)
512
Dan Willemsened869522018-01-08 14:58:46 -0800513 ret.configureLocale(ctx)
514
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700515 newPath := []string{filepath.Join(absJavaHome, "bin")}
516 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
517 newPath = append(newPath, path)
518 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100519
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700520 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
521 ret.environ.Set("JAVA_HOME", absJavaHome)
522 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000523 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
524 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100525 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700526 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
527
Colin Crossfe5ed4d2023-07-28 09:27:23 -0700528 // b/286885495, https://bugzilla.redhat.com/show_bug.cgi?id=2227130: some versions of Fedora include patches
529 // to unzip to enable zipbomb detection that incorrectly handle zip64 and data descriptors and fail on large
530 // zip files produced by soong_zip. Disable zipbomb detection.
531 ret.environ.Set("UNZIP_DISABLE_ZIPBOMB_DETECTION", "TRUE")
532
LaMont Jones52a72432023-03-09 18:19:35 +0000533 if ret.MultitreeBuild() {
534 ret.environ.Set("MULTITREE_BUILD", "true")
535 }
536
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800537 outDir := ret.OutDir()
538 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800539 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800540 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800541 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800542 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800543 }
Colin Cross28f527c2019-11-26 16:19:04 -0800544
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800545 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
546
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400547 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400548 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400549 ret.environ.Set(k, v)
550 }
551 }
552
Jihoon Kang1bff0342023-01-17 20:40:22 +0000553 if ret.BuildFromTextStub() {
554 // TODO(b/271443071): support hidden api check for from-text stub build
555 ret.environ.Set("UNSAFE_DISABLE_HIDDENAPI_FLAGS", "true")
556 }
557
Patrice Arruda83842d72020-12-08 19:42:08 +0000558 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800559 if err := os.RemoveAll(bpd); err != nil {
560 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
561 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000562
Patrice Arruda96850362020-08-11 20:41:11 +0000563 c := Config{ret}
564 storeConfigMetrics(ctx, c)
565 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700566}
567
Patrice Arruda13848222019-04-22 17:12:02 -0700568// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
569// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700570func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
571 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700572}
573
Patrice Arruda96850362020-08-11 20:41:11 +0000574// storeConfigMetrics selects a set of configuration information and store in
575// the metrics system for further analysis.
576func storeConfigMetrics(ctx Context, config Config) {
577 if ctx.Metrics == nil {
578 return
579 }
580
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400581 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000582
583 s := &smpb.SystemResourceInfo{
584 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
585 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
586 }
587 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000588}
589
Jeongik Cha8d63d562023-03-17 03:52:13 +0900590func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900591 switch s {
592 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900593 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900594 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900595 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900596 case EXTERNAL_FILE:
597 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900598 case HINT_FROM_SOONG:
599 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900600 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900601 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900602 }
603}
604
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400605func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700606 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400607 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
608 UseGoma: proto.Bool(config.UseGoma()),
609 UseRbe: proto.Bool(config.UseRBE()),
610 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
611 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900612 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400613 }
Yu Liue737a992021-10-04 13:21:41 -0700614 c.Targets = append(c.Targets, config.arguments...)
615
616 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400617}
618
Patrice Arruda13848222019-04-22 17:12:02 -0700619// getConfigArgs processes the command arguments based on the build action and creates a set of new
620// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700621func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700622 // The next block of code verifies that the current directory is the root directory of the source
623 // tree. It then finds the relative path of dir based on the root directory of the source tree
624 // and verify that dir is inside of the source tree.
625 checkTopDir(ctx)
626 topDir, err := os.Getwd()
627 if err != nil {
628 ctx.Fatalf("Error retrieving top directory: %v", err)
629 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700630 dir, err = filepath.EvalSymlinks(dir)
631 if err != nil {
632 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
633 }
Patrice Arruda13848222019-04-22 17:12:02 -0700634 dir, err = filepath.Abs(dir)
635 if err != nil {
636 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
637 }
638 relDir, err := filepath.Rel(topDir, dir)
639 if err != nil {
640 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
641 }
642 // If there are ".." in the path, it's not in the source tree.
643 if strings.Contains(relDir, "..") {
644 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
645 }
646
647 configArgs := args[:]
648
649 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
650 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
651 targetNamePrefix := "MODULES-IN-"
652 if inList("GET-INSTALL-PATH", configArgs) {
653 targetNamePrefix = "GET-INSTALL-PATH-IN-"
654 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
655 }
656
Patrice Arruda13848222019-04-22 17:12:02 -0700657 var targets []string
658
659 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700660 case BUILD_MODULES:
661 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700662 case BUILD_MODULES_IN_A_DIRECTORY:
663 // If dir is the root source tree, all the modules are built of the source tree are built so
664 // no need to find the build file.
665 if topDir == dir {
666 break
667 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700668
Patrice Arruda13848222019-04-22 17:12:02 -0700669 buildFile := findBuildFile(ctx, relDir)
670 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700671 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700672 }
Patrice Arruda13848222019-04-22 17:12:02 -0700673 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
674 case BUILD_MODULES_IN_DIRECTORIES:
675 newConfigArgs, dirs := splitArgs(configArgs)
676 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700677 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700678 }
679
680 // Tidy only override all other specified targets.
681 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
682 if tidyOnly == "true" || tidyOnly == "1" {
683 configArgs = append(configArgs, "tidy_only")
684 } else {
685 configArgs = append(configArgs, targets...)
686 }
687
688 return configArgs
689}
690
691// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
692func convertToTarget(dir string, targetNamePrefix string) string {
693 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
694}
695
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700696// hasBuildFile returns true if dir contains an Android build file.
697func hasBuildFile(ctx Context, dir string) bool {
698 for _, buildFile := range buildFiles {
699 _, err := os.Stat(filepath.Join(dir, buildFile))
700 if err == nil {
701 return true
702 }
703 if !os.IsNotExist(err) {
704 ctx.Fatalf("Error retrieving the build file stats: %v", err)
705 }
706 }
707 return false
708}
709
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700710// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
711// in the current and any sub directory of dir. If a build file is not found, traverse the path
712// up by one directory and repeat again until either a build file is found or reached to the root
713// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
714// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700715func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700716 // If the string is empty or ".", assume it is top directory of the source tree.
717 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700718 return ""
719 }
720
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700721 found := false
722 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
723 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
724 if err != nil {
725 return err
726 }
727 if found {
728 return filepath.SkipDir
729 }
730 if info.IsDir() {
731 return nil
732 }
733 for _, buildFile := range buildFiles {
734 if info.Name() == buildFile {
735 found = true
736 return filepath.SkipDir
737 }
738 }
739 return nil
740 })
741 if err != nil {
742 ctx.Fatalf("Error finding Android build file: %v", err)
743 }
744
745 if found {
746 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700747 }
748 }
749
750 return ""
751}
752
753// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
754func splitArgs(args []string) (newArgs []string, dirs []string) {
755 specialArgs := map[string]bool{
756 "showcommands": true,
757 "snod": true,
758 "dist": true,
759 "checkbuild": true,
760 }
761
762 newArgs = []string{}
763 dirs = []string{}
764
765 for _, arg := range args {
766 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
767 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
768 newArgs = append(newArgs, arg)
769 continue
770 }
771
772 if _, ok := specialArgs[arg]; ok {
773 newArgs = append(newArgs, arg)
774 continue
775 }
776
777 dirs = append(dirs, arg)
778 }
779
780 return newArgs, dirs
781}
782
783// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
784// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
785// source root tree where the build action command was invoked. Each directory is validated if the
786// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700787func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700788 for _, dir := range dirs {
789 // The directory may have specified specific modules to build. ":" is the separator to separate
790 // the directory and the list of modules.
791 s := strings.Split(dir, ":")
792 l := len(s)
793 if l > 2 { // more than one ":" was specified.
794 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
795 }
796
797 dir = filepath.Join(relDir, s[0])
798 if _, err := os.Stat(dir); err != nil {
799 ctx.Fatalf("couldn't find directory %s", dir)
800 }
801
802 // Verify that if there are any targets specified after ":". Each target is separated by ",".
803 var newTargets []string
804 if l == 2 && s[1] != "" {
805 newTargets = strings.Split(s[1], ",")
806 if inList("", newTargets) {
807 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
808 }
809 }
810
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700811 // If there are specified targets to build in dir, an android build file must exist for the one
812 // shot build. For the non-targets case, find the appropriate build file and build all the
813 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700814 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700815 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700816 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
817 }
818 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700819 buildFile := findBuildFile(ctx, dir)
820 if buildFile == "" {
821 ctx.Fatalf("Build file not found for %s directory", dir)
822 }
823 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700824 }
825
Patrice Arruda13848222019-04-22 17:12:02 -0700826 targets = append(targets, newTargets...)
827 }
828
Dan Willemsence41e942019-07-29 23:39:30 -0700829 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700830}
831
Dan Willemsen9b587492017-07-10 22:13:00 -0700832func (c *configImpl) parseArgs(ctx Context, args []string) {
833 for i := 0; i < len(args); i++ {
834 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100835 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700836 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200837 } else if arg == "--empty-ninja-file" {
838 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100839 } else if arg == "--skip-ninja" {
840 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700841 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700842 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
843 // but it does run a Kati ninja file if the .kati_enabled marker file was created
844 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000845 c.skipConfig = true
846 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100847 } else if arg == "--soong-only" {
848 c.skipKati = true
849 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200850 } else if arg == "--config-only" {
851 c.skipKati = true
852 c.skipKatiNinja = true
853 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700854 } else if arg == "--skip-config" {
855 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700856 } else if arg == "--skip-soong-tests" {
857 c.skipSoongTests = true
MarkDacekd0e7cd32022-12-02 22:22:40 +0000858 } else if arg == "--skip-metrics-upload" {
859 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500860 } else if arg == "--mk-metrics" {
861 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000862 } else if arg == "--multitree-build" {
863 c.multitreeBuild = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400864 } else if arg == "--bazel-mode" {
865 c.bazelProdMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000866 } else if arg == "--bazel-mode-staging" {
867 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000868 } else if arg == "--search-api-dir" {
869 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900870 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
871 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
872 if source == "ninja_log" {
873 c.ninjaWeightListSource = NINJA_LOG
874 } else if source == "evenly_distributed" {
875 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
876 } else if source == "not_used" {
877 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900878 } else if source == "soong" {
879 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900880 } else if strings.HasPrefix(source, "file,") {
881 c.ninjaWeightListSource = EXTERNAL_FILE
882 filePath := strings.TrimPrefix(source, "file,")
883 err := validateNinjaWeightList(filePath)
884 if err != nil {
885 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
886 }
887 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
888 if err != nil {
889 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
890 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900891 } else {
892 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
893 }
Jihoon Kang1bff0342023-01-17 20:40:22 +0000894 } else if arg == "--build-from-text-stub" {
895 c.buildFromTextStub = true
MarkDacekb96561e2022-12-02 04:34:43 +0000896 } else if strings.HasPrefix(arg, "--build-command=") {
897 buildCmd := strings.TrimPrefix(arg, "--build-command=")
898 // remove quotations
899 buildCmd = strings.TrimPrefix(buildCmd, "\"")
900 buildCmd = strings.TrimSuffix(buildCmd, "\"")
901 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000902 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
903 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
MarkDacek6614d9c2022-12-07 21:57:38 +0000904 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
905 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
906 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
907 if err == nil {
908 c.buildStartedTime = val
909 } else {
910 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
911 }
MarkDacekf47e1422023-04-19 16:47:36 +0000912 } else if arg == "--ensure-allowlist-integrity" {
913 c.ensureAllowlistIntegrity = true
MarkDacekd33c2fd2023-05-04 20:40:04 +0000914 } else if strings.HasPrefix(arg, "--bazel-exit-code=") {
915 bazelExitCodeStr := strings.TrimPrefix(arg, "--bazel-exit-code=")
916 val, err := strconv.Atoi(bazelExitCodeStr)
917 if err == nil {
918 c.bazelExitCode = int32(val)
919 } else {
920 ctx.Fatalf("Error parsing bazel-exit-code", err)
921 }
MarkDacek396491e2023-06-14 19:41:18 +0000922 } else if strings.HasPrefix(arg, "--bes-id=") {
923 c.besId = strings.TrimPrefix(arg, "--bes-id=")
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700924 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700925 parseArgNum := func(def int) int {
926 if len(arg) > 2 {
927 p, err := strconv.ParseUint(arg[2:], 10, 31)
928 if err != nil {
929 ctx.Fatalf("Failed to parse %q: %v", arg, err)
930 }
931 return int(p)
932 } else if i+1 < len(args) {
933 p, err := strconv.ParseUint(args[i+1], 10, 31)
934 if err == nil {
935 i++
936 return int(p)
937 }
938 }
939 return def
940 }
941
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700942 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700943 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700944 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700945 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700946 } else {
947 ctx.Fatalln("Unknown option:", arg)
948 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700949 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700950 if k == "OUT_DIR" {
951 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
952 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700953 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700954 } else if arg == "dist" {
955 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200956 } else if arg == "json-module-graph" {
957 c.jsonModuleGraph = true
958 } else if arg == "bp2build" {
959 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000960 } else if arg == "api_bp2build" {
961 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200962 } else if arg == "queryview" {
963 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200964 } else if arg == "soong_docs" {
965 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700966 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700967 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800968 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700969 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700970 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700971 }
972 }
Chris Parsons21f80272023-06-15 04:02:28 +0000973 if (!c.bazelProdMode) && (!c.bazelStagingMode) {
Chris Parsonsb6e96902022-10-31 20:08:45 -0400974 c.bazelProdMode = defaultBazelProdMode(c)
975 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700976}
977
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900978func validateNinjaWeightList(weightListFilePath string) (err error) {
979 data, err := os.ReadFile(weightListFilePath)
980 if err != nil {
981 return
982 }
983 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
984 for _, line := range lines {
985 fields := strings.Split(line, ",")
986 if len(fields) != 2 {
987 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
988 }
989 _, err = strconv.Atoi(fields[1])
990 if err != nil {
991 return
992 }
993 }
994 return
995}
996
Dan Willemsened869522018-01-08 14:58:46 -0800997func (c *configImpl) configureLocale(ctx Context) {
998 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
999 output, err := cmd.Output()
1000
1001 var locales []string
1002 if err == nil {
1003 locales = strings.Split(string(output), "\n")
1004 } else {
1005 // If we're unable to list the locales, let's assume en_US.UTF-8
1006 locales = []string{"en_US.UTF-8"}
1007 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
1008 }
1009
1010 // gettext uses LANGUAGE, which is passed directly through
1011
1012 // For LANG and LC_*, only preserve the evaluated version of
1013 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001014 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -08001015 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001016 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -08001017 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001018 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -08001019 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001020 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -08001021 }
1022
1023 c.environ.UnsetWithPrefix("LC_")
1024
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001025 if userLang != "" {
1026 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -08001027 }
1028
1029 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
1030 // for others)
1031 if inList("C.UTF-8", locales) {
1032 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -05001033 } else if inList("C.utf8", locales) {
1034 // These normalize to the same thing
1035 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -08001036 } else if inList("en_US.UTF-8", locales) {
1037 c.environ.Set("LANG", "en_US.UTF-8")
1038 } else if inList("en_US.utf8", locales) {
1039 // These normalize to the same thing
1040 c.environ.Set("LANG", "en_US.UTF-8")
1041 } else {
1042 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
1043 }
1044}
1045
Dan Willemsen1e704462016-08-21 15:17:17 -07001046func (c *configImpl) Environment() *Environment {
1047 return c.environ
1048}
1049
1050func (c *configImpl) Arguments() []string {
1051 return c.arguments
1052}
1053
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001054func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001055 if len(c.Arguments()) > 0 {
1056 // Explicit targets requested that are not special targets like b2pbuild
1057 // or the JSON module graph
1058 return true
1059 }
1060
Spandan Das5af0bd32022-09-28 20:43:08 +00001061 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001062 // Command line was empty, the default Ninja target is built
1063 return true
1064 }
1065
Liz Kammer88677422021-12-15 15:03:19 -05001066 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
1067 if c.Dist() && !c.Bp2Build() {
1068 return true
1069 }
1070
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001071 // build.ninja doesn't need to be generated
1072 return false
1073}
1074
Dan Willemsen1e704462016-08-21 15:17:17 -07001075func (c *configImpl) OutDir() string {
1076 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -07001077 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -07001078 }
1079 return "out"
1080}
1081
Dan Willemsen8a073a82017-02-04 17:30:44 -08001082func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -04001083 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001084}
1085
1086func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -07001087 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -08001088}
1089
Dan Willemsen1e704462016-08-21 15:17:17 -07001090func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001091 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001092 return c.arguments
1093 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001094 return c.ninjaArgs
1095}
1096
Jingwen Chen7c6089a2020-11-02 02:56:20 -05001097func (c *configImpl) BazelOutDir() string {
1098 return filepath.Join(c.OutDir(), "bazel")
1099}
1100
Liz Kammer2af5ea82022-11-11 14:21:03 -05001101func (c *configImpl) bazelOutputBase() string {
1102 return filepath.Join(c.BazelOutDir(), "output")
1103}
1104
Dan Willemsen1e704462016-08-21 15:17:17 -07001105func (c *configImpl) SoongOutDir() string {
1106 return filepath.Join(c.OutDir(), "soong")
1107}
1108
Spandan Das394aa322022-11-03 17:02:10 +00001109func (c *configImpl) ApiSurfacesOutDir() string {
1110 return filepath.Join(c.OutDir(), "api_surfaces")
1111}
1112
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001113func (c *configImpl) PrebuiltOS() string {
1114 switch runtime.GOOS {
1115 case "linux":
1116 return "linux-x86"
1117 case "darwin":
1118 return "darwin-x86"
1119 default:
1120 panic("Unknown GOOS")
1121 }
1122}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001123
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001124func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001125 if c.SkipKatiNinja() {
1126 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1127 } else {
1128 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1129 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001130}
1131
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001132func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001133 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001134}
1135
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001136func (c *configImpl) UsedEnvFile(tag string) string {
Kiyoung Kimeaa55a82023-06-05 16:56:49 +09001137 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1138 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+v+"."+tag)
1139 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001140 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1141}
1142
Lukacs T. Berkic541cd22022-10-26 07:26:50 +00001143func (c *configImpl) Bp2BuildFilesMarkerFile() string {
1144 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
1145}
1146
1147func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001148 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +02001149}
1150
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001151func (c *configImpl) SoongDocsHtml() string {
1152 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1153}
1154
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001155func (c *configImpl) QueryviewMarkerFile() string {
1156 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1157}
1158
Spandan Das5af0bd32022-09-28 20:43:08 +00001159func (c *configImpl) ApiBp2buildMarkerFile() string {
1160 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
1161}
1162
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001163func (c *configImpl) ModuleGraphFile() string {
1164 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1165}
1166
kgui67007242022-01-25 13:50:25 +08001167func (c *configImpl) ModuleActionsFile() string {
1168 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1169}
1170
Jeff Gastonefc1b412017-03-29 17:29:06 -07001171func (c *configImpl) TempDir() string {
1172 return shared.TempDirForOutDir(c.SoongOutDir())
1173}
1174
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001175func (c *configImpl) FileListDir() string {
1176 return filepath.Join(c.OutDir(), ".module_paths")
1177}
1178
Dan Willemsen1e704462016-08-21 15:17:17 -07001179func (c *configImpl) KatiSuffix() string {
1180 if c.katiSuffix != "" {
1181 return c.katiSuffix
1182 }
1183 panic("SetKatiSuffix has not been called")
1184}
1185
Colin Cross37193492017-11-16 17:55:00 -08001186// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1187// user is interested in additional checks at the expense of build time.
1188func (c *configImpl) Checkbuild() bool {
1189 return c.checkbuild
1190}
1191
Dan Willemsen8a073a82017-02-04 17:30:44 -08001192func (c *configImpl) Dist() bool {
1193 return c.dist
1194}
1195
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001196func (c *configImpl) JsonModuleGraph() bool {
1197 return c.jsonModuleGraph
1198}
1199
1200func (c *configImpl) Bp2Build() bool {
1201 return c.bp2build
1202}
1203
Spandan Das5af0bd32022-09-28 20:43:08 +00001204func (c *configImpl) ApiBp2build() bool {
1205 return c.apiBp2build
1206}
1207
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001208func (c *configImpl) Queryview() bool {
1209 return c.queryview
1210}
1211
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001212func (c *configImpl) SoongDocs() bool {
1213 return c.soongDocs
1214}
1215
Dan Willemsen1e704462016-08-21 15:17:17 -07001216func (c *configImpl) IsVerbose() bool {
1217 return c.verbose
1218}
1219
LaMont Jones52a72432023-03-09 18:19:35 +00001220func (c *configImpl) MultitreeBuild() bool {
1221 return c.multitreeBuild
1222}
1223
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001224func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1225 return c.ninjaWeightListSource
1226}
1227
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001228func (c *configImpl) SkipKati() bool {
1229 return c.skipKati
1230}
1231
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001232func (c *configImpl) SkipKatiNinja() bool {
1233 return c.skipKatiNinja
1234}
1235
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001236func (c *configImpl) SkipSoong() bool {
1237 return c.skipSoong
1238}
1239
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001240func (c *configImpl) SkipNinja() bool {
1241 return c.skipNinja
1242}
1243
Anton Hansson5a7861a2021-06-04 10:09:01 +01001244func (c *configImpl) SetSkipNinja(v bool) {
1245 c.skipNinja = v
1246}
1247
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001248func (c *configImpl) SkipConfig() bool {
1249 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001250}
1251
Jihoon Kang1bff0342023-01-17 20:40:22 +00001252func (c *configImpl) BuildFromTextStub() bool {
1253 return c.buildFromTextStub
1254}
1255
Dan Willemsen1e704462016-08-21 15:17:17 -07001256func (c *configImpl) TargetProduct() string {
1257 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1258 return v
1259 }
1260 panic("TARGET_PRODUCT is not defined")
1261}
1262
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001263func (c *configImpl) TargetProductOrErr() (string, error) {
1264 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1265 return v, nil
1266 }
1267 return "", fmt.Errorf("TARGET_PRODUCT is not defined")
1268}
1269
Dan Willemsen02781d52017-05-12 19:28:13 -07001270func (c *configImpl) TargetDevice() string {
1271 return c.targetDevice
1272}
1273
1274func (c *configImpl) SetTargetDevice(device string) {
1275 c.targetDevice = device
1276}
1277
1278func (c *configImpl) TargetBuildVariant() string {
1279 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1280 return v
1281 }
1282 panic("TARGET_BUILD_VARIANT is not defined")
1283}
1284
Dan Willemsen1e704462016-08-21 15:17:17 -07001285func (c *configImpl) KatiArgs() []string {
1286 return c.katiArgs
1287}
1288
1289func (c *configImpl) Parallel() int {
1290 return c.parallel
1291}
1292
Sam Delmerico98a73292023-02-21 11:50:29 -05001293func (c *configImpl) GetSourceRootDirs() []string {
1294 return c.sourceRootDirs
1295}
1296
1297func (c *configImpl) SetSourceRootDirs(i []string) {
1298 c.sourceRootDirs = i
1299}
1300
Spandan Dasc5763832022-11-08 18:42:16 +00001301func (c *configImpl) GetIncludeTags() []string {
1302 return c.includeTags
1303}
1304
1305func (c *configImpl) SetIncludeTags(i []string) {
1306 c.includeTags = i
1307}
1308
MarkDacek6614d9c2022-12-07 21:57:38 +00001309func (c *configImpl) GetLogsPrefix() string {
1310 return c.logsPrefix
1311}
1312
1313func (c *configImpl) SetLogsPrefix(prefix string) {
1314 c.logsPrefix = prefix
1315}
1316
Colin Cross8b8bec32019-11-15 13:18:43 -08001317func (c *configImpl) HighmemParallel() int {
1318 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1319 return i
1320 }
1321
1322 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1323 parallel := c.Parallel()
1324 if c.UseRemoteBuild() {
1325 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1326 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1327 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1328 // Return 1/16th of the size of the local pool, rounding up.
1329 return (parallel + 15) / 16
1330 } else if c.totalRAM == 0 {
1331 // Couldn't detect the total RAM, don't restrict highmem processes.
1332 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001333 } else if c.totalRAM <= 16*1024*1024*1024 {
1334 // Less than 16GB of ram, restrict to 1 highmem processes
1335 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001336 } else if c.totalRAM <= 32*1024*1024*1024 {
1337 // Less than 32GB of ram, restrict to 2 highmem processes
1338 return 2
1339 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1340 // If less than 8GB total RAM per process, reduce the number of highmem processes
1341 return p
1342 }
1343 // No restriction on highmem processes
1344 return parallel
1345}
1346
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001347func (c *configImpl) TotalRAM() uint64 {
1348 return c.totalRAM
1349}
1350
Kousik Kumarec478642020-09-21 13:39:24 -04001351// ForceUseGoma determines whether we should override Goma deprecation
1352// and use Goma for the current build or not.
1353func (c *configImpl) ForceUseGoma() bool {
1354 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1355 v = strings.TrimSpace(v)
1356 if v != "" && v != "false" {
1357 return true
1358 }
1359 }
1360 return false
1361}
1362
Dan Willemsen1e704462016-08-21 15:17:17 -07001363func (c *configImpl) UseGoma() bool {
1364 if v, ok := c.environ.Get("USE_GOMA"); ok {
1365 v = strings.TrimSpace(v)
1366 if v != "" && v != "false" {
1367 return true
1368 }
1369 }
1370 return false
1371}
1372
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001373func (c *configImpl) StartGoma() bool {
1374 if !c.UseGoma() {
1375 return false
1376 }
1377
1378 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1379 v = strings.TrimSpace(v)
1380 if v != "" && v != "false" {
1381 return false
1382 }
1383 }
1384 return true
1385}
1386
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001387func (c *configImpl) canSupportRBE() bool {
1388 // Do not use RBE with prod credentials in scenarios when stubby doesn't exist, since
1389 // its unlikely that we will be able to obtain necessary creds without stubby.
1390 authType, _ := c.rbeAuth()
1391 if !c.StubbyExists() && strings.Contains(authType, "use_google_prod_creds") {
1392 return false
1393 }
1394 return true
1395}
1396
Ramy Medhatbbf25672019-07-17 12:30:04 +00001397func (c *configImpl) UseRBE() bool {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001398 // These alternate modes of running Soong do not use RBE / reclient.
1399 if c.Bp2Build() || c.Queryview() || c.ApiBp2build() || c.JsonModuleGraph() {
1400 return false
1401 }
1402
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001403 if !c.canSupportRBE() {
Kousik Kumar67ad4342023-06-06 15:09:27 -04001404 return false
1405 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001406
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001407 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001408 v = strings.TrimSpace(v)
1409 if v != "" && v != "false" {
1410 return true
1411 }
1412 }
1413 return false
1414}
1415
Chris Parsonsef615e52022-08-18 22:04:11 -04001416func (c *configImpl) BazelBuildEnabled() bool {
Chris Parsons21f80272023-06-15 04:02:28 +00001417 return c.bazelProdMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001418}
1419
Ramy Medhatbbf25672019-07-17 12:30:04 +00001420func (c *configImpl) StartRBE() bool {
1421 if !c.UseRBE() {
1422 return false
1423 }
1424
1425 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1426 v = strings.TrimSpace(v)
1427 if v != "" && v != "false" {
1428 return false
1429 }
1430 }
1431 return true
1432}
1433
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001434func (c *configImpl) rbeProxyLogsDir() string {
1435 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001436 if v, ok := c.environ.Get(f); ok {
1437 return v
1438 }
1439 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001440 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1441 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001442}
1443
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001444func (c *configImpl) rbeCacheDir() string {
1445 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1446 if v, ok := c.environ.Get(f); ok {
1447 return v
1448 }
1449 }
1450 return shared.JoinPath(c.SoongOutDir(), "rbe")
1451}
1452
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001453func (c *configImpl) shouldCleanupRBELogsDir() bool {
1454 // Perform a log directory cleanup only when the log directory
1455 // is auto created by the build rather than user-specified.
1456 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1457 if _, ok := c.environ.Get(f); ok {
1458 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001459 }
1460 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001461 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001462}
1463
1464func (c *configImpl) rbeExecRoot() string {
1465 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1466 if v, ok := c.environ.Get(f); ok {
1467 return v
1468 }
1469 }
1470 wd, err := os.Getwd()
1471 if err != nil {
1472 return ""
1473 }
1474 return wd
1475}
1476
1477func (c *configImpl) rbeDir() string {
1478 if v, ok := c.environ.Get("RBE_DIR"); ok {
1479 return v
1480 }
1481 return "prebuilts/remoteexecution-client/live/"
1482}
1483
1484func (c *configImpl) rbeReproxy() string {
1485 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1486 if v, ok := c.environ.Get(f); ok {
1487 return v
1488 }
1489 }
1490 return filepath.Join(c.rbeDir(), "reproxy")
1491}
1492
1493func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001494 credFlags := []string{
1495 "use_application_default_credentials",
1496 "use_gce_credentials",
1497 "credential_file",
1498 "use_google_prod_creds",
1499 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001500 for _, cf := range credFlags {
1501 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1502 if v, ok := c.environ.Get(f); ok {
1503 v = strings.TrimSpace(v)
1504 if v != "" && v != "false" && v != "0" {
1505 return "RBE_" + cf, v
1506 }
1507 }
1508 }
1509 }
1510 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001511}
1512
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001513func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1514 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1515 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1516
1517 name := filepath.Join(dir, base)
1518 if len(name) < maxNameLen {
1519 return name, nil
1520 }
1521
1522 name = filepath.Join("/tmp", base)
1523 if len(name) < maxNameLen {
1524 return name, nil
1525 }
1526
1527 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1528}
1529
Kousik Kumar7bc78192022-04-27 14:52:56 -04001530// IsGooglerEnvironment returns true if the current build is running
1531// on a Google developer machine and false otherwise.
1532func (c *configImpl) IsGooglerEnvironment() bool {
1533 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1534 if v, ok := c.environ.Get(cf); ok {
1535 return v == "googler"
1536 }
1537 return false
1538}
1539
1540// GoogleProdCredsExist determine whether credentials exist on the
1541// Googler machine to use remote execution.
1542func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001543 if googleProdCredsExistCache {
1544 return googleProdCredsExistCache
1545 }
andusyu0b3dc032023-06-21 17:29:32 -04001546 if _, err := exec.Command("/usr/bin/gcertstatus", "-nocheck_ssh").Output(); err != nil {
Kousik Kumar7bc78192022-04-27 14:52:56 -04001547 return false
1548 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001549 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001550 return true
1551}
1552
1553// UseRemoteBuild indicates whether to use a remote build acceleration system
1554// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001555func (c *configImpl) UseRemoteBuild() bool {
1556 return c.UseGoma() || c.UseRBE()
1557}
1558
Kousik Kumar7bc78192022-04-27 14:52:56 -04001559// StubbyExists checks whether the stubby binary exists on the machine running
1560// the build.
1561func (c *configImpl) StubbyExists() bool {
1562 if _, err := exec.LookPath("stubby"); err != nil {
1563 return false
1564 }
1565 return true
1566}
1567
Dan Willemsen1e704462016-08-21 15:17:17 -07001568// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001569// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001570// still limited by Parallel()
1571func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001572 if !c.UseRemoteBuild() {
1573 return 0
1574 }
1575 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1576 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001577 }
1578 return 500
1579}
1580
1581func (c *configImpl) SetKatiArgs(args []string) {
1582 c.katiArgs = args
1583}
1584
1585func (c *configImpl) SetNinjaArgs(args []string) {
1586 c.ninjaArgs = args
1587}
1588
1589func (c *configImpl) SetKatiSuffix(suffix string) {
1590 c.katiSuffix = suffix
1591}
1592
Dan Willemsene0879fc2017-08-04 15:06:27 -07001593func (c *configImpl) LastKatiSuffixFile() string {
1594 return filepath.Join(c.OutDir(), "last_kati_suffix")
1595}
1596
1597func (c *configImpl) HasKatiSuffix() bool {
1598 return c.katiSuffix != ""
1599}
1600
Dan Willemsen1e704462016-08-21 15:17:17 -07001601func (c *configImpl) KatiEnvFile() string {
1602 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1603}
1604
Dan Willemsen29971232018-09-26 14:58:30 -07001605func (c *configImpl) KatiBuildNinjaFile() string {
1606 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001607}
1608
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001609func (c *configImpl) KatiPackageNinjaFile() string {
1610 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1611}
1612
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001613func (c *configImpl) SoongVarsFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001614 targetProduct, err := c.TargetProductOrErr()
1615 if err != nil {
1616 return filepath.Join(c.SoongOutDir(), "soong.variables")
1617 } else {
1618 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+".variables")
1619 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001620}
1621
Dan Willemsen1e704462016-08-21 15:17:17 -07001622func (c *configImpl) SoongNinjaFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001623 targetProduct, err := c.TargetProductOrErr()
1624 if err != nil {
1625 return filepath.Join(c.SoongOutDir(), "build.ninja")
1626 } else {
1627 return filepath.Join(c.SoongOutDir(), "build."+targetProduct+".ninja")
1628 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001629}
1630
1631func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001632 if c.katiSuffix == "" {
1633 return filepath.Join(c.OutDir(), "combined.ninja")
1634 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001635 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1636}
1637
1638func (c *configImpl) SoongAndroidMk() string {
1639 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1640}
1641
1642func (c *configImpl) SoongMakeVarsMk() string {
1643 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1644}
1645
Dan Willemsenf052f782017-05-18 15:29:04 -07001646func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001647 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001648}
1649
Dan Willemsen02781d52017-05-12 19:28:13 -07001650func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001651 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1652}
1653
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001654func (c *configImpl) KatiPackageMkDir() string {
1655 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1656}
1657
Dan Willemsenf052f782017-05-18 15:29:04 -07001658func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001659 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001660}
1661
1662func (c *configImpl) HostOut() string {
1663 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1664}
1665
1666// This probably needs to be multi-valued, so not exporting it for now
1667func (c *configImpl) hostCrossOut() string {
1668 if runtime.GOOS == "linux" {
1669 return filepath.Join(c.hostOutRoot(), "windows-x86")
1670 } else {
1671 return ""
1672 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001673}
1674
Dan Willemsen1e704462016-08-21 15:17:17 -07001675func (c *configImpl) HostPrebuiltTag() string {
1676 if runtime.GOOS == "linux" {
1677 return "linux-x86"
1678 } else if runtime.GOOS == "darwin" {
1679 return "darwin-x86"
1680 } else {
1681 panic("Unsupported OS")
1682 }
1683}
Dan Willemsenf173d592017-04-27 14:28:00 -07001684
Dan Willemsen8122bd52017-10-12 20:20:41 -07001685func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001686 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1687 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001688 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1689 if _, err := os.Stat(asan); err == nil {
1690 return asan
1691 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001692 }
1693 }
1694 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1695}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001696
1697func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1698 c.brokenDupRules = val
1699}
1700
1701func (c *configImpl) BuildBrokenDupRules() bool {
1702 return c.brokenDupRules
1703}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001704
Dan Willemsen25e6f092019-04-09 10:22:43 -07001705func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1706 c.brokenUsesNetwork = val
1707}
1708
1709func (c *configImpl) BuildBrokenUsesNetwork() bool {
1710 return c.brokenUsesNetwork
1711}
1712
Dan Willemsene3336352020-01-02 19:10:38 -08001713func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1714 c.brokenNinjaEnvVars = val
1715}
1716
1717func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1718 return c.brokenNinjaEnvVars
1719}
1720
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001721func (c *configImpl) SetTargetDeviceDir(dir string) {
1722 c.targetDeviceDir = dir
1723}
1724
1725func (c *configImpl) TargetDeviceDir() string {
1726 return c.targetDeviceDir
1727}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001728
Patrice Arruda219eef32020-06-01 17:29:30 +00001729func (c *configImpl) BuildDateTime() string {
1730 return c.buildDateTime
1731}
1732
1733func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001734 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001735}
Patrice Arruda83842d72020-12-08 19:42:08 +00001736
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001737// LogsDir returns the absolute path to the logs directory where build log and
1738// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001739// directory. If the argument dist is specified, the logs directory
1740// is <dist_dir>/logs.
1741func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001742 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001743 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001744 // 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 -05001745 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001746 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001747 absDir, err := filepath.Abs(dir)
1748 if err != nil {
1749 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1750 os.Exit(1)
1751 }
1752 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001753}
1754
1755// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1756// where the bazel profiles are located.
1757func (c *configImpl) BazelMetricsDir() string {
1758 return filepath.Join(c.LogsDir(), "bazel_metrics")
1759}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001760
Chris Parsons53f68ae2022-03-03 12:01:40 -05001761// MkFileMetrics returns the file path for make-related metrics.
1762func (c *configImpl) MkMetrics() string {
1763 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1764}
1765
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001766func (c *configImpl) SetEmptyNinjaFile(v bool) {
1767 c.emptyNinjaFile = v
1768}
1769
1770func (c *configImpl) EmptyNinjaFile() bool {
1771 return c.emptyNinjaFile
1772}
Yu Liu6e13b402021-07-27 14:29:06 -07001773
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001774func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1775 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1776}
1777
Chris Parsons9402ca82023-02-23 17:28:06 -05001778func (c *configImpl) IsPersistentBazelEnabled() bool {
1779 return c.Environment().IsEnvTrue("USE_PERSISTENT_BAZEL")
1780}
1781
Chris Parsonsc83398f2023-05-31 18:41:41 +00001782// GetBazeliskBazelVersion returns the Bazel version to use for this build,
1783// or the empty string if the current canonical prod Bazel should be used.
1784// This environment variable should only be set to debug the build system.
1785// The Bazel version, if set, will be passed to Bazelisk, and Bazelisk will
1786// handle downloading and invoking the correct Bazel binary.
1787func (c *configImpl) GetBazeliskBazelVersion() string {
1788 value, _ := c.Environment().Get("USE_BAZEL_VERSION")
1789 return value
1790}
1791
MarkDacekd06db5d2022-11-29 00:47:59 +00001792func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1793 return c.bazelForceEnabledModules
1794}
1795
MarkDacekd0e7cd32022-12-02 22:22:40 +00001796func (c *configImpl) SkipMetricsUpload() bool {
1797 return c.skipMetricsUpload
1798}
1799
MarkDacekf47e1422023-04-19 16:47:36 +00001800func (c *configImpl) EnsureAllowlistIntegrity() bool {
1801 return c.ensureAllowlistIntegrity
1802}
1803
MarkDacek6614d9c2022-12-07 21:57:38 +00001804// Returns a Time object if one was passed via a command-line flag.
1805// Otherwise returns the passed default.
1806func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1807 if c.buildStartedTime == 0 {
1808 return defaultTime
1809 }
1810 return time.UnixMilli(c.buildStartedTime)
1811}
1812
MarkDacekd33c2fd2023-05-04 20:40:04 +00001813func (c *configImpl) BazelExitCode() int32 {
1814 return c.bazelExitCode
1815}
1816
Yu Liu6e13b402021-07-27 14:29:06 -07001817func GetMetricsUploader(topDir string, env *Environment) string {
1818 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1819 metricsUploader := filepath.Join(topDir, p)
1820 if _, err := os.Stat(metricsUploader); err == nil {
1821 return metricsUploader
1822 }
1823 }
1824
1825 return ""
1826}