blob: d8a2788ee4917d3272ab397c6d227fd4d7ea9136 [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 (
Kevin Dagostino096ab2f2023-03-03 19:47:17 +000048 rbeRandPrefix int
49 googleProdCredsExistCache bool
Kousik Kumar4c180ad2022-05-27 07:48:37 -040050)
51
52func init() {
53 rand.Seed(time.Now().UnixNano())
54 rbeRandPrefix = rand.Intn(1000)
55}
56
Dan Willemsen1e704462016-08-21 15:17:17 -070057type Config struct{ *configImpl }
58
59type configImpl struct {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020060 // Some targets that are implemented in soong_build
61 // (bp2build, json-module-graph) are not here and have their own bits below.
Colin Cross28f527c2019-11-26 16:19:04 -080062 arguments []string
63 goma bool
64 environ *Environment
65 distDir string
66 buildDateTime string
MarkDacek6614d9c2022-12-07 21:57:38 +000067 logsPrefix string
Dan Willemsen1e704462016-08-21 15:17:17 -070068
69 // From the arguments
MarkDacekd0e7cd32022-12-02 22:22:40 +000070 parallel int
71 keepGoing int
72 verbose bool
73 checkbuild bool
74 dist bool
75 jsonModuleGraph bool
76 apiBp2build bool // Generate BUILD files for Soong modules that contribute APIs
77 bp2build bool
78 queryview bool
79 reportMkMetrics bool // Collect and report mk2bp migration progress metrics.
80 soongDocs bool
LaMont Jones52a72432023-03-09 18:19:35 +000081 multitreeBuild bool // This is a multitree build.
MarkDacekd0e7cd32022-12-02 22:22:40 +000082 skipConfig bool
83 skipKati bool
84 skipKatiNinja bool
85 skipSoong bool
86 skipNinja bool
87 skipSoongTests bool
88 searchApiDir bool // Scan the Android.bp files generated in out/api_surfaces
89 skipMetricsUpload bool
MarkDacek6614d9c2022-12-07 21:57:38 +000090 buildStartedTime int64 // For metrics-upload-only - manually specify a build-started time
Dan Willemsen1e704462016-08-21 15:17:17 -070091
92 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070093 katiArgs []string
94 ninjaArgs []string
95 katiSuffix string
96 targetDevice string
97 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +000098 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -070099
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800100 // Autodetected
101 totalRAM uint64
102
Dan Willemsene3336352020-01-02 19:10:38 -0800103 brokenDupRules bool
104 brokenUsesNetwork bool
105 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -0700106
107 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000108
MarkDacekb78465d2022-10-18 20:10:16 +0000109 bazelProdMode bool
110 bazelDevMode bool
111 bazelStagingMode bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000112
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700113 // Set by multiproduct_kati
114 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700115
116 metricsUploader string
MarkDacekd06db5d2022-11-29 00:47:59 +0000117
118 bazelForceEnabledModules string
Spandan Dasc5763832022-11-08 18:42:16 +0000119
120 includeTags []string
Dan Willemsen1e704462016-08-21 15:17:17 -0700121}
122
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800123const srcDirFileCheck = "build/soong/root.bp"
124
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700125var buildFiles = []string{"Android.mk", "Android.bp"}
126
Patrice Arruda13848222019-04-22 17:12:02 -0700127type BuildAction uint
128
129const (
130 // Builds all of the modules and their dependencies of a specified directory, relative to the root
131 // directory of the source tree.
132 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
133
134 // Builds all of the modules and their dependencies of a list of specified directories. All specified
135 // directories are relative to the root directory of the source tree.
136 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700137
138 // Build a list of specified modules. If none was specified, simply build the whole source tree.
139 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700140)
141
142// checkTopDir validates that the current directory is at the root directory of the source tree.
143func checkTopDir(ctx Context) {
144 if _, err := os.Stat(srcDirFileCheck); err != nil {
145 if os.IsNotExist(err) {
146 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
147 }
148 ctx.Fatalln("Error verifying tree state:", err)
149 }
150}
151
Kousik Kumarc8818332023-01-16 16:33:05 +0000152// fetchEnvConfig optionally fetches a configuration file that can then subsequently be
153// loaded into Soong environment to control certain aspects of build behavior (e.g., enabling RBE).
154// If a configuration file already exists on disk, the fetch is run in the background
155// so as to NOT block the rest of the build execution.
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500156func fetchEnvConfig(ctx Context, config *configImpl, envConfigName string) error {
David Goldsmith62243a32022-04-08 13:42:04 +0000157 configName := envConfigName + "." + jsonSuffix
Kousik Kumarc75e1292022-07-07 02:20:51 +0000158 expConfigFetcher := &smpb.ExpConfigFetcher{Filename: &configName}
David Goldsmith62243a32022-04-08 13:42:04 +0000159 defer func() {
160 ctx.Metrics.ExpConfigFetcher(expConfigFetcher)
161 }()
Kousik Kumarc75e1292022-07-07 02:20:51 +0000162 if !config.GoogleProdCredsExist() {
163 status := smpb.ExpConfigFetcher_MISSING_GCERT
164 expConfigFetcher.Status = &status
165 return nil
166 }
David Goldsmith62243a32022-04-08 13:42:04 +0000167
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500168 s, err := os.Stat(configFetcher)
169 if err != nil {
170 if os.IsNotExist(err) {
171 return nil
172 }
173 return err
174 }
175 if s.Mode()&0111 == 0 {
David Goldsmith62243a32022-04-08 13:42:04 +0000176 status := smpb.ExpConfigFetcher_ERROR
177 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500178 return fmt.Errorf("configuration fetcher binary %v is not executable: %v", configFetcher, s.Mode())
179 }
180
Kousik Kumarc8818332023-01-16 16:33:05 +0000181 configExists := false
182 outConfigFilePath := filepath.Join(config.OutDir(), configName)
183 if _, err := os.Stat(outConfigFilePath); err == nil {
184 configExists = true
185 }
186
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500187 tCtx, cancel := context.WithTimeout(ctx, envConfigFetchTimeout)
David Goldsmith62243a32022-04-08 13:42:04 +0000188 fetchStart := time.Now()
189 cmd := exec.CommandContext(tCtx, configFetcher, "-output_config_dir", config.OutDir(),
190 "-output_config_name", configName)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500191 if err := cmd.Start(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000192 status := smpb.ExpConfigFetcher_ERROR
193 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500194 return err
195 }
196
Kousik Kumarc8818332023-01-16 16:33:05 +0000197 fetchCfg := func() error {
198 if err := cmd.Wait(); err != nil {
199 status := smpb.ExpConfigFetcher_ERROR
200 expConfigFetcher.Status = &status
201 return err
202 }
203 fetchEnd := time.Now()
204 expConfigFetcher.Micros = proto.Uint64(uint64(fetchEnd.Sub(fetchStart).Microseconds()))
205 expConfigFetcher.Filename = proto.String(outConfigFilePath)
206
207 if _, err := os.Stat(outConfigFilePath); err != nil {
208 status := smpb.ExpConfigFetcher_NO_CONFIG
209 expConfigFetcher.Status = &status
210 return err
211 }
David Goldsmith62243a32022-04-08 13:42:04 +0000212 status := smpb.ExpConfigFetcher_CONFIG
213 expConfigFetcher.Status = &status
Kousik Kumarc8818332023-01-16 16:33:05 +0000214 return nil
David Goldsmith62243a32022-04-08 13:42:04 +0000215 }
Kousik Kumarc8818332023-01-16 16:33:05 +0000216
217 // If a config file does not exist, wait for the config file to be fetched. Otherwise
218 // fetch the config file in the background and return immediately.
219 if !configExists {
220 defer cancel()
221 return fetchCfg()
222 }
223
224 go func() {
225 defer cancel()
226 if err := fetchCfg(); err != nil {
227 ctx.Verbosef("Failed to fetch config file %v: %v\n", configName, err)
228 }
229 }()
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500230 return nil
231}
232
MarkDacek7901e582023-01-09 19:48:01 +0000233func loadEnvConfig(ctx Context, config *configImpl, bc string) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500234 if bc == "" {
235 return nil
236 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500237
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500238 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500239 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500240 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500241 envConfigDir,
242 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500243 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500244 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
245 envVarsJSON, err := ioutil.ReadFile(cfgFile)
246 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500247 continue
248 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500249 ctx.Verbosef("Loading config file %v\n", cfgFile)
250 var envVars map[string]map[string]string
251 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
252 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
253 continue
254 }
255 for k, v := range envVars["env"] {
256 if os.Getenv(k) != "" {
257 continue
258 }
259 config.environ.Set(k, v)
260 }
261 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
262 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500263 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500264
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500265 return nil
266}
267
Chris Parsonsb6e96902022-10-31 20:08:45 -0400268func defaultBazelProdMode(cfg *configImpl) bool {
MarkDacekd06db5d2022-11-29 00:47:59 +0000269 // Environment flag to disable Bazel for users which experience
Chris Parsonsb6e96902022-10-31 20:08:45 -0400270 // broken bazel-handled builds, or significant performance regressions.
271 if cfg.IsBazelMixedBuildForceDisabled() {
272 return false
273 }
274 // Darwin-host builds are currently untested with Bazel.
275 if runtime.GOOS == "darwin" {
276 return false
277 }
Chris Parsons035e03a2022-11-01 14:25:45 -0400278 return true
Chris Parsonsb6e96902022-10-31 20:08:45 -0400279}
280
MarkDacek6614d9c2022-12-07 21:57:38 +0000281func UploadOnlyConfig(ctx Context, _ ...string) Config {
282 ret := &configImpl{
283 environ: OsEnvironment(),
284 sandboxConfig: &SandboxConfig{},
285 }
MarkDacek7901e582023-01-09 19:48:01 +0000286 srcDir := absPath(ctx, ".")
287 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
288 if err := loadEnvConfig(ctx, ret, bc); err != nil {
289 ctx.Fatalln("Failed to parse env config files: %v", err)
290 }
291 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
MarkDacek6614d9c2022-12-07 21:57:38 +0000292 return Config{ret}
293}
294
Dan Willemsen1e704462016-08-21 15:17:17 -0700295func NewConfig(ctx Context, args ...string) Config {
296 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000297 environ: OsEnvironment(),
298 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700299 }
300
Patrice Arruda90109172020-07-28 18:07:27 +0000301 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700302 ret.parallel = runtime.NumCPU() + 2
303 ret.keepGoing = 1
304
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800305 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700306 ret.parseArgs(ctx, args)
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800307 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700308 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
309 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
310 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800311 outDir := "out"
312 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
313 if wd, err := os.Getwd(); err != nil {
314 ctx.Fatalln("Failed to get working directory:", err)
315 } else {
316 outDir = filepath.Join(baseDir, filepath.Base(wd))
317 }
318 }
319 ret.environ.Set("OUT_DIR", outDir)
320 }
321
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500322 // loadEnvConfig needs to know what the OUT_DIR is, so it should
323 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000324 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
325
326 if bc != "" {
327 if err := fetchEnvConfig(ctx, ret, bc); err != nil {
328 ctx.Verbosef("Failed to fetch config file: %v\n", err)
Kousik Kumarc8818332023-01-16 16:33:05 +0000329 }
330 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000331 ctx.Fatalln("Failed to parse env config files: %v", err)
332 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500333 }
334
Dan Willemsen2d31a442018-10-20 21:33:41 -0700335 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
336 ret.distDir = filepath.Clean(distDir)
337 } else {
338 ret.distDir = filepath.Join(ret.OutDir(), "dist")
339 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700340
Spandan Das05063612021-06-25 01:39:04 +0000341 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
342 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
343 }
344
Dan Willemsen1e704462016-08-21 15:17:17 -0700345 ret.environ.Unset(
346 // We're already using it
347 "USE_SOONG_UI",
348
349 // We should never use GOROOT/GOPATH from the shell environment
350 "GOROOT",
351 "GOPATH",
352
353 // These should only come from Soong, not the environment.
354 "CLANG",
355 "CLANG_CXX",
356 "CCC_CC",
357 "CCC_CXX",
358
359 // Used by the goma compiler wrapper, but should only be set by
360 // gomacc
361 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800362
363 // We handle this above
364 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700365
Dan Willemsen2d31a442018-10-20 21:33:41 -0700366 // This is handled above too, and set for individual commands later
367 "DIST_DIR",
368
Dan Willemsen68a09852017-04-18 13:56:57 -0700369 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000370 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700371 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700372 "DISPLAY",
373 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000374 "JAVAC",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700375 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700376 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700377
378 // Drop make flags
379 "MAKEFLAGS",
380 "MAKELEVEL",
381 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700382
383 // Set in envsetup.sh, reset in makefiles
384 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700385
386 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
387 "ANDROID_BUILD_TOP",
388 "ANDROID_HOST_OUT",
389 "ANDROID_PRODUCT_OUT",
390 "ANDROID_HOST_OUT_TESTCASES",
391 "ANDROID_TARGET_OUT_TESTCASES",
392 "ANDROID_TOOLCHAIN",
393 "ANDROID_TOOLCHAIN_2ND_ARCH",
394 "ANDROID_DEV_SCRIPTS",
395 "ANDROID_EMULATOR_PREBUILTS",
396 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700397 )
398
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400399 if ret.UseGoma() || ret.ForceUseGoma() {
400 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
401 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400402 }
403
Dan Willemsen1e704462016-08-21 15:17:17 -0700404 // Tell python not to spam the source tree with .pyc files.
405 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
406
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400407 tmpDir := absPath(ctx, ret.TempDir())
408 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800409
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700410 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
411 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
412 "llvm-binutils-stable/llvm-symbolizer")
413 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
414
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800415 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700416 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800417
Yu Liu6e13b402021-07-27 14:29:06 -0700418 srcDir := absPath(ctx, ".")
419 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700420 ctx.Println("You are building in a directory whose absolute path contains a space character:")
421 ctx.Println()
422 ctx.Printf("%q\n", srcDir)
423 ctx.Println()
424 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700425 }
426
Yu Liu6e13b402021-07-27 14:29:06 -0700427 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
428
Dan Willemsendb8457c2017-05-12 16:38:17 -0700429 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700430 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
431 ctx.Println()
432 ctx.Printf("%q\n", outDir)
433 ctx.Println()
434 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700435 }
436
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000437 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700438 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
439 ctx.Println()
440 ctx.Printf("%q\n", distDir)
441 ctx.Println()
442 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700443 }
444
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700445 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000446 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
447 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100448 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800449 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700450 javaHome := func() string {
451 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
452 return override
453 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000454 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
455 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 +0100456 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000457 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
458 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
459 }
460 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700461 }()
462 absJavaHome := absPath(ctx, javaHome)
463
Dan Willemsened869522018-01-08 14:58:46 -0800464 ret.configureLocale(ctx)
465
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700466 newPath := []string{filepath.Join(absJavaHome, "bin")}
467 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
468 newPath = append(newPath, path)
469 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100470
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700471 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
472 ret.environ.Set("JAVA_HOME", absJavaHome)
473 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000474 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
475 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100476 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700477 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
478
LaMont Jones52a72432023-03-09 18:19:35 +0000479 if ret.MultitreeBuild() {
480 ret.environ.Set("MULTITREE_BUILD", "true")
481 }
482
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800483 outDir := ret.OutDir()
484 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800485 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800486 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800487 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800488 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800489 }
Colin Cross28f527c2019-11-26 16:19:04 -0800490
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800491 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
492
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400493 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400494 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400495 ret.environ.Set(k, v)
496 }
497 }
498
Patrice Arruda83842d72020-12-08 19:42:08 +0000499 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800500 if err := os.RemoveAll(bpd); err != nil {
501 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
502 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000503
Patrice Arruda96850362020-08-11 20:41:11 +0000504 c := Config{ret}
505 storeConfigMetrics(ctx, c)
506 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700507}
508
Patrice Arruda13848222019-04-22 17:12:02 -0700509// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
510// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700511func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
512 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700513}
514
Patrice Arruda96850362020-08-11 20:41:11 +0000515// storeConfigMetrics selects a set of configuration information and store in
516// the metrics system for further analysis.
517func storeConfigMetrics(ctx Context, config Config) {
518 if ctx.Metrics == nil {
519 return
520 }
521
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400522 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000523
524 s := &smpb.SystemResourceInfo{
525 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
526 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
527 }
528 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000529}
530
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400531func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700532 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400533 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
534 UseGoma: proto.Bool(config.UseGoma()),
535 UseRbe: proto.Bool(config.UseRBE()),
536 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
537 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400538 }
Yu Liue737a992021-10-04 13:21:41 -0700539 c.Targets = append(c.Targets, config.arguments...)
540
541 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400542}
543
Patrice Arruda13848222019-04-22 17:12:02 -0700544// getConfigArgs processes the command arguments based on the build action and creates a set of new
545// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700546func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700547 // The next block of code verifies that the current directory is the root directory of the source
548 // tree. It then finds the relative path of dir based on the root directory of the source tree
549 // and verify that dir is inside of the source tree.
550 checkTopDir(ctx)
551 topDir, err := os.Getwd()
552 if err != nil {
553 ctx.Fatalf("Error retrieving top directory: %v", err)
554 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700555 dir, err = filepath.EvalSymlinks(dir)
556 if err != nil {
557 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
558 }
Patrice Arruda13848222019-04-22 17:12:02 -0700559 dir, err = filepath.Abs(dir)
560 if err != nil {
561 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
562 }
563 relDir, err := filepath.Rel(topDir, dir)
564 if err != nil {
565 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
566 }
567 // If there are ".." in the path, it's not in the source tree.
568 if strings.Contains(relDir, "..") {
569 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
570 }
571
572 configArgs := args[:]
573
574 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
575 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
576 targetNamePrefix := "MODULES-IN-"
577 if inList("GET-INSTALL-PATH", configArgs) {
578 targetNamePrefix = "GET-INSTALL-PATH-IN-"
579 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
580 }
581
Patrice Arruda13848222019-04-22 17:12:02 -0700582 var targets []string
583
584 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700585 case BUILD_MODULES:
586 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700587 case BUILD_MODULES_IN_A_DIRECTORY:
588 // If dir is the root source tree, all the modules are built of the source tree are built so
589 // no need to find the build file.
590 if topDir == dir {
591 break
592 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700593
Patrice Arruda13848222019-04-22 17:12:02 -0700594 buildFile := findBuildFile(ctx, relDir)
595 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700596 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700597 }
Patrice Arruda13848222019-04-22 17:12:02 -0700598 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
599 case BUILD_MODULES_IN_DIRECTORIES:
600 newConfigArgs, dirs := splitArgs(configArgs)
601 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700602 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700603 }
604
605 // Tidy only override all other specified targets.
606 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
607 if tidyOnly == "true" || tidyOnly == "1" {
608 configArgs = append(configArgs, "tidy_only")
609 } else {
610 configArgs = append(configArgs, targets...)
611 }
612
613 return configArgs
614}
615
616// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
617func convertToTarget(dir string, targetNamePrefix string) string {
618 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
619}
620
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700621// hasBuildFile returns true if dir contains an Android build file.
622func hasBuildFile(ctx Context, dir string) bool {
623 for _, buildFile := range buildFiles {
624 _, err := os.Stat(filepath.Join(dir, buildFile))
625 if err == nil {
626 return true
627 }
628 if !os.IsNotExist(err) {
629 ctx.Fatalf("Error retrieving the build file stats: %v", err)
630 }
631 }
632 return false
633}
634
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700635// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
636// in the current and any sub directory of dir. If a build file is not found, traverse the path
637// up by one directory and repeat again until either a build file is found or reached to the root
638// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
639// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700640func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700641 // If the string is empty or ".", assume it is top directory of the source tree.
642 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700643 return ""
644 }
645
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700646 found := false
647 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
648 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
649 if err != nil {
650 return err
651 }
652 if found {
653 return filepath.SkipDir
654 }
655 if info.IsDir() {
656 return nil
657 }
658 for _, buildFile := range buildFiles {
659 if info.Name() == buildFile {
660 found = true
661 return filepath.SkipDir
662 }
663 }
664 return nil
665 })
666 if err != nil {
667 ctx.Fatalf("Error finding Android build file: %v", err)
668 }
669
670 if found {
671 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700672 }
673 }
674
675 return ""
676}
677
678// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
679func splitArgs(args []string) (newArgs []string, dirs []string) {
680 specialArgs := map[string]bool{
681 "showcommands": true,
682 "snod": true,
683 "dist": true,
684 "checkbuild": true,
685 }
686
687 newArgs = []string{}
688 dirs = []string{}
689
690 for _, arg := range args {
691 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
692 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
693 newArgs = append(newArgs, arg)
694 continue
695 }
696
697 if _, ok := specialArgs[arg]; ok {
698 newArgs = append(newArgs, arg)
699 continue
700 }
701
702 dirs = append(dirs, arg)
703 }
704
705 return newArgs, dirs
706}
707
708// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
709// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
710// source root tree where the build action command was invoked. Each directory is validated if the
711// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700712func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700713 for _, dir := range dirs {
714 // The directory may have specified specific modules to build. ":" is the separator to separate
715 // the directory and the list of modules.
716 s := strings.Split(dir, ":")
717 l := len(s)
718 if l > 2 { // more than one ":" was specified.
719 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
720 }
721
722 dir = filepath.Join(relDir, s[0])
723 if _, err := os.Stat(dir); err != nil {
724 ctx.Fatalf("couldn't find directory %s", dir)
725 }
726
727 // Verify that if there are any targets specified after ":". Each target is separated by ",".
728 var newTargets []string
729 if l == 2 && s[1] != "" {
730 newTargets = strings.Split(s[1], ",")
731 if inList("", newTargets) {
732 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
733 }
734 }
735
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700736 // If there are specified targets to build in dir, an android build file must exist for the one
737 // shot build. For the non-targets case, find the appropriate build file and build all the
738 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700739 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700740 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700741 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
742 }
743 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700744 buildFile := findBuildFile(ctx, dir)
745 if buildFile == "" {
746 ctx.Fatalf("Build file not found for %s directory", dir)
747 }
748 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700749 }
750
Patrice Arruda13848222019-04-22 17:12:02 -0700751 targets = append(targets, newTargets...)
752 }
753
Dan Willemsence41e942019-07-29 23:39:30 -0700754 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700755}
756
Dan Willemsen9b587492017-07-10 22:13:00 -0700757func (c *configImpl) parseArgs(ctx Context, args []string) {
758 for i := 0; i < len(args); i++ {
759 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100760 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700761 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200762 } else if arg == "--empty-ninja-file" {
763 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100764 } else if arg == "--skip-ninja" {
765 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700766 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700767 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
768 // but it does run a Kati ninja file if the .kati_enabled marker file was created
769 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000770 c.skipConfig = true
771 c.skipKati = true
772 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100773 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000774 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100775 } else if arg == "--soong-only" {
776 c.skipKati = true
777 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200778 } else if arg == "--config-only" {
779 c.skipKati = true
780 c.skipKatiNinja = true
781 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700782 } else if arg == "--skip-config" {
783 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700784 } else if arg == "--skip-soong-tests" {
785 c.skipSoongTests = true
MarkDacekd0e7cd32022-12-02 22:22:40 +0000786 } else if arg == "--skip-metrics-upload" {
787 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500788 } else if arg == "--mk-metrics" {
789 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000790 } else if arg == "--multitree-build" {
791 c.multitreeBuild = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400792 } else if arg == "--bazel-mode" {
793 c.bazelProdMode = true
794 } else if arg == "--bazel-mode-dev" {
795 c.bazelDevMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000796 } else if arg == "--bazel-mode-staging" {
797 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000798 } else if arg == "--search-api-dir" {
799 c.searchApiDir = true
MarkDacekb96561e2022-12-02 04:34:43 +0000800 } else if strings.HasPrefix(arg, "--build-command=") {
801 buildCmd := strings.TrimPrefix(arg, "--build-command=")
802 // remove quotations
803 buildCmd = strings.TrimPrefix(buildCmd, "\"")
804 buildCmd = strings.TrimSuffix(buildCmd, "\"")
805 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000806 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
807 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
MarkDacek6614d9c2022-12-07 21:57:38 +0000808 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
809 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
810 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
811 if err == nil {
812 c.buildStartedTime = val
813 } else {
814 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
815 }
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700816 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700817 parseArgNum := func(def int) int {
818 if len(arg) > 2 {
819 p, err := strconv.ParseUint(arg[2:], 10, 31)
820 if err != nil {
821 ctx.Fatalf("Failed to parse %q: %v", arg, err)
822 }
823 return int(p)
824 } else if i+1 < len(args) {
825 p, err := strconv.ParseUint(args[i+1], 10, 31)
826 if err == nil {
827 i++
828 return int(p)
829 }
830 }
831 return def
832 }
833
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700834 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700835 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700836 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700837 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700838 } else {
839 ctx.Fatalln("Unknown option:", arg)
840 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700841 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700842 if k == "OUT_DIR" {
843 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
844 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700845 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700846 } else if arg == "dist" {
847 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200848 } else if arg == "json-module-graph" {
849 c.jsonModuleGraph = true
850 } else if arg == "bp2build" {
851 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000852 } else if arg == "api_bp2build" {
853 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200854 } else if arg == "queryview" {
855 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200856 } else if arg == "soong_docs" {
857 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700858 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700859 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800860 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700861 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700862 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700863 }
864 }
Chris Parsonsb6e96902022-10-31 20:08:45 -0400865 if (!c.bazelProdMode) && (!c.bazelDevMode) && (!c.bazelStagingMode) {
866 c.bazelProdMode = defaultBazelProdMode(c)
867 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700868}
869
Dan Willemsened869522018-01-08 14:58:46 -0800870func (c *configImpl) configureLocale(ctx Context) {
871 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
872 output, err := cmd.Output()
873
874 var locales []string
875 if err == nil {
876 locales = strings.Split(string(output), "\n")
877 } else {
878 // If we're unable to list the locales, let's assume en_US.UTF-8
879 locales = []string{"en_US.UTF-8"}
880 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
881 }
882
883 // gettext uses LANGUAGE, which is passed directly through
884
885 // For LANG and LC_*, only preserve the evaluated version of
886 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800887 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800888 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800889 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800890 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800891 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800892 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800893 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800894 }
895
896 c.environ.UnsetWithPrefix("LC_")
897
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800898 if userLang != "" {
899 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800900 }
901
902 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
903 // for others)
904 if inList("C.UTF-8", locales) {
905 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500906 } else if inList("C.utf8", locales) {
907 // These normalize to the same thing
908 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800909 } else if inList("en_US.UTF-8", locales) {
910 c.environ.Set("LANG", "en_US.UTF-8")
911 } else if inList("en_US.utf8", locales) {
912 // These normalize to the same thing
913 c.environ.Set("LANG", "en_US.UTF-8")
914 } else {
915 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
916 }
917}
918
Dan Willemsen1e704462016-08-21 15:17:17 -0700919func (c *configImpl) Environment() *Environment {
920 return c.environ
921}
922
923func (c *configImpl) Arguments() []string {
924 return c.arguments
925}
926
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200927func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200928 if len(c.Arguments()) > 0 {
929 // Explicit targets requested that are not special targets like b2pbuild
930 // or the JSON module graph
931 return true
932 }
933
Spandan Das5af0bd32022-09-28 20:43:08 +0000934 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200935 // Command line was empty, the default Ninja target is built
936 return true
937 }
938
Liz Kammer88677422021-12-15 15:03:19 -0500939 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
940 if c.Dist() && !c.Bp2Build() {
941 return true
942 }
943
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200944 // build.ninja doesn't need to be generated
945 return false
946}
947
Dan Willemsen1e704462016-08-21 15:17:17 -0700948func (c *configImpl) OutDir() string {
949 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700950 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700951 }
952 return "out"
953}
954
Dan Willemsen8a073a82017-02-04 17:30:44 -0800955func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400956 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000957}
958
959func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700960 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800961}
962
Dan Willemsen1e704462016-08-21 15:17:17 -0700963func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000964 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700965 return c.arguments
966 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700967 return c.ninjaArgs
968}
969
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500970func (c *configImpl) BazelOutDir() string {
971 return filepath.Join(c.OutDir(), "bazel")
972}
973
Liz Kammer2af5ea82022-11-11 14:21:03 -0500974func (c *configImpl) bazelOutputBase() string {
975 return filepath.Join(c.BazelOutDir(), "output")
976}
977
Dan Willemsen1e704462016-08-21 15:17:17 -0700978func (c *configImpl) SoongOutDir() string {
979 return filepath.Join(c.OutDir(), "soong")
980}
981
Spandan Das394aa322022-11-03 17:02:10 +0000982func (c *configImpl) ApiSurfacesOutDir() string {
983 return filepath.Join(c.OutDir(), "api_surfaces")
984}
985
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200986func (c *configImpl) PrebuiltOS() string {
987 switch runtime.GOOS {
988 case "linux":
989 return "linux-x86"
990 case "darwin":
991 return "darwin-x86"
992 default:
993 panic("Unknown GOOS")
994 }
995}
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100996
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200997func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -0700998 if c.SkipKatiNinja() {
999 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1000 } else {
1001 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1002 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001003}
1004
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001005func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001006 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001007}
1008
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001009func (c *configImpl) UsedEnvFile(tag string) string {
1010 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1011}
1012
Lukacs T. Berkic541cd22022-10-26 07:26:50 +00001013func (c *configImpl) Bp2BuildFilesMarkerFile() string {
1014 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
1015}
1016
1017func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001018 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +02001019}
1020
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001021func (c *configImpl) SoongDocsHtml() string {
1022 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1023}
1024
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001025func (c *configImpl) QueryviewMarkerFile() string {
1026 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1027}
1028
Spandan Das5af0bd32022-09-28 20:43:08 +00001029func (c *configImpl) ApiBp2buildMarkerFile() string {
1030 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
1031}
1032
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001033func (c *configImpl) ModuleGraphFile() string {
1034 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1035}
1036
kgui67007242022-01-25 13:50:25 +08001037func (c *configImpl) ModuleActionsFile() string {
1038 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1039}
1040
Jeff Gastonefc1b412017-03-29 17:29:06 -07001041func (c *configImpl) TempDir() string {
1042 return shared.TempDirForOutDir(c.SoongOutDir())
1043}
1044
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001045func (c *configImpl) FileListDir() string {
1046 return filepath.Join(c.OutDir(), ".module_paths")
1047}
1048
Dan Willemsen1e704462016-08-21 15:17:17 -07001049func (c *configImpl) KatiSuffix() string {
1050 if c.katiSuffix != "" {
1051 return c.katiSuffix
1052 }
1053 panic("SetKatiSuffix has not been called")
1054}
1055
Colin Cross37193492017-11-16 17:55:00 -08001056// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1057// user is interested in additional checks at the expense of build time.
1058func (c *configImpl) Checkbuild() bool {
1059 return c.checkbuild
1060}
1061
Dan Willemsen8a073a82017-02-04 17:30:44 -08001062func (c *configImpl) Dist() bool {
1063 return c.dist
1064}
1065
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001066func (c *configImpl) JsonModuleGraph() bool {
1067 return c.jsonModuleGraph
1068}
1069
1070func (c *configImpl) Bp2Build() bool {
1071 return c.bp2build
1072}
1073
Spandan Das5af0bd32022-09-28 20:43:08 +00001074func (c *configImpl) ApiBp2build() bool {
1075 return c.apiBp2build
1076}
1077
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001078func (c *configImpl) Queryview() bool {
1079 return c.queryview
1080}
1081
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001082func (c *configImpl) SoongDocs() bool {
1083 return c.soongDocs
1084}
1085
Dan Willemsen1e704462016-08-21 15:17:17 -07001086func (c *configImpl) IsVerbose() bool {
1087 return c.verbose
1088}
1089
LaMont Jones52a72432023-03-09 18:19:35 +00001090func (c *configImpl) MultitreeBuild() bool {
1091 return c.multitreeBuild
1092}
1093
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001094func (c *configImpl) SkipKati() bool {
1095 return c.skipKati
1096}
1097
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001098func (c *configImpl) SkipKatiNinja() bool {
1099 return c.skipKatiNinja
1100}
1101
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001102func (c *configImpl) SkipSoong() bool {
1103 return c.skipSoong
1104}
1105
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001106func (c *configImpl) SkipNinja() bool {
1107 return c.skipNinja
1108}
1109
Anton Hansson5a7861a2021-06-04 10:09:01 +01001110func (c *configImpl) SetSkipNinja(v bool) {
1111 c.skipNinja = v
1112}
1113
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001114func (c *configImpl) SkipConfig() bool {
1115 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001116}
1117
Dan Willemsen1e704462016-08-21 15:17:17 -07001118func (c *configImpl) TargetProduct() string {
1119 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1120 return v
1121 }
1122 panic("TARGET_PRODUCT is not defined")
1123}
1124
Dan Willemsen02781d52017-05-12 19:28:13 -07001125func (c *configImpl) TargetDevice() string {
1126 return c.targetDevice
1127}
1128
1129func (c *configImpl) SetTargetDevice(device string) {
1130 c.targetDevice = device
1131}
1132
1133func (c *configImpl) TargetBuildVariant() string {
1134 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1135 return v
1136 }
1137 panic("TARGET_BUILD_VARIANT is not defined")
1138}
1139
Dan Willemsen1e704462016-08-21 15:17:17 -07001140func (c *configImpl) KatiArgs() []string {
1141 return c.katiArgs
1142}
1143
1144func (c *configImpl) Parallel() int {
1145 return c.parallel
1146}
1147
Spandan Dasc5763832022-11-08 18:42:16 +00001148func (c *configImpl) GetIncludeTags() []string {
1149 return c.includeTags
1150}
1151
1152func (c *configImpl) SetIncludeTags(i []string) {
1153 c.includeTags = i
1154}
1155
MarkDacek6614d9c2022-12-07 21:57:38 +00001156func (c *configImpl) GetLogsPrefix() string {
1157 return c.logsPrefix
1158}
1159
1160func (c *configImpl) SetLogsPrefix(prefix string) {
1161 c.logsPrefix = prefix
1162}
1163
Colin Cross8b8bec32019-11-15 13:18:43 -08001164func (c *configImpl) HighmemParallel() int {
1165 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1166 return i
1167 }
1168
1169 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1170 parallel := c.Parallel()
1171 if c.UseRemoteBuild() {
1172 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1173 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1174 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1175 // Return 1/16th of the size of the local pool, rounding up.
1176 return (parallel + 15) / 16
1177 } else if c.totalRAM == 0 {
1178 // Couldn't detect the total RAM, don't restrict highmem processes.
1179 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001180 } else if c.totalRAM <= 16*1024*1024*1024 {
1181 // Less than 16GB of ram, restrict to 1 highmem processes
1182 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001183 } else if c.totalRAM <= 32*1024*1024*1024 {
1184 // Less than 32GB of ram, restrict to 2 highmem processes
1185 return 2
1186 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1187 // If less than 8GB total RAM per process, reduce the number of highmem processes
1188 return p
1189 }
1190 // No restriction on highmem processes
1191 return parallel
1192}
1193
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001194func (c *configImpl) TotalRAM() uint64 {
1195 return c.totalRAM
1196}
1197
Kousik Kumarec478642020-09-21 13:39:24 -04001198// ForceUseGoma determines whether we should override Goma deprecation
1199// and use Goma for the current build or not.
1200func (c *configImpl) ForceUseGoma() bool {
1201 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1202 v = strings.TrimSpace(v)
1203 if v != "" && v != "false" {
1204 return true
1205 }
1206 }
1207 return false
1208}
1209
Dan Willemsen1e704462016-08-21 15:17:17 -07001210func (c *configImpl) UseGoma() bool {
1211 if v, ok := c.environ.Get("USE_GOMA"); ok {
1212 v = strings.TrimSpace(v)
1213 if v != "" && v != "false" {
1214 return true
1215 }
1216 }
1217 return false
1218}
1219
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001220func (c *configImpl) StartGoma() bool {
1221 if !c.UseGoma() {
1222 return false
1223 }
1224
1225 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1226 v = strings.TrimSpace(v)
1227 if v != "" && v != "false" {
1228 return false
1229 }
1230 }
1231 return true
1232}
1233
Ramy Medhatbbf25672019-07-17 12:30:04 +00001234func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001235 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001236 v = strings.TrimSpace(v)
1237 if v != "" && v != "false" {
1238 return true
1239 }
1240 }
1241 return false
1242}
1243
Chris Parsonsef615e52022-08-18 22:04:11 -04001244func (c *configImpl) BazelBuildEnabled() bool {
MarkDacekb78465d2022-10-18 20:10:16 +00001245 return c.bazelProdMode || c.bazelDevMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001246}
1247
Ramy Medhatbbf25672019-07-17 12:30:04 +00001248func (c *configImpl) StartRBE() bool {
1249 if !c.UseRBE() {
1250 return false
1251 }
1252
1253 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1254 v = strings.TrimSpace(v)
1255 if v != "" && v != "false" {
1256 return false
1257 }
1258 }
1259 return true
1260}
1261
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001262func (c *configImpl) rbeProxyLogsDir() string {
1263 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001264 if v, ok := c.environ.Get(f); ok {
1265 return v
1266 }
1267 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001268 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1269 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001270}
1271
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001272func (c *configImpl) shouldCleanupRBELogsDir() bool {
1273 // Perform a log directory cleanup only when the log directory
1274 // is auto created by the build rather than user-specified.
1275 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1276 if _, ok := c.environ.Get(f); ok {
1277 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001278 }
1279 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001280 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001281}
1282
1283func (c *configImpl) rbeExecRoot() string {
1284 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1285 if v, ok := c.environ.Get(f); ok {
1286 return v
1287 }
1288 }
1289 wd, err := os.Getwd()
1290 if err != nil {
1291 return ""
1292 }
1293 return wd
1294}
1295
1296func (c *configImpl) rbeDir() string {
1297 if v, ok := c.environ.Get("RBE_DIR"); ok {
1298 return v
1299 }
1300 return "prebuilts/remoteexecution-client/live/"
1301}
1302
1303func (c *configImpl) rbeReproxy() string {
1304 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1305 if v, ok := c.environ.Get(f); ok {
1306 return v
1307 }
1308 }
1309 return filepath.Join(c.rbeDir(), "reproxy")
1310}
1311
1312func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001313 credFlags := []string{
1314 "use_application_default_credentials",
1315 "use_gce_credentials",
1316 "credential_file",
1317 "use_google_prod_creds",
1318 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001319 for _, cf := range credFlags {
1320 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1321 if v, ok := c.environ.Get(f); ok {
1322 v = strings.TrimSpace(v)
1323 if v != "" && v != "false" && v != "0" {
1324 return "RBE_" + cf, v
1325 }
1326 }
1327 }
1328 }
1329 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001330}
1331
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001332func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1333 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1334 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1335
1336 name := filepath.Join(dir, base)
1337 if len(name) < maxNameLen {
1338 return name, nil
1339 }
1340
1341 name = filepath.Join("/tmp", base)
1342 if len(name) < maxNameLen {
1343 return name, nil
1344 }
1345
1346 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1347}
1348
Kousik Kumar7bc78192022-04-27 14:52:56 -04001349// IsGooglerEnvironment returns true if the current build is running
1350// on a Google developer machine and false otherwise.
1351func (c *configImpl) IsGooglerEnvironment() bool {
1352 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1353 if v, ok := c.environ.Get(cf); ok {
1354 return v == "googler"
1355 }
1356 return false
1357}
1358
1359// GoogleProdCredsExist determine whether credentials exist on the
1360// Googler machine to use remote execution.
1361func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001362 if googleProdCredsExistCache {
1363 return googleProdCredsExistCache
1364 }
Kousik Kumar7bc78192022-04-27 14:52:56 -04001365 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1366 return false
1367 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001368 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001369 return true
1370}
1371
1372// UseRemoteBuild indicates whether to use a remote build acceleration system
1373// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001374func (c *configImpl) UseRemoteBuild() bool {
1375 return c.UseGoma() || c.UseRBE()
1376}
1377
Kousik Kumar7bc78192022-04-27 14:52:56 -04001378// StubbyExists checks whether the stubby binary exists on the machine running
1379// the build.
1380func (c *configImpl) StubbyExists() bool {
1381 if _, err := exec.LookPath("stubby"); err != nil {
1382 return false
1383 }
1384 return true
1385}
1386
Dan Willemsen1e704462016-08-21 15:17:17 -07001387// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001388// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001389// still limited by Parallel()
1390func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001391 if !c.UseRemoteBuild() {
1392 return 0
1393 }
1394 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1395 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001396 }
1397 return 500
1398}
1399
1400func (c *configImpl) SetKatiArgs(args []string) {
1401 c.katiArgs = args
1402}
1403
1404func (c *configImpl) SetNinjaArgs(args []string) {
1405 c.ninjaArgs = args
1406}
1407
1408func (c *configImpl) SetKatiSuffix(suffix string) {
1409 c.katiSuffix = suffix
1410}
1411
Dan Willemsene0879fc2017-08-04 15:06:27 -07001412func (c *configImpl) LastKatiSuffixFile() string {
1413 return filepath.Join(c.OutDir(), "last_kati_suffix")
1414}
1415
1416func (c *configImpl) HasKatiSuffix() bool {
1417 return c.katiSuffix != ""
1418}
1419
Dan Willemsen1e704462016-08-21 15:17:17 -07001420func (c *configImpl) KatiEnvFile() string {
1421 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1422}
1423
Dan Willemsen29971232018-09-26 14:58:30 -07001424func (c *configImpl) KatiBuildNinjaFile() string {
1425 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001426}
1427
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001428func (c *configImpl) KatiPackageNinjaFile() string {
1429 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1430}
1431
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001432func (c *configImpl) SoongVarsFile() string {
1433 return filepath.Join(c.SoongOutDir(), "soong.variables")
1434}
1435
Dan Willemsen1e704462016-08-21 15:17:17 -07001436func (c *configImpl) SoongNinjaFile() string {
1437 return filepath.Join(c.SoongOutDir(), "build.ninja")
1438}
1439
1440func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001441 if c.katiSuffix == "" {
1442 return filepath.Join(c.OutDir(), "combined.ninja")
1443 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001444 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1445}
1446
1447func (c *configImpl) SoongAndroidMk() string {
1448 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1449}
1450
1451func (c *configImpl) SoongMakeVarsMk() string {
1452 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1453}
1454
Dan Willemsenf052f782017-05-18 15:29:04 -07001455func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001456 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001457}
1458
Dan Willemsen02781d52017-05-12 19:28:13 -07001459func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001460 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1461}
1462
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001463func (c *configImpl) KatiPackageMkDir() string {
1464 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1465}
1466
Dan Willemsenf052f782017-05-18 15:29:04 -07001467func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001468 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001469}
1470
1471func (c *configImpl) HostOut() string {
1472 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1473}
1474
1475// This probably needs to be multi-valued, so not exporting it for now
1476func (c *configImpl) hostCrossOut() string {
1477 if runtime.GOOS == "linux" {
1478 return filepath.Join(c.hostOutRoot(), "windows-x86")
1479 } else {
1480 return ""
1481 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001482}
1483
Dan Willemsen1e704462016-08-21 15:17:17 -07001484func (c *configImpl) HostPrebuiltTag() string {
1485 if runtime.GOOS == "linux" {
1486 return "linux-x86"
1487 } else if runtime.GOOS == "darwin" {
1488 return "darwin-x86"
1489 } else {
1490 panic("Unsupported OS")
1491 }
1492}
Dan Willemsenf173d592017-04-27 14:28:00 -07001493
Dan Willemsen8122bd52017-10-12 20:20:41 -07001494func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001495 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1496 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001497 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1498 if _, err := os.Stat(asan); err == nil {
1499 return asan
1500 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001501 }
1502 }
1503 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1504}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001505
1506func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1507 c.brokenDupRules = val
1508}
1509
1510func (c *configImpl) BuildBrokenDupRules() bool {
1511 return c.brokenDupRules
1512}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001513
Dan Willemsen25e6f092019-04-09 10:22:43 -07001514func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1515 c.brokenUsesNetwork = val
1516}
1517
1518func (c *configImpl) BuildBrokenUsesNetwork() bool {
1519 return c.brokenUsesNetwork
1520}
1521
Dan Willemsene3336352020-01-02 19:10:38 -08001522func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1523 c.brokenNinjaEnvVars = val
1524}
1525
1526func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1527 return c.brokenNinjaEnvVars
1528}
1529
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001530func (c *configImpl) SetTargetDeviceDir(dir string) {
1531 c.targetDeviceDir = dir
1532}
1533
1534func (c *configImpl) TargetDeviceDir() string {
1535 return c.targetDeviceDir
1536}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001537
Patrice Arruda219eef32020-06-01 17:29:30 +00001538func (c *configImpl) BuildDateTime() string {
1539 return c.buildDateTime
1540}
1541
1542func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001543 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001544}
Patrice Arruda83842d72020-12-08 19:42:08 +00001545
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001546// LogsDir returns the absolute path to the logs directory where build log and
1547// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001548// directory. If the argument dist is specified, the logs directory
1549// is <dist_dir>/logs.
1550func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001551 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001552 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001553 // 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 -05001554 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001555 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001556 absDir, err := filepath.Abs(dir)
1557 if err != nil {
1558 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1559 os.Exit(1)
1560 }
1561 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001562}
1563
1564// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1565// where the bazel profiles are located.
1566func (c *configImpl) BazelMetricsDir() string {
1567 return filepath.Join(c.LogsDir(), "bazel_metrics")
1568}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001569
Chris Parsons53f68ae2022-03-03 12:01:40 -05001570// MkFileMetrics returns the file path for make-related metrics.
1571func (c *configImpl) MkMetrics() string {
1572 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1573}
1574
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001575func (c *configImpl) SetEmptyNinjaFile(v bool) {
1576 c.emptyNinjaFile = v
1577}
1578
1579func (c *configImpl) EmptyNinjaFile() bool {
1580 return c.emptyNinjaFile
1581}
Yu Liu6e13b402021-07-27 14:29:06 -07001582
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001583func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1584 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1585}
1586
Chris Parsons9402ca82023-02-23 17:28:06 -05001587func (c *configImpl) IsPersistentBazelEnabled() bool {
1588 return c.Environment().IsEnvTrue("USE_PERSISTENT_BAZEL")
1589}
1590
MarkDacekd06db5d2022-11-29 00:47:59 +00001591func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1592 return c.bazelForceEnabledModules
1593}
1594
MarkDacekd0e7cd32022-12-02 22:22:40 +00001595func (c *configImpl) SkipMetricsUpload() bool {
1596 return c.skipMetricsUpload
1597}
1598
MarkDacek6614d9c2022-12-07 21:57:38 +00001599// Returns a Time object if one was passed via a command-line flag.
1600// Otherwise returns the passed default.
1601func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1602 if c.buildStartedTime == 0 {
1603 return defaultTime
1604 }
1605 return time.UnixMilli(c.buildStartedTime)
1606}
1607
Yu Liu6e13b402021-07-27 14:29:06 -07001608func GetMetricsUploader(topDir string, env *Environment) string {
1609 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1610 metricsUploader := filepath.Join(topDir, p)
1611 if _, err := os.Stat(metricsUploader); err == nil {
1612 return metricsUploader
1613 }
1614 }
1615
1616 return ""
1617}