blob: b228bb493edf7ad3661cf9f4b200acc0345fe6cc [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
Dan Willemsen1e704462016-08-21 15:17:17 -0700208func NewConfig(ctx Context, args ...string) Config {
209 ret := &configImpl{
Jeongik Chaf2ecf762023-05-19 14:03:45 +0900210 environ: OsEnvironment(),
211 sandboxConfig: &SandboxConfig{},
Jeongik Chaa87506f2023-06-01 23:16:41 +0900212 ninjaWeightListSource: DEFAULT,
Dan Willemsen1e704462016-08-21 15:17:17 -0700213 }
214
Colin Cross106d6ef2023-10-24 10:34:56 -0700215 // Skip soong tests by default on Linux
216 if runtime.GOOS == "linux" {
217 ret.skipSoongTests = true
218 }
219
Patrice Arruda90109172020-07-28 18:07:27 +0000220 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700221 ret.parallel = runtime.NumCPU() + 2
222 ret.keepGoing = 1
223
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800224 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700225 ret.parseArgs(ctx, args)
Jeongik Chae114e602023-03-19 00:12:39 +0900226
227 if ret.ninjaWeightListSource == HINT_FROM_SOONG {
Jeongik Chaa87506f2023-06-01 23:16:41 +0900228 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "always")
229 } else if ret.ninjaWeightListSource == DEFAULT {
230 defaultNinjaWeightListSource := NINJA_LOG
231 if _, err := os.Stat(filepath.Join(ret.OutDir(), ninjaLogFileName)); errors.Is(err, os.ErrNotExist) {
232 ctx.Verboseln("$OUT/.ninja_log doesn't exist, use HINT_FROM_SOONG instead")
233 defaultNinjaWeightListSource = HINT_FROM_SOONG
234 } else {
235 ctx.Verboseln("$OUT/.ninja_log exist, use NINJA_LOG")
236 }
237 ret.ninjaWeightListSource = defaultNinjaWeightListSource
238 // soong_build generates ninja hint depending on ninja log existence.
239 // Set it "depend" to avoid soong re-run due to env variable change.
240 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "depend")
Jeongik Chae114e602023-03-19 00:12:39 +0900241 }
Jeongik Chaa87506f2023-06-01 23:16:41 +0900242
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800243 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700244 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
245 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
246 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800247 outDir := "out"
248 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
249 if wd, err := os.Getwd(); err != nil {
250 ctx.Fatalln("Failed to get working directory:", err)
251 } else {
252 outDir = filepath.Join(baseDir, filepath.Base(wd))
253 }
254 }
255 ret.environ.Set("OUT_DIR", outDir)
256 }
257
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500258 // loadEnvConfig needs to know what the OUT_DIR is, so it should
259 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000260 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
261
262 if bc != "" {
Kousik Kumarc8818332023-01-16 16:33:05 +0000263 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000264 ctx.Fatalln("Failed to parse env config files: %v", err)
265 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +0000266 if !ret.canSupportRBE() {
267 // Explicitly set USE_RBE env variable to false when we cannot run
268 // an RBE build to avoid ninja local execution pool issues.
269 ret.environ.Set("USE_RBE", "false")
270 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500271 }
272
Dan Willemsen2d31a442018-10-20 21:33:41 -0700273 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
274 ret.distDir = filepath.Clean(distDir)
275 } else {
276 ret.distDir = filepath.Join(ret.OutDir(), "dist")
277 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700278
Spandan Das05063612021-06-25 01:39:04 +0000279 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
280 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
281 }
282
Dan Willemsen1e704462016-08-21 15:17:17 -0700283 ret.environ.Unset(
284 // We're already using it
285 "USE_SOONG_UI",
286
287 // We should never use GOROOT/GOPATH from the shell environment
288 "GOROOT",
289 "GOPATH",
290
291 // These should only come from Soong, not the environment.
292 "CLANG",
293 "CLANG_CXX",
294 "CCC_CC",
295 "CCC_CXX",
296
297 // Used by the goma compiler wrapper, but should only be set by
298 // gomacc
299 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800300
301 // We handle this above
302 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700303
Dan Willemsen2d31a442018-10-20 21:33:41 -0700304 // This is handled above too, and set for individual commands later
305 "DIST_DIR",
306
Dan Willemsen68a09852017-04-18 13:56:57 -0700307 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000308 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700309 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700310 "DISPLAY",
311 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000312 "JAVAC",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700313 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700314 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700315
316 // Drop make flags
317 "MAKEFLAGS",
318 "MAKELEVEL",
319 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700320
321 // Set in envsetup.sh, reset in makefiles
322 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700323
324 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
325 "ANDROID_BUILD_TOP",
326 "ANDROID_HOST_OUT",
327 "ANDROID_PRODUCT_OUT",
328 "ANDROID_HOST_OUT_TESTCASES",
329 "ANDROID_TARGET_OUT_TESTCASES",
330 "ANDROID_TOOLCHAIN",
331 "ANDROID_TOOLCHAIN_2ND_ARCH",
332 "ANDROID_DEV_SCRIPTS",
333 "ANDROID_EMULATOR_PREBUILTS",
334 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700335 )
336
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400337 if ret.UseGoma() || ret.ForceUseGoma() {
338 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
339 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400340 }
341
Dan Willemsen1e704462016-08-21 15:17:17 -0700342 // Tell python not to spam the source tree with .pyc files.
343 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
344
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400345 tmpDir := absPath(ctx, ret.TempDir())
346 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800347
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700348 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
349 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
350 "llvm-binutils-stable/llvm-symbolizer")
351 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
352
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800353 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700354 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800355
Yu Liu6e13b402021-07-27 14:29:06 -0700356 srcDir := absPath(ctx, ".")
357 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700358 ctx.Println("You are building in a directory whose absolute path contains a space character:")
359 ctx.Println()
360 ctx.Printf("%q\n", srcDir)
361 ctx.Println()
362 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700363 }
364
Yu Liu6e13b402021-07-27 14:29:06 -0700365 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
366
Dan Willemsendb8457c2017-05-12 16:38:17 -0700367 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700368 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
369 ctx.Println()
370 ctx.Printf("%q\n", outDir)
371 ctx.Println()
372 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700373 }
374
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000375 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700376 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
377 ctx.Println()
378 ctx.Printf("%q\n", distDir)
379 ctx.Println()
380 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700381 }
382
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700383 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000384 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
385 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100386 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800387 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700388 javaHome := func() string {
389 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
390 return override
391 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000392 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
393 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 +0100394 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000395 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
396 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
397 }
398 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700399 }()
400 absJavaHome := absPath(ctx, javaHome)
401
Dan Willemsened869522018-01-08 14:58:46 -0800402 ret.configureLocale(ctx)
403
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700404 newPath := []string{filepath.Join(absJavaHome, "bin")}
405 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
406 newPath = append(newPath, path)
407 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100408
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700409 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
410 ret.environ.Set("JAVA_HOME", absJavaHome)
411 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000412 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
413 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100414 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700415 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
416
Colin Crossfe5ed4d2023-07-28 09:27:23 -0700417 // b/286885495, https://bugzilla.redhat.com/show_bug.cgi?id=2227130: some versions of Fedora include patches
418 // to unzip to enable zipbomb detection that incorrectly handle zip64 and data descriptors and fail on large
419 // zip files produced by soong_zip. Disable zipbomb detection.
420 ret.environ.Set("UNZIP_DISABLE_ZIPBOMB_DETECTION", "TRUE")
421
LaMont Jones52a72432023-03-09 18:19:35 +0000422 if ret.MultitreeBuild() {
423 ret.environ.Set("MULTITREE_BUILD", "true")
424 }
425
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800426 outDir := ret.OutDir()
427 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800428 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800429 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800430 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800431 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800432 }
Colin Cross28f527c2019-11-26 16:19:04 -0800433
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800434 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
435
Cole Faust583dfb42023-09-28 13:56:30 -0700436 if _, ok := ret.environ.Get("BUILD_USERNAME"); !ok {
437 username := "unknown"
438 if u, err := user.Current(); err == nil {
439 username = u.Username
440 } else {
441 ctx.Println("Failed to get current user:", err)
442 }
443 ret.environ.Set("BUILD_USERNAME", username)
444 }
445
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400446 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400447 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400448 ret.environ.Set(k, v)
449 }
450 }
451
Patrice Arruda83842d72020-12-08 19:42:08 +0000452 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800453 if err := os.RemoveAll(bpd); err != nil {
454 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
455 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000456
Patrice Arruda96850362020-08-11 20:41:11 +0000457 c := Config{ret}
458 storeConfigMetrics(ctx, c)
459 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700460}
461
Patrice Arruda13848222019-04-22 17:12:02 -0700462// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
463// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700464func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
465 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700466}
467
Patrice Arruda96850362020-08-11 20:41:11 +0000468// storeConfigMetrics selects a set of configuration information and store in
469// the metrics system for further analysis.
470func storeConfigMetrics(ctx Context, config Config) {
471 if ctx.Metrics == nil {
472 return
473 }
474
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400475 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000476
477 s := &smpb.SystemResourceInfo{
478 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
479 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
480 }
481 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000482}
483
Jeongik Cha8d63d562023-03-17 03:52:13 +0900484func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900485 switch s {
486 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900487 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900488 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900489 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900490 case EXTERNAL_FILE:
491 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900492 case HINT_FROM_SOONG:
493 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900494 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900495 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900496 }
497}
498
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400499func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700500 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400501 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
502 UseGoma: proto.Bool(config.UseGoma()),
503 UseRbe: proto.Bool(config.UseRBE()),
504 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
505 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900506 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400507 }
Yu Liue737a992021-10-04 13:21:41 -0700508 c.Targets = append(c.Targets, config.arguments...)
509
510 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400511}
512
Patrice Arruda13848222019-04-22 17:12:02 -0700513// getConfigArgs processes the command arguments based on the build action and creates a set of new
514// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700515func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700516 // The next block of code verifies that the current directory is the root directory of the source
517 // tree. It then finds the relative path of dir based on the root directory of the source tree
518 // and verify that dir is inside of the source tree.
519 checkTopDir(ctx)
520 topDir, err := os.Getwd()
521 if err != nil {
522 ctx.Fatalf("Error retrieving top directory: %v", err)
523 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700524 dir, err = filepath.EvalSymlinks(dir)
525 if err != nil {
526 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
527 }
Patrice Arruda13848222019-04-22 17:12:02 -0700528 dir, err = filepath.Abs(dir)
529 if err != nil {
530 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
531 }
532 relDir, err := filepath.Rel(topDir, dir)
533 if err != nil {
534 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
535 }
536 // If there are ".." in the path, it's not in the source tree.
537 if strings.Contains(relDir, "..") {
538 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
539 }
540
541 configArgs := args[:]
542
543 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
544 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
545 targetNamePrefix := "MODULES-IN-"
546 if inList("GET-INSTALL-PATH", configArgs) {
547 targetNamePrefix = "GET-INSTALL-PATH-IN-"
548 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
549 }
550
Patrice Arruda13848222019-04-22 17:12:02 -0700551 var targets []string
552
553 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700554 case BUILD_MODULES:
555 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700556 case BUILD_MODULES_IN_A_DIRECTORY:
557 // If dir is the root source tree, all the modules are built of the source tree are built so
558 // no need to find the build file.
559 if topDir == dir {
560 break
561 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700562
Patrice Arruda13848222019-04-22 17:12:02 -0700563 buildFile := findBuildFile(ctx, relDir)
564 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700565 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700566 }
Patrice Arruda13848222019-04-22 17:12:02 -0700567 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
568 case BUILD_MODULES_IN_DIRECTORIES:
569 newConfigArgs, dirs := splitArgs(configArgs)
570 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700571 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700572 }
573
574 // Tidy only override all other specified targets.
575 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
576 if tidyOnly == "true" || tidyOnly == "1" {
577 configArgs = append(configArgs, "tidy_only")
578 } else {
579 configArgs = append(configArgs, targets...)
580 }
581
582 return configArgs
583}
584
585// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
586func convertToTarget(dir string, targetNamePrefix string) string {
587 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
588}
589
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700590// hasBuildFile returns true if dir contains an Android build file.
591func hasBuildFile(ctx Context, dir string) bool {
592 for _, buildFile := range buildFiles {
593 _, err := os.Stat(filepath.Join(dir, buildFile))
594 if err == nil {
595 return true
596 }
597 if !os.IsNotExist(err) {
598 ctx.Fatalf("Error retrieving the build file stats: %v", err)
599 }
600 }
601 return false
602}
603
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700604// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
605// in the current and any sub directory of dir. If a build file is not found, traverse the path
606// up by one directory and repeat again until either a build file is found or reached to the root
607// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
608// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700609func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700610 // If the string is empty or ".", assume it is top directory of the source tree.
611 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700612 return ""
613 }
614
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700615 found := false
616 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
617 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
618 if err != nil {
619 return err
620 }
621 if found {
622 return filepath.SkipDir
623 }
624 if info.IsDir() {
625 return nil
626 }
627 for _, buildFile := range buildFiles {
628 if info.Name() == buildFile {
629 found = true
630 return filepath.SkipDir
631 }
632 }
633 return nil
634 })
635 if err != nil {
636 ctx.Fatalf("Error finding Android build file: %v", err)
637 }
638
639 if found {
640 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700641 }
642 }
643
644 return ""
645}
646
647// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
648func splitArgs(args []string) (newArgs []string, dirs []string) {
649 specialArgs := map[string]bool{
650 "showcommands": true,
651 "snod": true,
652 "dist": true,
653 "checkbuild": true,
654 }
655
656 newArgs = []string{}
657 dirs = []string{}
658
659 for _, arg := range args {
660 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
661 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
662 newArgs = append(newArgs, arg)
663 continue
664 }
665
666 if _, ok := specialArgs[arg]; ok {
667 newArgs = append(newArgs, arg)
668 continue
669 }
670
671 dirs = append(dirs, arg)
672 }
673
674 return newArgs, dirs
675}
676
677// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
678// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
679// source root tree where the build action command was invoked. Each directory is validated if the
680// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700681func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700682 for _, dir := range dirs {
683 // The directory may have specified specific modules to build. ":" is the separator to separate
684 // the directory and the list of modules.
685 s := strings.Split(dir, ":")
686 l := len(s)
687 if l > 2 { // more than one ":" was specified.
688 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
689 }
690
691 dir = filepath.Join(relDir, s[0])
692 if _, err := os.Stat(dir); err != nil {
693 ctx.Fatalf("couldn't find directory %s", dir)
694 }
695
696 // Verify that if there are any targets specified after ":". Each target is separated by ",".
697 var newTargets []string
698 if l == 2 && s[1] != "" {
699 newTargets = strings.Split(s[1], ",")
700 if inList("", newTargets) {
701 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
702 }
703 }
704
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700705 // If there are specified targets to build in dir, an android build file must exist for the one
706 // shot build. For the non-targets case, find the appropriate build file and build all the
707 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700708 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700709 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700710 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
711 }
712 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700713 buildFile := findBuildFile(ctx, dir)
714 if buildFile == "" {
715 ctx.Fatalf("Build file not found for %s directory", dir)
716 }
717 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700718 }
719
Patrice Arruda13848222019-04-22 17:12:02 -0700720 targets = append(targets, newTargets...)
721 }
722
Dan Willemsence41e942019-07-29 23:39:30 -0700723 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700724}
725
Dan Willemsen9b587492017-07-10 22:13:00 -0700726func (c *configImpl) parseArgs(ctx Context, args []string) {
727 for i := 0; i < len(args); i++ {
728 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100729 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700730 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200731 } else if arg == "--empty-ninja-file" {
732 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100733 } else if arg == "--skip-ninja" {
734 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700735 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700736 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
737 // but it does run a Kati ninja file if the .kati_enabled marker file was created
738 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000739 c.skipConfig = true
740 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100741 } else if arg == "--soong-only" {
742 c.skipKati = true
743 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200744 } else if arg == "--config-only" {
745 c.skipKati = true
746 c.skipKatiNinja = true
747 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700748 } else if arg == "--skip-config" {
749 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700750 } else if arg == "--skip-soong-tests" {
751 c.skipSoongTests = true
Colin Cross106d6ef2023-10-24 10:34:56 -0700752 } else if arg == "--no-skip-soong-tests" {
753 c.skipSoongTests = false
MarkDacekd0e7cd32022-12-02 22:22:40 +0000754 } else if arg == "--skip-metrics-upload" {
755 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500756 } else if arg == "--mk-metrics" {
757 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000758 } else if arg == "--multitree-build" {
759 c.multitreeBuild = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400760 } else if arg == "--bazel-mode" {
761 c.bazelProdMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000762 } else if arg == "--bazel-mode-staging" {
763 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000764 } else if arg == "--search-api-dir" {
765 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900766 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
767 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
768 if source == "ninja_log" {
769 c.ninjaWeightListSource = NINJA_LOG
770 } else if source == "evenly_distributed" {
771 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
772 } else if source == "not_used" {
773 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900774 } else if source == "soong" {
775 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900776 } else if strings.HasPrefix(source, "file,") {
777 c.ninjaWeightListSource = EXTERNAL_FILE
778 filePath := strings.TrimPrefix(source, "file,")
779 err := validateNinjaWeightList(filePath)
780 if err != nil {
781 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
782 }
783 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
784 if err != nil {
785 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
786 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900787 } else {
788 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
789 }
Sebastian Pickl1c4188c2023-10-24 11:18:34 +0000790 } else if arg == "--build-from-text-stub" {
791 c.buildFromTextStub = true
MarkDacekb96561e2022-12-02 04:34:43 +0000792 } else if strings.HasPrefix(arg, "--build-command=") {
793 buildCmd := strings.TrimPrefix(arg, "--build-command=")
794 // remove quotations
795 buildCmd = strings.TrimPrefix(buildCmd, "\"")
796 buildCmd = strings.TrimSuffix(buildCmd, "\"")
797 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000798 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
799 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
MarkDacek6614d9c2022-12-07 21:57:38 +0000800 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
801 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
802 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
803 if err == nil {
804 c.buildStartedTime = val
805 } else {
806 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
807 }
MarkDacekf47e1422023-04-19 16:47:36 +0000808 } else if arg == "--ensure-allowlist-integrity" {
809 c.ensureAllowlistIntegrity = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700810 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700811 parseArgNum := func(def int) int {
812 if len(arg) > 2 {
813 p, err := strconv.ParseUint(arg[2:], 10, 31)
814 if err != nil {
815 ctx.Fatalf("Failed to parse %q: %v", arg, err)
816 }
817 return int(p)
818 } else if i+1 < len(args) {
819 p, err := strconv.ParseUint(args[i+1], 10, 31)
820 if err == nil {
821 i++
822 return int(p)
823 }
824 }
825 return def
826 }
827
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700828 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700829 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700830 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700831 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700832 } else {
833 ctx.Fatalln("Unknown option:", arg)
834 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700835 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700836 if k == "OUT_DIR" {
837 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
838 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700839 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700840 } else if arg == "dist" {
841 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200842 } else if arg == "json-module-graph" {
843 c.jsonModuleGraph = true
844 } else if arg == "bp2build" {
845 c.bp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200846 } else if arg == "queryview" {
847 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200848 } else if arg == "soong_docs" {
849 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700850 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700851 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800852 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700853 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700854 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700855 }
856 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700857}
858
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900859func validateNinjaWeightList(weightListFilePath string) (err error) {
860 data, err := os.ReadFile(weightListFilePath)
861 if err != nil {
862 return
863 }
864 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
865 for _, line := range lines {
866 fields := strings.Split(line, ",")
867 if len(fields) != 2 {
868 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
869 }
870 _, err = strconv.Atoi(fields[1])
871 if err != nil {
872 return
873 }
874 }
875 return
876}
877
Dan Willemsened869522018-01-08 14:58:46 -0800878func (c *configImpl) configureLocale(ctx Context) {
879 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
880 output, err := cmd.Output()
881
882 var locales []string
883 if err == nil {
884 locales = strings.Split(string(output), "\n")
885 } else {
886 // If we're unable to list the locales, let's assume en_US.UTF-8
887 locales = []string{"en_US.UTF-8"}
888 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
889 }
890
891 // gettext uses LANGUAGE, which is passed directly through
892
893 // For LANG and LC_*, only preserve the evaluated version of
894 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800895 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800896 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800897 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800898 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800899 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800900 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800901 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800902 }
903
904 c.environ.UnsetWithPrefix("LC_")
905
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800906 if userLang != "" {
907 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800908 }
909
910 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
911 // for others)
912 if inList("C.UTF-8", locales) {
913 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500914 } else if inList("C.utf8", locales) {
915 // These normalize to the same thing
916 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800917 } else if inList("en_US.UTF-8", locales) {
918 c.environ.Set("LANG", "en_US.UTF-8")
919 } else if inList("en_US.utf8", locales) {
920 // These normalize to the same thing
921 c.environ.Set("LANG", "en_US.UTF-8")
922 } else {
923 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
924 }
925}
926
Dan Willemsen1e704462016-08-21 15:17:17 -0700927func (c *configImpl) Environment() *Environment {
928 return c.environ
929}
930
931func (c *configImpl) Arguments() []string {
932 return c.arguments
933}
934
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200935func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200936 if len(c.Arguments()) > 0 {
937 // Explicit targets requested that are not special targets like b2pbuild
938 // or the JSON module graph
939 return true
940 }
941
Chris Parsons73f411b2023-06-20 21:46:57 +0000942 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200943 // Command line was empty, the default Ninja target is built
944 return true
945 }
946
Liz Kammer88677422021-12-15 15:03:19 -0500947 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
948 if c.Dist() && !c.Bp2Build() {
949 return true
950 }
951
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200952 // build.ninja doesn't need to be generated
953 return false
954}
955
Dan Willemsen1e704462016-08-21 15:17:17 -0700956func (c *configImpl) OutDir() string {
957 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700958 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700959 }
960 return "out"
961}
962
Dan Willemsen8a073a82017-02-04 17:30:44 -0800963func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400964 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000965}
966
967func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700968 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800969}
970
Dan Willemsen1e704462016-08-21 15:17:17 -0700971func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000972 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700973 return c.arguments
974 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700975 return c.ninjaArgs
976}
977
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500978func (c *configImpl) BazelOutDir() string {
979 return filepath.Join(c.OutDir(), "bazel")
980}
981
Liz Kammer2af5ea82022-11-11 14:21:03 -0500982func (c *configImpl) bazelOutputBase() string {
983 return filepath.Join(c.BazelOutDir(), "output")
984}
985
Dan Willemsen1e704462016-08-21 15:17:17 -0700986func (c *configImpl) SoongOutDir() string {
987 return filepath.Join(c.OutDir(), "soong")
988}
989
Spandan Das394aa322022-11-03 17:02:10 +0000990func (c *configImpl) ApiSurfacesOutDir() string {
991 return filepath.Join(c.OutDir(), "api_surfaces")
992}
993
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200994func (c *configImpl) PrebuiltOS() string {
995 switch runtime.GOOS {
996 case "linux":
997 return "linux-x86"
998 case "darwin":
999 return "darwin-x86"
1000 default:
1001 panic("Unknown GOOS")
1002 }
1003}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001004
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001005func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001006 if c.SkipKatiNinja() {
1007 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1008 } else {
1009 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1010 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001011}
1012
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001013func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001014 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001015}
1016
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001017func (c *configImpl) UsedEnvFile(tag string) string {
Kiyoung Kimeaa55a82023-06-05 16:56:49 +09001018 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1019 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+v+"."+tag)
1020 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001021 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1022}
1023
Lukacs T. Berkic541cd22022-10-26 07:26:50 +00001024func (c *configImpl) Bp2BuildFilesMarkerFile() string {
1025 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
1026}
1027
1028func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001029 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +02001030}
1031
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001032func (c *configImpl) SoongDocsHtml() string {
1033 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1034}
1035
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001036func (c *configImpl) QueryviewMarkerFile() string {
1037 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1038}
1039
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001040func (c *configImpl) ModuleGraphFile() string {
1041 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1042}
1043
kgui67007242022-01-25 13:50:25 +08001044func (c *configImpl) ModuleActionsFile() string {
1045 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1046}
1047
Jeff Gastonefc1b412017-03-29 17:29:06 -07001048func (c *configImpl) TempDir() string {
1049 return shared.TempDirForOutDir(c.SoongOutDir())
1050}
1051
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001052func (c *configImpl) FileListDir() string {
1053 return filepath.Join(c.OutDir(), ".module_paths")
1054}
1055
Dan Willemsen1e704462016-08-21 15:17:17 -07001056func (c *configImpl) KatiSuffix() string {
1057 if c.katiSuffix != "" {
1058 return c.katiSuffix
1059 }
1060 panic("SetKatiSuffix has not been called")
1061}
1062
Colin Cross37193492017-11-16 17:55:00 -08001063// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1064// user is interested in additional checks at the expense of build time.
1065func (c *configImpl) Checkbuild() bool {
1066 return c.checkbuild
1067}
1068
Dan Willemsen8a073a82017-02-04 17:30:44 -08001069func (c *configImpl) Dist() bool {
1070 return c.dist
1071}
1072
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001073func (c *configImpl) JsonModuleGraph() bool {
1074 return c.jsonModuleGraph
1075}
1076
1077func (c *configImpl) Bp2Build() bool {
1078 return c.bp2build
1079}
1080
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001081func (c *configImpl) Queryview() bool {
1082 return c.queryview
1083}
1084
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001085func (c *configImpl) SoongDocs() bool {
1086 return c.soongDocs
1087}
1088
Dan Willemsen1e704462016-08-21 15:17:17 -07001089func (c *configImpl) IsVerbose() bool {
1090 return c.verbose
1091}
1092
LaMont Jones52a72432023-03-09 18:19:35 +00001093func (c *configImpl) MultitreeBuild() bool {
1094 return c.multitreeBuild
1095}
1096
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001097func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1098 return c.ninjaWeightListSource
1099}
1100
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001101func (c *configImpl) SkipKati() bool {
1102 return c.skipKati
1103}
1104
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001105func (c *configImpl) SkipKatiNinja() bool {
1106 return c.skipKatiNinja
1107}
1108
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001109func (c *configImpl) SkipSoong() bool {
1110 return c.skipSoong
1111}
1112
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001113func (c *configImpl) SkipNinja() bool {
1114 return c.skipNinja
1115}
1116
Anton Hansson5a7861a2021-06-04 10:09:01 +01001117func (c *configImpl) SetSkipNinja(v bool) {
1118 c.skipNinja = v
1119}
1120
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001121func (c *configImpl) SkipConfig() bool {
1122 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001123}
1124
Jihoon Kang1bff0342023-01-17 20:40:22 +00001125func (c *configImpl) BuildFromTextStub() bool {
Sebastian Pickl1c4188c2023-10-24 11:18:34 +00001126 return c.buildFromTextStub
Jihoon Kang1bff0342023-01-17 20:40:22 +00001127}
1128
Dan Willemsen1e704462016-08-21 15:17:17 -07001129func (c *configImpl) TargetProduct() string {
1130 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1131 return v
1132 }
1133 panic("TARGET_PRODUCT is not defined")
1134}
1135
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001136func (c *configImpl) TargetProductOrErr() (string, error) {
1137 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1138 return v, nil
1139 }
1140 return "", fmt.Errorf("TARGET_PRODUCT is not defined")
1141}
1142
Dan Willemsen02781d52017-05-12 19:28:13 -07001143func (c *configImpl) TargetDevice() string {
1144 return c.targetDevice
1145}
1146
1147func (c *configImpl) SetTargetDevice(device string) {
1148 c.targetDevice = device
1149}
1150
1151func (c *configImpl) TargetBuildVariant() string {
1152 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1153 return v
1154 }
1155 panic("TARGET_BUILD_VARIANT is not defined")
1156}
1157
Dan Willemsen1e704462016-08-21 15:17:17 -07001158func (c *configImpl) KatiArgs() []string {
1159 return c.katiArgs
1160}
1161
1162func (c *configImpl) Parallel() int {
1163 return c.parallel
1164}
1165
Sam Delmerico98a73292023-02-21 11:50:29 -05001166func (c *configImpl) GetSourceRootDirs() []string {
1167 return c.sourceRootDirs
1168}
1169
1170func (c *configImpl) SetSourceRootDirs(i []string) {
1171 c.sourceRootDirs = i
1172}
1173
Spandan Dasc5763832022-11-08 18:42:16 +00001174func (c *configImpl) GetIncludeTags() []string {
1175 return c.includeTags
1176}
1177
1178func (c *configImpl) SetIncludeTags(i []string) {
1179 c.includeTags = i
1180}
1181
MarkDacek6614d9c2022-12-07 21:57:38 +00001182func (c *configImpl) GetLogsPrefix() string {
1183 return c.logsPrefix
1184}
1185
1186func (c *configImpl) SetLogsPrefix(prefix string) {
1187 c.logsPrefix = prefix
1188}
1189
Colin Cross8b8bec32019-11-15 13:18:43 -08001190func (c *configImpl) HighmemParallel() int {
1191 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1192 return i
1193 }
1194
1195 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1196 parallel := c.Parallel()
1197 if c.UseRemoteBuild() {
1198 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1199 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1200 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1201 // Return 1/16th of the size of the local pool, rounding up.
1202 return (parallel + 15) / 16
1203 } else if c.totalRAM == 0 {
1204 // Couldn't detect the total RAM, don't restrict highmem processes.
1205 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001206 } else if c.totalRAM <= 16*1024*1024*1024 {
1207 // Less than 16GB of ram, restrict to 1 highmem processes
1208 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001209 } else if c.totalRAM <= 32*1024*1024*1024 {
1210 // Less than 32GB of ram, restrict to 2 highmem processes
1211 return 2
1212 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1213 // If less than 8GB total RAM per process, reduce the number of highmem processes
1214 return p
1215 }
1216 // No restriction on highmem processes
1217 return parallel
1218}
1219
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001220func (c *configImpl) TotalRAM() uint64 {
1221 return c.totalRAM
1222}
1223
Kousik Kumarec478642020-09-21 13:39:24 -04001224// ForceUseGoma determines whether we should override Goma deprecation
1225// and use Goma for the current build or not.
1226func (c *configImpl) ForceUseGoma() bool {
1227 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1228 v = strings.TrimSpace(v)
1229 if v != "" && v != "false" {
1230 return true
1231 }
1232 }
1233 return false
1234}
1235
Dan Willemsen1e704462016-08-21 15:17:17 -07001236func (c *configImpl) UseGoma() bool {
1237 if v, ok := c.environ.Get("USE_GOMA"); ok {
1238 v = strings.TrimSpace(v)
1239 if v != "" && v != "false" {
1240 return true
1241 }
1242 }
1243 return false
1244}
1245
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001246func (c *configImpl) StartGoma() bool {
1247 if !c.UseGoma() {
1248 return false
1249 }
1250
1251 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1252 v = strings.TrimSpace(v)
1253 if v != "" && v != "false" {
1254 return false
1255 }
1256 }
1257 return true
1258}
1259
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001260func (c *configImpl) canSupportRBE() bool {
1261 // Do not use RBE with prod credentials in scenarios when stubby doesn't exist, since
1262 // its unlikely that we will be able to obtain necessary creds without stubby.
1263 authType, _ := c.rbeAuth()
1264 if !c.StubbyExists() && strings.Contains(authType, "use_google_prod_creds") {
1265 return false
1266 }
1267 return true
1268}
1269
Ramy Medhatbbf25672019-07-17 12:30:04 +00001270func (c *configImpl) UseRBE() bool {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001271 // These alternate modes of running Soong do not use RBE / reclient.
Chris Parsons73f411b2023-06-20 21:46:57 +00001272 if c.Bp2Build() || c.Queryview() || c.JsonModuleGraph() {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001273 return false
1274 }
1275
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001276 if !c.canSupportRBE() {
Kousik Kumar67ad4342023-06-06 15:09:27 -04001277 return false
1278 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001279
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001280 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001281 v = strings.TrimSpace(v)
1282 if v != "" && v != "false" {
1283 return true
1284 }
1285 }
1286 return false
1287}
1288
Chris Parsonsef615e52022-08-18 22:04:11 -04001289func (c *configImpl) BazelBuildEnabled() bool {
Chris Parsons21f80272023-06-15 04:02:28 +00001290 return c.bazelProdMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001291}
1292
Ramy Medhatbbf25672019-07-17 12:30:04 +00001293func (c *configImpl) StartRBE() bool {
1294 if !c.UseRBE() {
1295 return false
1296 }
1297
1298 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1299 v = strings.TrimSpace(v)
1300 if v != "" && v != "false" {
1301 return false
1302 }
1303 }
1304 return true
1305}
1306
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001307func (c *configImpl) rbeProxyLogsDir() string {
1308 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001309 if v, ok := c.environ.Get(f); ok {
1310 return v
1311 }
1312 }
Ramy Medhatbc061762023-10-10 18:36:59 +00001313 return c.rbeTmpDir()
1314}
1315
1316func (c *configImpl) rbeDownloadTmpDir() string {
Cole Faust06ea5312023-10-18 17:38:40 -07001317 for _, f := range []string{"RBE_download_tmp_dir", "FLAG_download_tmp_dir"} {
Ramy Medhatbc061762023-10-10 18:36:59 +00001318 if v, ok := c.environ.Get(f); ok {
1319 return v
1320 }
1321 }
1322 return c.rbeTmpDir()
1323}
1324
1325func (c *configImpl) rbeTmpDir() string {
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001326 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1327 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001328}
1329
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001330func (c *configImpl) rbeCacheDir() string {
1331 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1332 if v, ok := c.environ.Get(f); ok {
1333 return v
1334 }
1335 }
1336 return shared.JoinPath(c.SoongOutDir(), "rbe")
1337}
1338
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001339func (c *configImpl) shouldCleanupRBELogsDir() bool {
1340 // Perform a log directory cleanup only when the log directory
1341 // is auto created by the build rather than user-specified.
1342 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1343 if _, ok := c.environ.Get(f); ok {
1344 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001345 }
1346 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001347 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001348}
1349
1350func (c *configImpl) rbeExecRoot() string {
1351 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1352 if v, ok := c.environ.Get(f); ok {
1353 return v
1354 }
1355 }
1356 wd, err := os.Getwd()
1357 if err != nil {
1358 return ""
1359 }
1360 return wd
1361}
1362
1363func (c *configImpl) rbeDir() string {
1364 if v, ok := c.environ.Get("RBE_DIR"); ok {
1365 return v
1366 }
1367 return "prebuilts/remoteexecution-client/live/"
1368}
1369
1370func (c *configImpl) rbeReproxy() string {
1371 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1372 if v, ok := c.environ.Get(f); ok {
1373 return v
1374 }
1375 }
1376 return filepath.Join(c.rbeDir(), "reproxy")
1377}
1378
1379func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001380 credFlags := []string{
1381 "use_application_default_credentials",
1382 "use_gce_credentials",
1383 "credential_file",
1384 "use_google_prod_creds",
1385 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001386 for _, cf := range credFlags {
1387 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1388 if v, ok := c.environ.Get(f); ok {
1389 v = strings.TrimSpace(v)
1390 if v != "" && v != "false" && v != "0" {
1391 return "RBE_" + cf, v
1392 }
1393 }
1394 }
1395 }
1396 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001397}
1398
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001399func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1400 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1401 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1402
1403 name := filepath.Join(dir, base)
1404 if len(name) < maxNameLen {
1405 return name, nil
1406 }
1407
1408 name = filepath.Join("/tmp", base)
1409 if len(name) < maxNameLen {
1410 return name, nil
1411 }
1412
1413 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1414}
1415
Kousik Kumar7bc78192022-04-27 14:52:56 -04001416// IsGooglerEnvironment returns true if the current build is running
1417// on a Google developer machine and false otherwise.
1418func (c *configImpl) IsGooglerEnvironment() bool {
1419 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1420 if v, ok := c.environ.Get(cf); ok {
1421 return v == "googler"
1422 }
1423 return false
1424}
1425
1426// GoogleProdCredsExist determine whether credentials exist on the
1427// Googler machine to use remote execution.
1428func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001429 if googleProdCredsExistCache {
1430 return googleProdCredsExistCache
1431 }
andusyu0b3dc032023-06-21 17:29:32 -04001432 if _, err := exec.Command("/usr/bin/gcertstatus", "-nocheck_ssh").Output(); err != nil {
Kousik Kumar7bc78192022-04-27 14:52:56 -04001433 return false
1434 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001435 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001436 return true
1437}
1438
1439// UseRemoteBuild indicates whether to use a remote build acceleration system
1440// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001441func (c *configImpl) UseRemoteBuild() bool {
1442 return c.UseGoma() || c.UseRBE()
1443}
1444
Kousik Kumar7bc78192022-04-27 14:52:56 -04001445// StubbyExists checks whether the stubby binary exists on the machine running
1446// the build.
1447func (c *configImpl) StubbyExists() bool {
1448 if _, err := exec.LookPath("stubby"); err != nil {
1449 return false
1450 }
1451 return true
1452}
1453
Dan Willemsen1e704462016-08-21 15:17:17 -07001454// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001455// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001456// still limited by Parallel()
1457func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001458 if !c.UseRemoteBuild() {
1459 return 0
1460 }
1461 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1462 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001463 }
1464 return 500
1465}
1466
1467func (c *configImpl) SetKatiArgs(args []string) {
1468 c.katiArgs = args
1469}
1470
1471func (c *configImpl) SetNinjaArgs(args []string) {
1472 c.ninjaArgs = args
1473}
1474
1475func (c *configImpl) SetKatiSuffix(suffix string) {
1476 c.katiSuffix = suffix
1477}
1478
Dan Willemsene0879fc2017-08-04 15:06:27 -07001479func (c *configImpl) LastKatiSuffixFile() string {
1480 return filepath.Join(c.OutDir(), "last_kati_suffix")
1481}
1482
1483func (c *configImpl) HasKatiSuffix() bool {
1484 return c.katiSuffix != ""
1485}
1486
Dan Willemsen1e704462016-08-21 15:17:17 -07001487func (c *configImpl) KatiEnvFile() string {
1488 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1489}
1490
Dan Willemsen29971232018-09-26 14:58:30 -07001491func (c *configImpl) KatiBuildNinjaFile() string {
1492 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001493}
1494
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001495func (c *configImpl) KatiPackageNinjaFile() string {
1496 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1497}
1498
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001499func (c *configImpl) SoongVarsFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001500 targetProduct, err := c.TargetProductOrErr()
1501 if err != nil {
1502 return filepath.Join(c.SoongOutDir(), "soong.variables")
1503 } else {
1504 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+".variables")
1505 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001506}
1507
Dan Willemsen1e704462016-08-21 15:17:17 -07001508func (c *configImpl) SoongNinjaFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001509 targetProduct, err := c.TargetProductOrErr()
1510 if err != nil {
1511 return filepath.Join(c.SoongOutDir(), "build.ninja")
1512 } else {
1513 return filepath.Join(c.SoongOutDir(), "build."+targetProduct+".ninja")
1514 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001515}
1516
1517func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001518 if c.katiSuffix == "" {
1519 return filepath.Join(c.OutDir(), "combined.ninja")
1520 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001521 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1522}
1523
1524func (c *configImpl) SoongAndroidMk() string {
1525 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1526}
1527
1528func (c *configImpl) SoongMakeVarsMk() string {
1529 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1530}
1531
Colin Crossaa9a2732023-10-27 10:54:27 -07001532func (c *configImpl) SoongBuildMetrics() string {
Colin Crossb67b0612023-10-31 10:02:45 -07001533 return filepath.Join(c.LogsDir(), "soong_build_metrics.pb")
Colin Crossaa9a2732023-10-27 10:54:27 -07001534}
1535
Dan Willemsenf052f782017-05-18 15:29:04 -07001536func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001537 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001538}
1539
Dan Willemsen02781d52017-05-12 19:28:13 -07001540func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001541 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1542}
1543
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001544func (c *configImpl) KatiPackageMkDir() string {
1545 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1546}
1547
Dan Willemsenf052f782017-05-18 15:29:04 -07001548func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001549 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001550}
1551
1552func (c *configImpl) HostOut() string {
1553 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1554}
1555
1556// This probably needs to be multi-valued, so not exporting it for now
1557func (c *configImpl) hostCrossOut() string {
1558 if runtime.GOOS == "linux" {
1559 return filepath.Join(c.hostOutRoot(), "windows-x86")
1560 } else {
1561 return ""
1562 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001563}
1564
Dan Willemsen1e704462016-08-21 15:17:17 -07001565func (c *configImpl) HostPrebuiltTag() string {
1566 if runtime.GOOS == "linux" {
1567 return "linux-x86"
1568 } else if runtime.GOOS == "darwin" {
1569 return "darwin-x86"
1570 } else {
1571 panic("Unsupported OS")
1572 }
1573}
Dan Willemsenf173d592017-04-27 14:28:00 -07001574
Dan Willemsen8122bd52017-10-12 20:20:41 -07001575func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001576 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1577 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001578 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1579 if _, err := os.Stat(asan); err == nil {
1580 return asan
1581 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001582 }
1583 }
1584 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1585}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001586
1587func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1588 c.brokenDupRules = val
1589}
1590
1591func (c *configImpl) BuildBrokenDupRules() bool {
1592 return c.brokenDupRules
1593}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001594
Dan Willemsen25e6f092019-04-09 10:22:43 -07001595func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1596 c.brokenUsesNetwork = val
1597}
1598
1599func (c *configImpl) BuildBrokenUsesNetwork() bool {
1600 return c.brokenUsesNetwork
1601}
1602
Dan Willemsene3336352020-01-02 19:10:38 -08001603func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1604 c.brokenNinjaEnvVars = val
1605}
1606
1607func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1608 return c.brokenNinjaEnvVars
1609}
1610
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001611func (c *configImpl) SetTargetDeviceDir(dir string) {
1612 c.targetDeviceDir = dir
1613}
1614
1615func (c *configImpl) TargetDeviceDir() string {
1616 return c.targetDeviceDir
1617}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001618
Patrice Arruda219eef32020-06-01 17:29:30 +00001619func (c *configImpl) BuildDateTime() string {
1620 return c.buildDateTime
1621}
1622
1623func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001624 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001625}
Patrice Arruda83842d72020-12-08 19:42:08 +00001626
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001627// LogsDir returns the absolute path to the logs directory where build log and
1628// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001629// directory. If the argument dist is specified, the logs directory
1630// is <dist_dir>/logs.
1631func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001632 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001633 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001634 // 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 -05001635 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001636 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001637 absDir, err := filepath.Abs(dir)
1638 if err != nil {
1639 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1640 os.Exit(1)
1641 }
1642 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001643}
1644
1645// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1646// where the bazel profiles are located.
1647func (c *configImpl) BazelMetricsDir() string {
1648 return filepath.Join(c.LogsDir(), "bazel_metrics")
1649}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001650
Chris Parsons53f68ae2022-03-03 12:01:40 -05001651// MkFileMetrics returns the file path for make-related metrics.
1652func (c *configImpl) MkMetrics() string {
1653 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1654}
1655
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001656func (c *configImpl) SetEmptyNinjaFile(v bool) {
1657 c.emptyNinjaFile = v
1658}
1659
1660func (c *configImpl) EmptyNinjaFile() bool {
1661 return c.emptyNinjaFile
1662}
Yu Liu6e13b402021-07-27 14:29:06 -07001663
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001664func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1665 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1666}
1667
Chris Parsons9402ca82023-02-23 17:28:06 -05001668func (c *configImpl) IsPersistentBazelEnabled() bool {
1669 return c.Environment().IsEnvTrue("USE_PERSISTENT_BAZEL")
1670}
1671
Chris Parsonsc83398f2023-05-31 18:41:41 +00001672// GetBazeliskBazelVersion returns the Bazel version to use for this build,
1673// or the empty string if the current canonical prod Bazel should be used.
1674// This environment variable should only be set to debug the build system.
1675// The Bazel version, if set, will be passed to Bazelisk, and Bazelisk will
1676// handle downloading and invoking the correct Bazel binary.
1677func (c *configImpl) GetBazeliskBazelVersion() string {
1678 value, _ := c.Environment().Get("USE_BAZEL_VERSION")
1679 return value
1680}
1681
MarkDacekd06db5d2022-11-29 00:47:59 +00001682func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1683 return c.bazelForceEnabledModules
1684}
1685
MarkDacekd0e7cd32022-12-02 22:22:40 +00001686func (c *configImpl) SkipMetricsUpload() bool {
1687 return c.skipMetricsUpload
1688}
1689
MarkDacekf47e1422023-04-19 16:47:36 +00001690func (c *configImpl) EnsureAllowlistIntegrity() bool {
1691 return c.ensureAllowlistIntegrity
1692}
1693
MarkDacek6614d9c2022-12-07 21:57:38 +00001694// Returns a Time object if one was passed via a command-line flag.
1695// Otherwise returns the passed default.
1696func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1697 if c.buildStartedTime == 0 {
1698 return defaultTime
1699 }
1700 return time.UnixMilli(c.buildStartedTime)
1701}
1702
MarkDacekd33c2fd2023-05-04 20:40:04 +00001703func (c *configImpl) BazelExitCode() int32 {
1704 return c.bazelExitCode
1705}
1706
Yu Liu6e13b402021-07-27 14:29:06 -07001707func GetMetricsUploader(topDir string, env *Environment) string {
1708 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1709 metricsUploader := filepath.Join(topDir, p)
1710 if _, err := os.Stat(metricsUploader); err == nil {
1711 return metricsUploader
1712 }
1713 }
1714
1715 return ""
1716}