blob: 5925b283c954fe7e84396d406efe9f3c92364dfa [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 Kumar3ff037e2022-01-25 22:11:01 -050018 "encoding/json"
Jeongik Chaa87506f2023-06-01 23:16:41 +090019 "errors"
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"
Cole Faust583dfb42023-09-28 13:56:30 -070025 "os/user"
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 Kumar3ff037e2022-01-25 22:11:01 -050043)
44
Kousik Kumar4c180ad2022-05-27 07:48:37 -040045var (
Kevin Dagostino096ab2f2023-03-03 19:47:17 +000046 rbeRandPrefix int
47 googleProdCredsExistCache bool
Kousik Kumar4c180ad2022-05-27 07:48:37 -040048)
49
50func init() {
51 rand.Seed(time.Now().UnixNano())
52 rbeRandPrefix = rand.Intn(1000)
53}
54
Dan Willemsen1e704462016-08-21 15:17:17 -070055type Config struct{ *configImpl }
56
57type configImpl struct {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020058 // Some targets that are implemented in soong_build
59 // (bp2build, json-module-graph) are not here and have their own bits below.
Colin Cross28f527c2019-11-26 16:19:04 -080060 arguments []string
61 goma bool
62 environ *Environment
63 distDir string
64 buildDateTime string
MarkDacek6614d9c2022-12-07 21:57:38 +000065 logsPrefix string
Dan Willemsen1e704462016-08-21 15:17:17 -070066
67 // From the arguments
MarkDacekf47e1422023-04-19 16:47:36 +000068 parallel int
69 keepGoing int
70 verbose bool
71 checkbuild bool
72 dist bool
73 jsonModuleGraph bool
MarkDacekf47e1422023-04-19 16:47:36 +000074 bp2build bool
75 queryview bool
76 reportMkMetrics bool // Collect and report mk2bp migration progress metrics.
77 soongDocs bool
78 multitreeBuild bool // This is a multitree build.
79 skipConfig bool
80 skipKati bool
81 skipKatiNinja bool
82 skipSoong bool
83 skipNinja bool
84 skipSoongTests bool
85 searchApiDir bool // Scan the Android.bp files generated in out/api_surfaces
86 skipMetricsUpload bool
87 buildStartedTime int64 // For metrics-upload-only - manually specify a build-started time
Sebastian Pickl1c4188c2023-10-24 11:18:34 +000088 buildFromTextStub bool
MarkDacek396491e2023-06-14 19:41:18 +000089 ensureAllowlistIntegrity bool // For CI builds - make sure modules are mixed-built
90 bazelExitCode int32 // For b runs - necessary for updating NonZeroExit
91 besId string // For b runs, to identify the BuildEventService logs
Dan Willemsen1e704462016-08-21 15:17:17 -070092
93 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070094 katiArgs []string
95 ninjaArgs []string
96 katiSuffix string
97 targetDevice string
98 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +000099 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -0700100
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800101 // Autodetected
102 totalRAM uint64
103
Dan Willemsene3336352020-01-02 19:10:38 -0800104 brokenDupRules bool
105 brokenUsesNetwork bool
106 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -0700107
108 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000109
MarkDacekb78465d2022-10-18 20:10:16 +0000110 bazelProdMode bool
MarkDacekb78465d2022-10-18 20:10:16 +0000111 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
Sam Delmerico98a73292023-02-21 11:50:29 -0500120 includeTags []string
121 sourceRootDirs []string
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900122
123 // Data source to write ninja weight list
124 ninjaWeightListSource NinjaWeightListSource
Dan Willemsen1e704462016-08-21 15:17:17 -0700125}
126
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900127type NinjaWeightListSource uint
128
129const (
130 // ninja doesn't use weight list.
131 NOT_USED NinjaWeightListSource = iota
132 // ninja uses weight list based on previous builds by ninja log
133 NINJA_LOG
134 // ninja thinks every task has the same weight.
135 EVENLY_DISTRIBUTED
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900136 // ninja uses an external custom weight list
137 EXTERNAL_FILE
Jeongik Chae114e602023-03-19 00:12:39 +0900138 // ninja uses a prioritized module list from Soong
139 HINT_FROM_SOONG
Jeongik Chaa87506f2023-06-01 23:16:41 +0900140 // If ninja log exists, use NINJA_LOG, if not, use HINT_FROM_SOONG instead.
141 // We can assume it is an incremental build if ninja log exists.
142 DEFAULT
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900143)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800144const srcDirFileCheck = "build/soong/root.bp"
145
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700146var buildFiles = []string{"Android.mk", "Android.bp"}
147
Patrice Arruda13848222019-04-22 17:12:02 -0700148type BuildAction uint
149
150const (
151 // Builds all of the modules and their dependencies of a specified directory, relative to the root
152 // directory of the source tree.
153 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
154
155 // Builds all of the modules and their dependencies of a list of specified directories. All specified
156 // directories are relative to the root directory of the source tree.
157 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700158
159 // Build a list of specified modules. If none was specified, simply build the whole source tree.
160 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700161)
162
163// checkTopDir validates that the current directory is at the root directory of the source tree.
164func checkTopDir(ctx Context) {
165 if _, err := os.Stat(srcDirFileCheck); err != nil {
166 if os.IsNotExist(err) {
167 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
168 }
169 ctx.Fatalln("Error verifying tree state:", err)
170 }
171}
172
MarkDacek7901e582023-01-09 19:48:01 +0000173func loadEnvConfig(ctx Context, config *configImpl, bc string) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500174 if bc == "" {
175 return nil
176 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500177
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500178 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500179 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500180 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500181 envConfigDir,
182 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500183 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500184 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
185 envVarsJSON, err := ioutil.ReadFile(cfgFile)
186 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500187 continue
188 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500189 ctx.Verbosef("Loading config file %v\n", cfgFile)
190 var envVars map[string]map[string]string
191 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
192 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
193 continue
194 }
195 for k, v := range envVars["env"] {
196 if os.Getenv(k) != "" {
197 continue
198 }
199 config.environ.Set(k, v)
200 }
201 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
202 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500203 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500204
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500205 return nil
206}
207
Chris Parsonsb6e96902022-10-31 20:08:45 -0400208func defaultBazelProdMode(cfg *configImpl) bool {
MarkDacekd06db5d2022-11-29 00:47:59 +0000209 // Environment flag to disable Bazel for users which experience
Chris Parsonsb6e96902022-10-31 20:08:45 -0400210 // broken bazel-handled builds, or significant performance regressions.
211 if cfg.IsBazelMixedBuildForceDisabled() {
212 return false
213 }
214 // Darwin-host builds are currently untested with Bazel.
215 if runtime.GOOS == "darwin" {
216 return false
217 }
Chris Parsons035e03a2022-11-01 14:25:45 -0400218 return true
Chris Parsonsb6e96902022-10-31 20:08:45 -0400219}
220
MarkDacekd33c2fd2023-05-04 20:40:04 +0000221func UploadOnlyConfig(ctx Context, args ...string) Config {
MarkDacek6614d9c2022-12-07 21:57:38 +0000222 ret := &configImpl{
223 environ: OsEnvironment(),
224 sandboxConfig: &SandboxConfig{},
225 }
MarkDacekd33c2fd2023-05-04 20:40:04 +0000226 ret.parseArgs(ctx, args)
MarkDacek7901e582023-01-09 19:48:01 +0000227 srcDir := absPath(ctx, ".")
228 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
229 if err := loadEnvConfig(ctx, ret, bc); err != nil {
230 ctx.Fatalln("Failed to parse env config files: %v", err)
231 }
232 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
MarkDacek6614d9c2022-12-07 21:57:38 +0000233 return Config{ret}
234}
235
Dan Willemsen1e704462016-08-21 15:17:17 -0700236func NewConfig(ctx Context, args ...string) Config {
237 ret := &configImpl{
Jeongik Chaf2ecf762023-05-19 14:03:45 +0900238 environ: OsEnvironment(),
239 sandboxConfig: &SandboxConfig{},
Jeongik Chaa87506f2023-06-01 23:16:41 +0900240 ninjaWeightListSource: DEFAULT,
Dan Willemsen1e704462016-08-21 15:17:17 -0700241 }
242
Patrice Arruda90109172020-07-28 18:07:27 +0000243 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700244 ret.parallel = runtime.NumCPU() + 2
245 ret.keepGoing = 1
246
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800247 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700248 ret.parseArgs(ctx, args)
Jeongik Chae114e602023-03-19 00:12:39 +0900249
250 if ret.ninjaWeightListSource == HINT_FROM_SOONG {
Jeongik Chaa87506f2023-06-01 23:16:41 +0900251 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "always")
252 } else if ret.ninjaWeightListSource == DEFAULT {
253 defaultNinjaWeightListSource := NINJA_LOG
254 if _, err := os.Stat(filepath.Join(ret.OutDir(), ninjaLogFileName)); errors.Is(err, os.ErrNotExist) {
255 ctx.Verboseln("$OUT/.ninja_log doesn't exist, use HINT_FROM_SOONG instead")
256 defaultNinjaWeightListSource = HINT_FROM_SOONG
257 } else {
258 ctx.Verboseln("$OUT/.ninja_log exist, use NINJA_LOG")
259 }
260 ret.ninjaWeightListSource = defaultNinjaWeightListSource
261 // soong_build generates ninja hint depending on ninja log existence.
262 // Set it "depend" to avoid soong re-run due to env variable change.
263 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "depend")
Jeongik Chae114e602023-03-19 00:12:39 +0900264 }
Jeongik Chaa87506f2023-06-01 23:16:41 +0900265
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800266 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700267 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
268 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
269 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800270 outDir := "out"
271 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
272 if wd, err := os.Getwd(); err != nil {
273 ctx.Fatalln("Failed to get working directory:", err)
274 } else {
275 outDir = filepath.Join(baseDir, filepath.Base(wd))
276 }
277 }
278 ret.environ.Set("OUT_DIR", outDir)
279 }
280
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500281 // loadEnvConfig needs to know what the OUT_DIR is, so it should
282 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000283 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
284
285 if bc != "" {
Kousik Kumarc8818332023-01-16 16:33:05 +0000286 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000287 ctx.Fatalln("Failed to parse env config files: %v", err)
288 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +0000289 if !ret.canSupportRBE() {
290 // Explicitly set USE_RBE env variable to false when we cannot run
291 // an RBE build to avoid ninja local execution pool issues.
292 ret.environ.Set("USE_RBE", "false")
293 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500294 }
295
Dan Willemsen2d31a442018-10-20 21:33:41 -0700296 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
297 ret.distDir = filepath.Clean(distDir)
298 } else {
299 ret.distDir = filepath.Join(ret.OutDir(), "dist")
300 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700301
Spandan Das05063612021-06-25 01:39:04 +0000302 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
303 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
304 }
305
Dan Willemsen1e704462016-08-21 15:17:17 -0700306 ret.environ.Unset(
307 // We're already using it
308 "USE_SOONG_UI",
309
310 // We should never use GOROOT/GOPATH from the shell environment
311 "GOROOT",
312 "GOPATH",
313
314 // These should only come from Soong, not the environment.
315 "CLANG",
316 "CLANG_CXX",
317 "CCC_CC",
318 "CCC_CXX",
319
320 // Used by the goma compiler wrapper, but should only be set by
321 // gomacc
322 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800323
324 // We handle this above
325 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700326
Dan Willemsen2d31a442018-10-20 21:33:41 -0700327 // This is handled above too, and set for individual commands later
328 "DIST_DIR",
329
Dan Willemsen68a09852017-04-18 13:56:57 -0700330 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000331 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700332 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700333 "DISPLAY",
334 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000335 "JAVAC",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700336 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700337 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700338
339 // Drop make flags
340 "MAKEFLAGS",
341 "MAKELEVEL",
342 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700343
344 // Set in envsetup.sh, reset in makefiles
345 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700346
347 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
348 "ANDROID_BUILD_TOP",
349 "ANDROID_HOST_OUT",
350 "ANDROID_PRODUCT_OUT",
351 "ANDROID_HOST_OUT_TESTCASES",
352 "ANDROID_TARGET_OUT_TESTCASES",
353 "ANDROID_TOOLCHAIN",
354 "ANDROID_TOOLCHAIN_2ND_ARCH",
355 "ANDROID_DEV_SCRIPTS",
356 "ANDROID_EMULATOR_PREBUILTS",
357 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700358 )
359
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400360 if ret.UseGoma() || ret.ForceUseGoma() {
361 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
362 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400363 }
364
Dan Willemsen1e704462016-08-21 15:17:17 -0700365 // Tell python not to spam the source tree with .pyc files.
366 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
367
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400368 tmpDir := absPath(ctx, ret.TempDir())
369 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800370
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700371 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
372 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
373 "llvm-binutils-stable/llvm-symbolizer")
374 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
375
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800376 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700377 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800378
Yu Liu6e13b402021-07-27 14:29:06 -0700379 srcDir := absPath(ctx, ".")
380 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700381 ctx.Println("You are building in a directory whose absolute path contains a space character:")
382 ctx.Println()
383 ctx.Printf("%q\n", srcDir)
384 ctx.Println()
385 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700386 }
387
Yu Liu6e13b402021-07-27 14:29:06 -0700388 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
389
Dan Willemsendb8457c2017-05-12 16:38:17 -0700390 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700391 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
392 ctx.Println()
393 ctx.Printf("%q\n", outDir)
394 ctx.Println()
395 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700396 }
397
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000398 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700399 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
400 ctx.Println()
401 ctx.Printf("%q\n", distDir)
402 ctx.Println()
403 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700404 }
405
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700406 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000407 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
408 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100409 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800410 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700411 javaHome := func() string {
412 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
413 return override
414 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000415 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
416 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 +0100417 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000418 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
419 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
420 }
421 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700422 }()
423 absJavaHome := absPath(ctx, javaHome)
424
Dan Willemsened869522018-01-08 14:58:46 -0800425 ret.configureLocale(ctx)
426
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700427 newPath := []string{filepath.Join(absJavaHome, "bin")}
428 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
429 newPath = append(newPath, path)
430 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100431
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700432 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
433 ret.environ.Set("JAVA_HOME", absJavaHome)
434 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000435 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
436 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100437 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700438 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
439
Colin Crossfe5ed4d2023-07-28 09:27:23 -0700440 // b/286885495, https://bugzilla.redhat.com/show_bug.cgi?id=2227130: some versions of Fedora include patches
441 // to unzip to enable zipbomb detection that incorrectly handle zip64 and data descriptors and fail on large
442 // zip files produced by soong_zip. Disable zipbomb detection.
443 ret.environ.Set("UNZIP_DISABLE_ZIPBOMB_DETECTION", "TRUE")
444
LaMont Jones52a72432023-03-09 18:19:35 +0000445 if ret.MultitreeBuild() {
446 ret.environ.Set("MULTITREE_BUILD", "true")
447 }
448
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800449 outDir := ret.OutDir()
450 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800451 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800452 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800453 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800454 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800455 }
Colin Cross28f527c2019-11-26 16:19:04 -0800456
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800457 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
458
Cole Faust583dfb42023-09-28 13:56:30 -0700459 if _, ok := ret.environ.Get("BUILD_USERNAME"); !ok {
460 username := "unknown"
461 if u, err := user.Current(); err == nil {
462 username = u.Username
463 } else {
464 ctx.Println("Failed to get current user:", err)
465 }
466 ret.environ.Set("BUILD_USERNAME", username)
467 }
468
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400469 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400470 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400471 ret.environ.Set(k, v)
472 }
473 }
474
Patrice Arruda83842d72020-12-08 19:42:08 +0000475 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800476 if err := os.RemoveAll(bpd); err != nil {
477 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
478 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000479
Patrice Arruda96850362020-08-11 20:41:11 +0000480 c := Config{ret}
481 storeConfigMetrics(ctx, c)
482 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700483}
484
Patrice Arruda13848222019-04-22 17:12:02 -0700485// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
486// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700487func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
488 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700489}
490
Patrice Arruda96850362020-08-11 20:41:11 +0000491// storeConfigMetrics selects a set of configuration information and store in
492// the metrics system for further analysis.
493func storeConfigMetrics(ctx Context, config Config) {
494 if ctx.Metrics == nil {
495 return
496 }
497
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400498 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000499
500 s := &smpb.SystemResourceInfo{
501 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
502 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
503 }
504 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000505}
506
Jeongik Cha8d63d562023-03-17 03:52:13 +0900507func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900508 switch s {
509 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900510 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900511 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900512 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900513 case EXTERNAL_FILE:
514 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900515 case HINT_FROM_SOONG:
516 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900517 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900518 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900519 }
520}
521
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400522func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700523 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400524 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
525 UseGoma: proto.Bool(config.UseGoma()),
526 UseRbe: proto.Bool(config.UseRBE()),
527 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
528 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900529 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400530 }
Yu Liue737a992021-10-04 13:21:41 -0700531 c.Targets = append(c.Targets, config.arguments...)
532
533 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400534}
535
Patrice Arruda13848222019-04-22 17:12:02 -0700536// getConfigArgs processes the command arguments based on the build action and creates a set of new
537// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700538func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700539 // The next block of code verifies that the current directory is the root directory of the source
540 // tree. It then finds the relative path of dir based on the root directory of the source tree
541 // and verify that dir is inside of the source tree.
542 checkTopDir(ctx)
543 topDir, err := os.Getwd()
544 if err != nil {
545 ctx.Fatalf("Error retrieving top directory: %v", err)
546 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700547 dir, err = filepath.EvalSymlinks(dir)
548 if err != nil {
549 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
550 }
Patrice Arruda13848222019-04-22 17:12:02 -0700551 dir, err = filepath.Abs(dir)
552 if err != nil {
553 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
554 }
555 relDir, err := filepath.Rel(topDir, dir)
556 if err != nil {
557 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
558 }
559 // If there are ".." in the path, it's not in the source tree.
560 if strings.Contains(relDir, "..") {
561 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
562 }
563
564 configArgs := args[:]
565
566 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
567 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
568 targetNamePrefix := "MODULES-IN-"
569 if inList("GET-INSTALL-PATH", configArgs) {
570 targetNamePrefix = "GET-INSTALL-PATH-IN-"
571 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
572 }
573
Patrice Arruda13848222019-04-22 17:12:02 -0700574 var targets []string
575
576 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700577 case BUILD_MODULES:
578 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700579 case BUILD_MODULES_IN_A_DIRECTORY:
580 // If dir is the root source tree, all the modules are built of the source tree are built so
581 // no need to find the build file.
582 if topDir == dir {
583 break
584 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700585
Patrice Arruda13848222019-04-22 17:12:02 -0700586 buildFile := findBuildFile(ctx, relDir)
587 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700588 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700589 }
Patrice Arruda13848222019-04-22 17:12:02 -0700590 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
591 case BUILD_MODULES_IN_DIRECTORIES:
592 newConfigArgs, dirs := splitArgs(configArgs)
593 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700594 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700595 }
596
597 // Tidy only override all other specified targets.
598 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
599 if tidyOnly == "true" || tidyOnly == "1" {
600 configArgs = append(configArgs, "tidy_only")
601 } else {
602 configArgs = append(configArgs, targets...)
603 }
604
605 return configArgs
606}
607
608// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
609func convertToTarget(dir string, targetNamePrefix string) string {
610 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
611}
612
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700613// hasBuildFile returns true if dir contains an Android build file.
614func hasBuildFile(ctx Context, dir string) bool {
615 for _, buildFile := range buildFiles {
616 _, err := os.Stat(filepath.Join(dir, buildFile))
617 if err == nil {
618 return true
619 }
620 if !os.IsNotExist(err) {
621 ctx.Fatalf("Error retrieving the build file stats: %v", err)
622 }
623 }
624 return false
625}
626
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700627// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
628// in the current and any sub directory of dir. If a build file is not found, traverse the path
629// up by one directory and repeat again until either a build file is found or reached to the root
630// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
631// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700632func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700633 // If the string is empty or ".", assume it is top directory of the source tree.
634 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700635 return ""
636 }
637
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700638 found := false
639 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
640 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
641 if err != nil {
642 return err
643 }
644 if found {
645 return filepath.SkipDir
646 }
647 if info.IsDir() {
648 return nil
649 }
650 for _, buildFile := range buildFiles {
651 if info.Name() == buildFile {
652 found = true
653 return filepath.SkipDir
654 }
655 }
656 return nil
657 })
658 if err != nil {
659 ctx.Fatalf("Error finding Android build file: %v", err)
660 }
661
662 if found {
663 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700664 }
665 }
666
667 return ""
668}
669
670// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
671func splitArgs(args []string) (newArgs []string, dirs []string) {
672 specialArgs := map[string]bool{
673 "showcommands": true,
674 "snod": true,
675 "dist": true,
676 "checkbuild": true,
677 }
678
679 newArgs = []string{}
680 dirs = []string{}
681
682 for _, arg := range args {
683 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
684 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
685 newArgs = append(newArgs, arg)
686 continue
687 }
688
689 if _, ok := specialArgs[arg]; ok {
690 newArgs = append(newArgs, arg)
691 continue
692 }
693
694 dirs = append(dirs, arg)
695 }
696
697 return newArgs, dirs
698}
699
700// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
701// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
702// source root tree where the build action command was invoked. Each directory is validated if the
703// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700704func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700705 for _, dir := range dirs {
706 // The directory may have specified specific modules to build. ":" is the separator to separate
707 // the directory and the list of modules.
708 s := strings.Split(dir, ":")
709 l := len(s)
710 if l > 2 { // more than one ":" was specified.
711 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
712 }
713
714 dir = filepath.Join(relDir, s[0])
715 if _, err := os.Stat(dir); err != nil {
716 ctx.Fatalf("couldn't find directory %s", dir)
717 }
718
719 // Verify that if there are any targets specified after ":". Each target is separated by ",".
720 var newTargets []string
721 if l == 2 && s[1] != "" {
722 newTargets = strings.Split(s[1], ",")
723 if inList("", newTargets) {
724 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
725 }
726 }
727
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700728 // If there are specified targets to build in dir, an android build file must exist for the one
729 // shot build. For the non-targets case, find the appropriate build file and build all the
730 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700731 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700732 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700733 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
734 }
735 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700736 buildFile := findBuildFile(ctx, dir)
737 if buildFile == "" {
738 ctx.Fatalf("Build file not found for %s directory", dir)
739 }
740 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700741 }
742
Patrice Arruda13848222019-04-22 17:12:02 -0700743 targets = append(targets, newTargets...)
744 }
745
Dan Willemsence41e942019-07-29 23:39:30 -0700746 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700747}
748
Dan Willemsen9b587492017-07-10 22:13:00 -0700749func (c *configImpl) parseArgs(ctx Context, args []string) {
750 for i := 0; i < len(args); i++ {
751 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100752 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700753 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200754 } else if arg == "--empty-ninja-file" {
755 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100756 } else if arg == "--skip-ninja" {
757 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700758 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700759 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
760 // but it does run a Kati ninja file if the .kati_enabled marker file was created
761 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000762 c.skipConfig = true
763 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100764 } else if arg == "--soong-only" {
765 c.skipKati = true
766 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200767 } else if arg == "--config-only" {
768 c.skipKati = true
769 c.skipKatiNinja = true
770 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700771 } else if arg == "--skip-config" {
772 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700773 } else if arg == "--skip-soong-tests" {
774 c.skipSoongTests = true
MarkDacekd0e7cd32022-12-02 22:22:40 +0000775 } else if arg == "--skip-metrics-upload" {
776 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500777 } else if arg == "--mk-metrics" {
778 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000779 } else if arg == "--multitree-build" {
780 c.multitreeBuild = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400781 } else if arg == "--bazel-mode" {
782 c.bazelProdMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000783 } else if arg == "--bazel-mode-staging" {
784 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000785 } else if arg == "--search-api-dir" {
786 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900787 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
788 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
789 if source == "ninja_log" {
790 c.ninjaWeightListSource = NINJA_LOG
791 } else if source == "evenly_distributed" {
792 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
793 } else if source == "not_used" {
794 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900795 } else if source == "soong" {
796 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900797 } else if strings.HasPrefix(source, "file,") {
798 c.ninjaWeightListSource = EXTERNAL_FILE
799 filePath := strings.TrimPrefix(source, "file,")
800 err := validateNinjaWeightList(filePath)
801 if err != nil {
802 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
803 }
804 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
805 if err != nil {
806 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
807 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900808 } else {
809 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
810 }
Sebastian Pickl1c4188c2023-10-24 11:18:34 +0000811 } else if arg == "--build-from-text-stub" {
812 c.buildFromTextStub = true
MarkDacekb96561e2022-12-02 04:34:43 +0000813 } else if strings.HasPrefix(arg, "--build-command=") {
814 buildCmd := strings.TrimPrefix(arg, "--build-command=")
815 // remove quotations
816 buildCmd = strings.TrimPrefix(buildCmd, "\"")
817 buildCmd = strings.TrimSuffix(buildCmd, "\"")
818 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000819 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
820 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
MarkDacek6614d9c2022-12-07 21:57:38 +0000821 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
822 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
823 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
824 if err == nil {
825 c.buildStartedTime = val
826 } else {
827 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
828 }
MarkDacekf47e1422023-04-19 16:47:36 +0000829 } else if arg == "--ensure-allowlist-integrity" {
830 c.ensureAllowlistIntegrity = true
MarkDacekd33c2fd2023-05-04 20:40:04 +0000831 } else if strings.HasPrefix(arg, "--bazel-exit-code=") {
832 bazelExitCodeStr := strings.TrimPrefix(arg, "--bazel-exit-code=")
833 val, err := strconv.Atoi(bazelExitCodeStr)
834 if err == nil {
835 c.bazelExitCode = int32(val)
836 } else {
837 ctx.Fatalf("Error parsing bazel-exit-code", err)
838 }
MarkDacek396491e2023-06-14 19:41:18 +0000839 } else if strings.HasPrefix(arg, "--bes-id=") {
840 c.besId = strings.TrimPrefix(arg, "--bes-id=")
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700841 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700842 parseArgNum := func(def int) int {
843 if len(arg) > 2 {
844 p, err := strconv.ParseUint(arg[2:], 10, 31)
845 if err != nil {
846 ctx.Fatalf("Failed to parse %q: %v", arg, err)
847 }
848 return int(p)
849 } else if i+1 < len(args) {
850 p, err := strconv.ParseUint(args[i+1], 10, 31)
851 if err == nil {
852 i++
853 return int(p)
854 }
855 }
856 return def
857 }
858
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700859 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700860 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700861 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700862 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700863 } else {
864 ctx.Fatalln("Unknown option:", arg)
865 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700866 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700867 if k == "OUT_DIR" {
868 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
869 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700870 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700871 } else if arg == "dist" {
872 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200873 } else if arg == "json-module-graph" {
874 c.jsonModuleGraph = true
875 } else if arg == "bp2build" {
876 c.bp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200877 } else if arg == "queryview" {
878 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200879 } else if arg == "soong_docs" {
880 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700881 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700882 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800883 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700884 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700885 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700886 }
887 }
Chris Parsons21f80272023-06-15 04:02:28 +0000888 if (!c.bazelProdMode) && (!c.bazelStagingMode) {
Chris Parsonsb6e96902022-10-31 20:08:45 -0400889 c.bazelProdMode = defaultBazelProdMode(c)
890 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700891}
892
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900893func validateNinjaWeightList(weightListFilePath string) (err error) {
894 data, err := os.ReadFile(weightListFilePath)
895 if err != nil {
896 return
897 }
898 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
899 for _, line := range lines {
900 fields := strings.Split(line, ",")
901 if len(fields) != 2 {
902 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
903 }
904 _, err = strconv.Atoi(fields[1])
905 if err != nil {
906 return
907 }
908 }
909 return
910}
911
Dan Willemsened869522018-01-08 14:58:46 -0800912func (c *configImpl) configureLocale(ctx Context) {
913 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
914 output, err := cmd.Output()
915
916 var locales []string
917 if err == nil {
918 locales = strings.Split(string(output), "\n")
919 } else {
920 // If we're unable to list the locales, let's assume en_US.UTF-8
921 locales = []string{"en_US.UTF-8"}
922 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
923 }
924
925 // gettext uses LANGUAGE, which is passed directly through
926
927 // For LANG and LC_*, only preserve the evaluated version of
928 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800929 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800930 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800931 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800932 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800933 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800934 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800935 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800936 }
937
938 c.environ.UnsetWithPrefix("LC_")
939
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800940 if userLang != "" {
941 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800942 }
943
944 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
945 // for others)
946 if inList("C.UTF-8", locales) {
947 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500948 } else if inList("C.utf8", locales) {
949 // These normalize to the same thing
950 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800951 } else if inList("en_US.UTF-8", locales) {
952 c.environ.Set("LANG", "en_US.UTF-8")
953 } else if inList("en_US.utf8", locales) {
954 // These normalize to the same thing
955 c.environ.Set("LANG", "en_US.UTF-8")
956 } else {
957 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
958 }
959}
960
Dan Willemsen1e704462016-08-21 15:17:17 -0700961func (c *configImpl) Environment() *Environment {
962 return c.environ
963}
964
965func (c *configImpl) Arguments() []string {
966 return c.arguments
967}
968
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200969func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200970 if len(c.Arguments()) > 0 {
971 // Explicit targets requested that are not special targets like b2pbuild
972 // or the JSON module graph
973 return true
974 }
975
Chris Parsons73f411b2023-06-20 21:46:57 +0000976 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200977 // Command line was empty, the default Ninja target is built
978 return true
979 }
980
Liz Kammer88677422021-12-15 15:03:19 -0500981 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
982 if c.Dist() && !c.Bp2Build() {
983 return true
984 }
985
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200986 // build.ninja doesn't need to be generated
987 return false
988}
989
Dan Willemsen1e704462016-08-21 15:17:17 -0700990func (c *configImpl) OutDir() string {
991 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700992 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700993 }
994 return "out"
995}
996
Dan Willemsen8a073a82017-02-04 17:30:44 -0800997func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400998 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000999}
1000
1001func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -07001002 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -08001003}
1004
Dan Willemsen1e704462016-08-21 15:17:17 -07001005func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001006 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001007 return c.arguments
1008 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001009 return c.ninjaArgs
1010}
1011
Jingwen Chen7c6089a2020-11-02 02:56:20 -05001012func (c *configImpl) BazelOutDir() string {
1013 return filepath.Join(c.OutDir(), "bazel")
1014}
1015
Liz Kammer2af5ea82022-11-11 14:21:03 -05001016func (c *configImpl) bazelOutputBase() string {
1017 return filepath.Join(c.BazelOutDir(), "output")
1018}
1019
Dan Willemsen1e704462016-08-21 15:17:17 -07001020func (c *configImpl) SoongOutDir() string {
1021 return filepath.Join(c.OutDir(), "soong")
1022}
1023
Spandan Das394aa322022-11-03 17:02:10 +00001024func (c *configImpl) ApiSurfacesOutDir() string {
1025 return filepath.Join(c.OutDir(), "api_surfaces")
1026}
1027
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001028func (c *configImpl) PrebuiltOS() string {
1029 switch runtime.GOOS {
1030 case "linux":
1031 return "linux-x86"
1032 case "darwin":
1033 return "darwin-x86"
1034 default:
1035 panic("Unknown GOOS")
1036 }
1037}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001038
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001039func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001040 if c.SkipKatiNinja() {
1041 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1042 } else {
1043 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1044 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001045}
1046
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001047func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001048 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001049}
1050
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001051func (c *configImpl) UsedEnvFile(tag string) string {
Kiyoung Kimeaa55a82023-06-05 16:56:49 +09001052 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1053 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+v+"."+tag)
1054 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001055 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1056}
1057
Lukacs T. Berkic541cd22022-10-26 07:26:50 +00001058func (c *configImpl) Bp2BuildFilesMarkerFile() string {
1059 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
1060}
1061
1062func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001063 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +02001064}
1065
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001066func (c *configImpl) SoongDocsHtml() string {
1067 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1068}
1069
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001070func (c *configImpl) QueryviewMarkerFile() string {
1071 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1072}
1073
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001074func (c *configImpl) ModuleGraphFile() string {
1075 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1076}
1077
kgui67007242022-01-25 13:50:25 +08001078func (c *configImpl) ModuleActionsFile() string {
1079 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1080}
1081
Jeff Gastonefc1b412017-03-29 17:29:06 -07001082func (c *configImpl) TempDir() string {
1083 return shared.TempDirForOutDir(c.SoongOutDir())
1084}
1085
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001086func (c *configImpl) FileListDir() string {
1087 return filepath.Join(c.OutDir(), ".module_paths")
1088}
1089
Dan Willemsen1e704462016-08-21 15:17:17 -07001090func (c *configImpl) KatiSuffix() string {
1091 if c.katiSuffix != "" {
1092 return c.katiSuffix
1093 }
1094 panic("SetKatiSuffix has not been called")
1095}
1096
Colin Cross37193492017-11-16 17:55:00 -08001097// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1098// user is interested in additional checks at the expense of build time.
1099func (c *configImpl) Checkbuild() bool {
1100 return c.checkbuild
1101}
1102
Dan Willemsen8a073a82017-02-04 17:30:44 -08001103func (c *configImpl) Dist() bool {
1104 return c.dist
1105}
1106
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001107func (c *configImpl) JsonModuleGraph() bool {
1108 return c.jsonModuleGraph
1109}
1110
1111func (c *configImpl) Bp2Build() bool {
1112 return c.bp2build
1113}
1114
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001115func (c *configImpl) Queryview() bool {
1116 return c.queryview
1117}
1118
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001119func (c *configImpl) SoongDocs() bool {
1120 return c.soongDocs
1121}
1122
Dan Willemsen1e704462016-08-21 15:17:17 -07001123func (c *configImpl) IsVerbose() bool {
1124 return c.verbose
1125}
1126
LaMont Jones52a72432023-03-09 18:19:35 +00001127func (c *configImpl) MultitreeBuild() bool {
1128 return c.multitreeBuild
1129}
1130
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001131func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1132 return c.ninjaWeightListSource
1133}
1134
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001135func (c *configImpl) SkipKati() bool {
1136 return c.skipKati
1137}
1138
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001139func (c *configImpl) SkipKatiNinja() bool {
1140 return c.skipKatiNinja
1141}
1142
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001143func (c *configImpl) SkipSoong() bool {
1144 return c.skipSoong
1145}
1146
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001147func (c *configImpl) SkipNinja() bool {
1148 return c.skipNinja
1149}
1150
Anton Hansson5a7861a2021-06-04 10:09:01 +01001151func (c *configImpl) SetSkipNinja(v bool) {
1152 c.skipNinja = v
1153}
1154
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001155func (c *configImpl) SkipConfig() bool {
1156 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001157}
1158
Jihoon Kang1bff0342023-01-17 20:40:22 +00001159func (c *configImpl) BuildFromTextStub() bool {
Sebastian Pickl1c4188c2023-10-24 11:18:34 +00001160 return c.buildFromTextStub
Jihoon Kang1bff0342023-01-17 20:40:22 +00001161}
1162
Dan Willemsen1e704462016-08-21 15:17:17 -07001163func (c *configImpl) TargetProduct() string {
1164 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1165 return v
1166 }
1167 panic("TARGET_PRODUCT is not defined")
1168}
1169
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001170func (c *configImpl) TargetProductOrErr() (string, error) {
1171 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1172 return v, nil
1173 }
1174 return "", fmt.Errorf("TARGET_PRODUCT is not defined")
1175}
1176
Dan Willemsen02781d52017-05-12 19:28:13 -07001177func (c *configImpl) TargetDevice() string {
1178 return c.targetDevice
1179}
1180
1181func (c *configImpl) SetTargetDevice(device string) {
1182 c.targetDevice = device
1183}
1184
1185func (c *configImpl) TargetBuildVariant() string {
1186 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1187 return v
1188 }
1189 panic("TARGET_BUILD_VARIANT is not defined")
1190}
1191
Dan Willemsen1e704462016-08-21 15:17:17 -07001192func (c *configImpl) KatiArgs() []string {
1193 return c.katiArgs
1194}
1195
1196func (c *configImpl) Parallel() int {
1197 return c.parallel
1198}
1199
Sam Delmerico98a73292023-02-21 11:50:29 -05001200func (c *configImpl) GetSourceRootDirs() []string {
1201 return c.sourceRootDirs
1202}
1203
1204func (c *configImpl) SetSourceRootDirs(i []string) {
1205 c.sourceRootDirs = i
1206}
1207
Spandan Dasc5763832022-11-08 18:42:16 +00001208func (c *configImpl) GetIncludeTags() []string {
1209 return c.includeTags
1210}
1211
1212func (c *configImpl) SetIncludeTags(i []string) {
1213 c.includeTags = i
1214}
1215
MarkDacek6614d9c2022-12-07 21:57:38 +00001216func (c *configImpl) GetLogsPrefix() string {
1217 return c.logsPrefix
1218}
1219
1220func (c *configImpl) SetLogsPrefix(prefix string) {
1221 c.logsPrefix = prefix
1222}
1223
Colin Cross8b8bec32019-11-15 13:18:43 -08001224func (c *configImpl) HighmemParallel() int {
1225 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1226 return i
1227 }
1228
1229 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1230 parallel := c.Parallel()
1231 if c.UseRemoteBuild() {
1232 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1233 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1234 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1235 // Return 1/16th of the size of the local pool, rounding up.
1236 return (parallel + 15) / 16
1237 } else if c.totalRAM == 0 {
1238 // Couldn't detect the total RAM, don't restrict highmem processes.
1239 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001240 } else if c.totalRAM <= 16*1024*1024*1024 {
1241 // Less than 16GB of ram, restrict to 1 highmem processes
1242 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001243 } else if c.totalRAM <= 32*1024*1024*1024 {
1244 // Less than 32GB of ram, restrict to 2 highmem processes
1245 return 2
1246 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1247 // If less than 8GB total RAM per process, reduce the number of highmem processes
1248 return p
1249 }
1250 // No restriction on highmem processes
1251 return parallel
1252}
1253
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001254func (c *configImpl) TotalRAM() uint64 {
1255 return c.totalRAM
1256}
1257
Kousik Kumarec478642020-09-21 13:39:24 -04001258// ForceUseGoma determines whether we should override Goma deprecation
1259// and use Goma for the current build or not.
1260func (c *configImpl) ForceUseGoma() bool {
1261 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1262 v = strings.TrimSpace(v)
1263 if v != "" && v != "false" {
1264 return true
1265 }
1266 }
1267 return false
1268}
1269
Dan Willemsen1e704462016-08-21 15:17:17 -07001270func (c *configImpl) UseGoma() bool {
1271 if v, ok := c.environ.Get("USE_GOMA"); ok {
1272 v = strings.TrimSpace(v)
1273 if v != "" && v != "false" {
1274 return true
1275 }
1276 }
1277 return false
1278}
1279
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001280func (c *configImpl) StartGoma() bool {
1281 if !c.UseGoma() {
1282 return false
1283 }
1284
1285 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1286 v = strings.TrimSpace(v)
1287 if v != "" && v != "false" {
1288 return false
1289 }
1290 }
1291 return true
1292}
1293
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001294func (c *configImpl) canSupportRBE() bool {
1295 // Do not use RBE with prod credentials in scenarios when stubby doesn't exist, since
1296 // its unlikely that we will be able to obtain necessary creds without stubby.
1297 authType, _ := c.rbeAuth()
1298 if !c.StubbyExists() && strings.Contains(authType, "use_google_prod_creds") {
1299 return false
1300 }
1301 return true
1302}
1303
Ramy Medhatbbf25672019-07-17 12:30:04 +00001304func (c *configImpl) UseRBE() bool {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001305 // These alternate modes of running Soong do not use RBE / reclient.
Chris Parsons73f411b2023-06-20 21:46:57 +00001306 if c.Bp2Build() || c.Queryview() || c.JsonModuleGraph() {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001307 return false
1308 }
1309
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001310 if !c.canSupportRBE() {
Kousik Kumar67ad4342023-06-06 15:09:27 -04001311 return false
1312 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001313
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001314 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001315 v = strings.TrimSpace(v)
1316 if v != "" && v != "false" {
1317 return true
1318 }
1319 }
1320 return false
1321}
1322
Chris Parsonsef615e52022-08-18 22:04:11 -04001323func (c *configImpl) BazelBuildEnabled() bool {
Chris Parsons21f80272023-06-15 04:02:28 +00001324 return c.bazelProdMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001325}
1326
Ramy Medhatbbf25672019-07-17 12:30:04 +00001327func (c *configImpl) StartRBE() bool {
1328 if !c.UseRBE() {
1329 return false
1330 }
1331
1332 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1333 v = strings.TrimSpace(v)
1334 if v != "" && v != "false" {
1335 return false
1336 }
1337 }
1338 return true
1339}
1340
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001341func (c *configImpl) rbeProxyLogsDir() string {
1342 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001343 if v, ok := c.environ.Get(f); ok {
1344 return v
1345 }
1346 }
Ramy Medhatbc061762023-10-10 18:36:59 +00001347 return c.rbeTmpDir()
1348}
1349
1350func (c *configImpl) rbeDownloadTmpDir() string {
Cole Faust06ea5312023-10-18 17:38:40 -07001351 for _, f := range []string{"RBE_download_tmp_dir", "FLAG_download_tmp_dir"} {
Ramy Medhatbc061762023-10-10 18:36:59 +00001352 if v, ok := c.environ.Get(f); ok {
1353 return v
1354 }
1355 }
1356 return c.rbeTmpDir()
1357}
1358
1359func (c *configImpl) rbeTmpDir() string {
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001360 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1361 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001362}
1363
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001364func (c *configImpl) rbeCacheDir() string {
1365 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1366 if v, ok := c.environ.Get(f); ok {
1367 return v
1368 }
1369 }
1370 return shared.JoinPath(c.SoongOutDir(), "rbe")
1371}
1372
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001373func (c *configImpl) shouldCleanupRBELogsDir() bool {
1374 // Perform a log directory cleanup only when the log directory
1375 // is auto created by the build rather than user-specified.
1376 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1377 if _, ok := c.environ.Get(f); ok {
1378 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001379 }
1380 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001381 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001382}
1383
1384func (c *configImpl) rbeExecRoot() string {
1385 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1386 if v, ok := c.environ.Get(f); ok {
1387 return v
1388 }
1389 }
1390 wd, err := os.Getwd()
1391 if err != nil {
1392 return ""
1393 }
1394 return wd
1395}
1396
1397func (c *configImpl) rbeDir() string {
1398 if v, ok := c.environ.Get("RBE_DIR"); ok {
1399 return v
1400 }
1401 return "prebuilts/remoteexecution-client/live/"
1402}
1403
1404func (c *configImpl) rbeReproxy() string {
1405 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1406 if v, ok := c.environ.Get(f); ok {
1407 return v
1408 }
1409 }
1410 return filepath.Join(c.rbeDir(), "reproxy")
1411}
1412
1413func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001414 credFlags := []string{
1415 "use_application_default_credentials",
1416 "use_gce_credentials",
1417 "credential_file",
1418 "use_google_prod_creds",
1419 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001420 for _, cf := range credFlags {
1421 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1422 if v, ok := c.environ.Get(f); ok {
1423 v = strings.TrimSpace(v)
1424 if v != "" && v != "false" && v != "0" {
1425 return "RBE_" + cf, v
1426 }
1427 }
1428 }
1429 }
1430 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001431}
1432
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001433func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1434 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1435 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1436
1437 name := filepath.Join(dir, base)
1438 if len(name) < maxNameLen {
1439 return name, nil
1440 }
1441
1442 name = filepath.Join("/tmp", base)
1443 if len(name) < maxNameLen {
1444 return name, nil
1445 }
1446
1447 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1448}
1449
Kousik Kumar7bc78192022-04-27 14:52:56 -04001450// IsGooglerEnvironment returns true if the current build is running
1451// on a Google developer machine and false otherwise.
1452func (c *configImpl) IsGooglerEnvironment() bool {
1453 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1454 if v, ok := c.environ.Get(cf); ok {
1455 return v == "googler"
1456 }
1457 return false
1458}
1459
1460// GoogleProdCredsExist determine whether credentials exist on the
1461// Googler machine to use remote execution.
1462func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001463 if googleProdCredsExistCache {
1464 return googleProdCredsExistCache
1465 }
andusyu0b3dc032023-06-21 17:29:32 -04001466 if _, err := exec.Command("/usr/bin/gcertstatus", "-nocheck_ssh").Output(); err != nil {
Kousik Kumar7bc78192022-04-27 14:52:56 -04001467 return false
1468 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001469 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001470 return true
1471}
1472
1473// UseRemoteBuild indicates whether to use a remote build acceleration system
1474// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001475func (c *configImpl) UseRemoteBuild() bool {
1476 return c.UseGoma() || c.UseRBE()
1477}
1478
Kousik Kumar7bc78192022-04-27 14:52:56 -04001479// StubbyExists checks whether the stubby binary exists on the machine running
1480// the build.
1481func (c *configImpl) StubbyExists() bool {
1482 if _, err := exec.LookPath("stubby"); err != nil {
1483 return false
1484 }
1485 return true
1486}
1487
Dan Willemsen1e704462016-08-21 15:17:17 -07001488// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001489// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001490// still limited by Parallel()
1491func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001492 if !c.UseRemoteBuild() {
1493 return 0
1494 }
1495 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1496 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001497 }
1498 return 500
1499}
1500
1501func (c *configImpl) SetKatiArgs(args []string) {
1502 c.katiArgs = args
1503}
1504
1505func (c *configImpl) SetNinjaArgs(args []string) {
1506 c.ninjaArgs = args
1507}
1508
1509func (c *configImpl) SetKatiSuffix(suffix string) {
1510 c.katiSuffix = suffix
1511}
1512
Dan Willemsene0879fc2017-08-04 15:06:27 -07001513func (c *configImpl) LastKatiSuffixFile() string {
1514 return filepath.Join(c.OutDir(), "last_kati_suffix")
1515}
1516
1517func (c *configImpl) HasKatiSuffix() bool {
1518 return c.katiSuffix != ""
1519}
1520
Dan Willemsen1e704462016-08-21 15:17:17 -07001521func (c *configImpl) KatiEnvFile() string {
1522 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1523}
1524
Dan Willemsen29971232018-09-26 14:58:30 -07001525func (c *configImpl) KatiBuildNinjaFile() string {
1526 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001527}
1528
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001529func (c *configImpl) KatiPackageNinjaFile() string {
1530 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1531}
1532
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001533func (c *configImpl) SoongVarsFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001534 targetProduct, err := c.TargetProductOrErr()
1535 if err != nil {
1536 return filepath.Join(c.SoongOutDir(), "soong.variables")
1537 } else {
1538 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+".variables")
1539 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001540}
1541
Dan Willemsen1e704462016-08-21 15:17:17 -07001542func (c *configImpl) SoongNinjaFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001543 targetProduct, err := c.TargetProductOrErr()
1544 if err != nil {
1545 return filepath.Join(c.SoongOutDir(), "build.ninja")
1546 } else {
1547 return filepath.Join(c.SoongOutDir(), "build."+targetProduct+".ninja")
1548 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001549}
1550
1551func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001552 if c.katiSuffix == "" {
1553 return filepath.Join(c.OutDir(), "combined.ninja")
1554 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001555 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1556}
1557
1558func (c *configImpl) SoongAndroidMk() string {
1559 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1560}
1561
1562func (c *configImpl) SoongMakeVarsMk() string {
1563 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1564}
1565
Dan Willemsenf052f782017-05-18 15:29:04 -07001566func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001567 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001568}
1569
Dan Willemsen02781d52017-05-12 19:28:13 -07001570func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001571 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1572}
1573
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001574func (c *configImpl) KatiPackageMkDir() string {
1575 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1576}
1577
Dan Willemsenf052f782017-05-18 15:29:04 -07001578func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001579 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001580}
1581
1582func (c *configImpl) HostOut() string {
1583 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1584}
1585
1586// This probably needs to be multi-valued, so not exporting it for now
1587func (c *configImpl) hostCrossOut() string {
1588 if runtime.GOOS == "linux" {
1589 return filepath.Join(c.hostOutRoot(), "windows-x86")
1590 } else {
1591 return ""
1592 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001593}
1594
Dan Willemsen1e704462016-08-21 15:17:17 -07001595func (c *configImpl) HostPrebuiltTag() string {
1596 if runtime.GOOS == "linux" {
1597 return "linux-x86"
1598 } else if runtime.GOOS == "darwin" {
1599 return "darwin-x86"
1600 } else {
1601 panic("Unsupported OS")
1602 }
1603}
Dan Willemsenf173d592017-04-27 14:28:00 -07001604
Dan Willemsen8122bd52017-10-12 20:20:41 -07001605func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001606 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1607 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001608 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1609 if _, err := os.Stat(asan); err == nil {
1610 return asan
1611 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001612 }
1613 }
1614 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1615}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001616
1617func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1618 c.brokenDupRules = val
1619}
1620
1621func (c *configImpl) BuildBrokenDupRules() bool {
1622 return c.brokenDupRules
1623}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001624
Dan Willemsen25e6f092019-04-09 10:22:43 -07001625func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1626 c.brokenUsesNetwork = val
1627}
1628
1629func (c *configImpl) BuildBrokenUsesNetwork() bool {
1630 return c.brokenUsesNetwork
1631}
1632
Dan Willemsene3336352020-01-02 19:10:38 -08001633func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1634 c.brokenNinjaEnvVars = val
1635}
1636
1637func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1638 return c.brokenNinjaEnvVars
1639}
1640
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001641func (c *configImpl) SetTargetDeviceDir(dir string) {
1642 c.targetDeviceDir = dir
1643}
1644
1645func (c *configImpl) TargetDeviceDir() string {
1646 return c.targetDeviceDir
1647}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001648
Patrice Arruda219eef32020-06-01 17:29:30 +00001649func (c *configImpl) BuildDateTime() string {
1650 return c.buildDateTime
1651}
1652
1653func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001654 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001655}
Patrice Arruda83842d72020-12-08 19:42:08 +00001656
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001657// LogsDir returns the absolute path to the logs directory where build log and
1658// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001659// directory. If the argument dist is specified, the logs directory
1660// is <dist_dir>/logs.
1661func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001662 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001663 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001664 // 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 -05001665 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001666 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001667 absDir, err := filepath.Abs(dir)
1668 if err != nil {
1669 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1670 os.Exit(1)
1671 }
1672 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001673}
1674
1675// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1676// where the bazel profiles are located.
1677func (c *configImpl) BazelMetricsDir() string {
1678 return filepath.Join(c.LogsDir(), "bazel_metrics")
1679}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001680
Chris Parsons53f68ae2022-03-03 12:01:40 -05001681// MkFileMetrics returns the file path for make-related metrics.
1682func (c *configImpl) MkMetrics() string {
1683 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1684}
1685
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001686func (c *configImpl) SetEmptyNinjaFile(v bool) {
1687 c.emptyNinjaFile = v
1688}
1689
1690func (c *configImpl) EmptyNinjaFile() bool {
1691 return c.emptyNinjaFile
1692}
Yu Liu6e13b402021-07-27 14:29:06 -07001693
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001694func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1695 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1696}
1697
Chris Parsons9402ca82023-02-23 17:28:06 -05001698func (c *configImpl) IsPersistentBazelEnabled() bool {
1699 return c.Environment().IsEnvTrue("USE_PERSISTENT_BAZEL")
1700}
1701
Chris Parsonsc83398f2023-05-31 18:41:41 +00001702// GetBazeliskBazelVersion returns the Bazel version to use for this build,
1703// or the empty string if the current canonical prod Bazel should be used.
1704// This environment variable should only be set to debug the build system.
1705// The Bazel version, if set, will be passed to Bazelisk, and Bazelisk will
1706// handle downloading and invoking the correct Bazel binary.
1707func (c *configImpl) GetBazeliskBazelVersion() string {
1708 value, _ := c.Environment().Get("USE_BAZEL_VERSION")
1709 return value
1710}
1711
MarkDacekd06db5d2022-11-29 00:47:59 +00001712func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1713 return c.bazelForceEnabledModules
1714}
1715
MarkDacekd0e7cd32022-12-02 22:22:40 +00001716func (c *configImpl) SkipMetricsUpload() bool {
1717 return c.skipMetricsUpload
1718}
1719
MarkDacekf47e1422023-04-19 16:47:36 +00001720func (c *configImpl) EnsureAllowlistIntegrity() bool {
1721 return c.ensureAllowlistIntegrity
1722}
1723
MarkDacek6614d9c2022-12-07 21:57:38 +00001724// Returns a Time object if one was passed via a command-line flag.
1725// Otherwise returns the passed default.
1726func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1727 if c.buildStartedTime == 0 {
1728 return defaultTime
1729 }
1730 return time.UnixMilli(c.buildStartedTime)
1731}
1732
MarkDacekd33c2fd2023-05-04 20:40:04 +00001733func (c *configImpl) BazelExitCode() int32 {
1734 return c.bazelExitCode
1735}
1736
Yu Liu6e13b402021-07-27 14:29:06 -07001737func GetMetricsUploader(topDir string, env *Environment) string {
1738 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1739 metricsUploader := filepath.Join(topDir, p)
1740 if _, err := os.Stat(metricsUploader); err == nil {
1741 return metricsUploader
1742 }
1743 }
1744
1745 return ""
1746}