blob: 697cc6611b2572ff2d3857c76dfa6d093066444b [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"
Dan Willemsen1e704462016-08-21 15:17:17 -070025 "path/filepath"
26 "runtime"
27 "strconv"
28 "strings"
Kousik Kumar4c180ad2022-05-27 07:48:37 -040029 "syscall"
Nan Zhang2e6a4ff2018-02-14 13:27:26 -080030 "time"
Jeff Gastonefc1b412017-03-29 17:29:06 -070031
32 "android/soong/shared"
Kousik Kumarec478642020-09-21 13:39:24 -040033
Dan Willemsen4591b642021-05-24 14:24:12 -070034 "google.golang.org/protobuf/proto"
Patrice Arruda96850362020-08-11 20:41:11 +000035
36 smpb "android/soong/ui/metrics/metrics_proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070037)
38
Kousik Kumar3ff037e2022-01-25 22:11:01 -050039const (
Chris Parsons53f68ae2022-03-03 12:01:40 -050040 envConfigDir = "vendor/google/tools/soong_config"
41 jsonSuffix = "json"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050042)
43
Kousik Kumar4c180ad2022-05-27 07:48:37 -040044var (
Kevin Dagostino096ab2f2023-03-03 19:47:17 +000045 rbeRandPrefix int
46 googleProdCredsExistCache bool
Kousik Kumar4c180ad2022-05-27 07:48:37 -040047)
48
49func init() {
50 rand.Seed(time.Now().UnixNano())
51 rbeRandPrefix = rand.Intn(1000)
52}
53
Dan Willemsen1e704462016-08-21 15:17:17 -070054type Config struct{ *configImpl }
55
56type configImpl struct {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020057 // Some targets that are implemented in soong_build
58 // (bp2build, json-module-graph) are not here and have their own bits below.
Colin Cross28f527c2019-11-26 16:19:04 -080059 arguments []string
60 goma bool
61 environ *Environment
62 distDir string
63 buildDateTime string
MarkDacek6614d9c2022-12-07 21:57:38 +000064 logsPrefix string
Dan Willemsen1e704462016-08-21 15:17:17 -070065
66 // From the arguments
MarkDacekf47e1422023-04-19 16:47:36 +000067 parallel int
68 keepGoing int
69 verbose bool
70 checkbuild bool
71 dist bool
72 jsonModuleGraph bool
73 apiBp2build bool // Generate BUILD files for Soong modules that contribute APIs
74 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
88 buildFromTextStub bool
MarkDacekd33c2fd2023-05-04 20:40:04 +000089 ensureAllowlistIntegrity bool // For CI builds - make sure modules are mixed-built
90 bazelExitCode int32 // For b-runs - necessary for updating NonZeroExit
Dan Willemsen1e704462016-08-21 15:17:17 -070091
92 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070093 katiArgs []string
94 ninjaArgs []string
95 katiSuffix string
96 targetDevice string
97 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +000098 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -070099
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800100 // Autodetected
101 totalRAM uint64
102
Dan Willemsene3336352020-01-02 19:10:38 -0800103 brokenDupRules bool
104 brokenUsesNetwork bool
105 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -0700106
107 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000108
MarkDacekb78465d2022-10-18 20:10:16 +0000109 bazelProdMode bool
110 bazelDevMode bool
111 bazelStagingMode bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000112
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700113 // Set by multiproduct_kati
114 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700115
116 metricsUploader string
MarkDacekd06db5d2022-11-29 00:47:59 +0000117
118 bazelForceEnabledModules string
Spandan Dasc5763832022-11-08 18:42:16 +0000119
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 Kumar3ff037e2022-01-25 22:11:01 -0500289 }
290
Dan Willemsen2d31a442018-10-20 21:33:41 -0700291 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
292 ret.distDir = filepath.Clean(distDir)
293 } else {
294 ret.distDir = filepath.Join(ret.OutDir(), "dist")
295 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700296
Spandan Das05063612021-06-25 01:39:04 +0000297 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
298 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
299 }
300
Dan Willemsen1e704462016-08-21 15:17:17 -0700301 ret.environ.Unset(
302 // We're already using it
303 "USE_SOONG_UI",
304
305 // We should never use GOROOT/GOPATH from the shell environment
306 "GOROOT",
307 "GOPATH",
308
309 // These should only come from Soong, not the environment.
310 "CLANG",
311 "CLANG_CXX",
312 "CCC_CC",
313 "CCC_CXX",
314
315 // Used by the goma compiler wrapper, but should only be set by
316 // gomacc
317 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800318
319 // We handle this above
320 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700321
Dan Willemsen2d31a442018-10-20 21:33:41 -0700322 // This is handled above too, and set for individual commands later
323 "DIST_DIR",
324
Dan Willemsen68a09852017-04-18 13:56:57 -0700325 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000326 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700327 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700328 "DISPLAY",
329 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000330 "JAVAC",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700331 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700332 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700333
334 // Drop make flags
335 "MAKEFLAGS",
336 "MAKELEVEL",
337 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700338
339 // Set in envsetup.sh, reset in makefiles
340 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700341
342 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
343 "ANDROID_BUILD_TOP",
344 "ANDROID_HOST_OUT",
345 "ANDROID_PRODUCT_OUT",
346 "ANDROID_HOST_OUT_TESTCASES",
347 "ANDROID_TARGET_OUT_TESTCASES",
348 "ANDROID_TOOLCHAIN",
349 "ANDROID_TOOLCHAIN_2ND_ARCH",
350 "ANDROID_DEV_SCRIPTS",
351 "ANDROID_EMULATOR_PREBUILTS",
352 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700353 )
354
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400355 if ret.UseGoma() || ret.ForceUseGoma() {
356 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
357 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400358 }
359
Dan Willemsen1e704462016-08-21 15:17:17 -0700360 // Tell python not to spam the source tree with .pyc files.
361 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
362
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400363 tmpDir := absPath(ctx, ret.TempDir())
364 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800365
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700366 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
367 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
368 "llvm-binutils-stable/llvm-symbolizer")
369 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
370
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800371 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700372 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800373
Yu Liu6e13b402021-07-27 14:29:06 -0700374 srcDir := absPath(ctx, ".")
375 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700376 ctx.Println("You are building in a directory whose absolute path contains a space character:")
377 ctx.Println()
378 ctx.Printf("%q\n", srcDir)
379 ctx.Println()
380 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700381 }
382
Yu Liu6e13b402021-07-27 14:29:06 -0700383 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
384
Dan Willemsendb8457c2017-05-12 16:38:17 -0700385 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700386 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
387 ctx.Println()
388 ctx.Printf("%q\n", outDir)
389 ctx.Println()
390 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700391 }
392
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000393 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700394 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
395 ctx.Println()
396 ctx.Printf("%q\n", distDir)
397 ctx.Println()
398 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700399 }
400
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700401 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000402 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
403 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100404 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800405 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700406 javaHome := func() string {
407 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
408 return override
409 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000410 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
411 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 +0100412 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000413 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
414 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
415 }
416 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700417 }()
418 absJavaHome := absPath(ctx, javaHome)
419
Dan Willemsened869522018-01-08 14:58:46 -0800420 ret.configureLocale(ctx)
421
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700422 newPath := []string{filepath.Join(absJavaHome, "bin")}
423 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
424 newPath = append(newPath, path)
425 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100426
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700427 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
428 ret.environ.Set("JAVA_HOME", absJavaHome)
429 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000430 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
431 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100432 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700433 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
434
LaMont Jones52a72432023-03-09 18:19:35 +0000435 if ret.MultitreeBuild() {
436 ret.environ.Set("MULTITREE_BUILD", "true")
437 }
438
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800439 outDir := ret.OutDir()
440 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800441 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800442 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800443 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800444 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800445 }
Colin Cross28f527c2019-11-26 16:19:04 -0800446
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800447 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
448
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400449 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400450 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400451 ret.environ.Set(k, v)
452 }
453 }
454
Jihoon Kang1bff0342023-01-17 20:40:22 +0000455 if ret.BuildFromTextStub() {
456 // TODO(b/271443071): support hidden api check for from-text stub build
457 ret.environ.Set("UNSAFE_DISABLE_HIDDENAPI_FLAGS", "true")
458 }
459
Patrice Arruda83842d72020-12-08 19:42:08 +0000460 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800461 if err := os.RemoveAll(bpd); err != nil {
462 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
463 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000464
Patrice Arruda96850362020-08-11 20:41:11 +0000465 c := Config{ret}
466 storeConfigMetrics(ctx, c)
467 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700468}
469
Patrice Arruda13848222019-04-22 17:12:02 -0700470// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
471// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700472func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
473 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700474}
475
Patrice Arruda96850362020-08-11 20:41:11 +0000476// storeConfigMetrics selects a set of configuration information and store in
477// the metrics system for further analysis.
478func storeConfigMetrics(ctx Context, config Config) {
479 if ctx.Metrics == nil {
480 return
481 }
482
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400483 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000484
485 s := &smpb.SystemResourceInfo{
486 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
487 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
488 }
489 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000490}
491
Jeongik Cha8d63d562023-03-17 03:52:13 +0900492func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900493 switch s {
494 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900495 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900496 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900497 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900498 case EXTERNAL_FILE:
499 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900500 case HINT_FROM_SOONG:
501 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900502 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900503 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900504 }
505}
506
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400507func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700508 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400509 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
510 UseGoma: proto.Bool(config.UseGoma()),
511 UseRbe: proto.Bool(config.UseRBE()),
512 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
513 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900514 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400515 }
Yu Liue737a992021-10-04 13:21:41 -0700516 c.Targets = append(c.Targets, config.arguments...)
517
518 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400519}
520
Patrice Arruda13848222019-04-22 17:12:02 -0700521// getConfigArgs processes the command arguments based on the build action and creates a set of new
522// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700523func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700524 // The next block of code verifies that the current directory is the root directory of the source
525 // tree. It then finds the relative path of dir based on the root directory of the source tree
526 // and verify that dir is inside of the source tree.
527 checkTopDir(ctx)
528 topDir, err := os.Getwd()
529 if err != nil {
530 ctx.Fatalf("Error retrieving top directory: %v", err)
531 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700532 dir, err = filepath.EvalSymlinks(dir)
533 if err != nil {
534 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
535 }
Patrice Arruda13848222019-04-22 17:12:02 -0700536 dir, err = filepath.Abs(dir)
537 if err != nil {
538 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
539 }
540 relDir, err := filepath.Rel(topDir, dir)
541 if err != nil {
542 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
543 }
544 // If there are ".." in the path, it's not in the source tree.
545 if strings.Contains(relDir, "..") {
546 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
547 }
548
549 configArgs := args[:]
550
551 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
552 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
553 targetNamePrefix := "MODULES-IN-"
554 if inList("GET-INSTALL-PATH", configArgs) {
555 targetNamePrefix = "GET-INSTALL-PATH-IN-"
556 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
557 }
558
Patrice Arruda13848222019-04-22 17:12:02 -0700559 var targets []string
560
561 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700562 case BUILD_MODULES:
563 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700564 case BUILD_MODULES_IN_A_DIRECTORY:
565 // If dir is the root source tree, all the modules are built of the source tree are built so
566 // no need to find the build file.
567 if topDir == dir {
568 break
569 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700570
Patrice Arruda13848222019-04-22 17:12:02 -0700571 buildFile := findBuildFile(ctx, relDir)
572 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700573 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700574 }
Patrice Arruda13848222019-04-22 17:12:02 -0700575 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
576 case BUILD_MODULES_IN_DIRECTORIES:
577 newConfigArgs, dirs := splitArgs(configArgs)
578 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700579 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700580 }
581
582 // Tidy only override all other specified targets.
583 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
584 if tidyOnly == "true" || tidyOnly == "1" {
585 configArgs = append(configArgs, "tidy_only")
586 } else {
587 configArgs = append(configArgs, targets...)
588 }
589
590 return configArgs
591}
592
593// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
594func convertToTarget(dir string, targetNamePrefix string) string {
595 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
596}
597
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700598// hasBuildFile returns true if dir contains an Android build file.
599func hasBuildFile(ctx Context, dir string) bool {
600 for _, buildFile := range buildFiles {
601 _, err := os.Stat(filepath.Join(dir, buildFile))
602 if err == nil {
603 return true
604 }
605 if !os.IsNotExist(err) {
606 ctx.Fatalf("Error retrieving the build file stats: %v", err)
607 }
608 }
609 return false
610}
611
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700612// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
613// in the current and any sub directory of dir. If a build file is not found, traverse the path
614// up by one directory and repeat again until either a build file is found or reached to the root
615// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
616// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700617func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700618 // If the string is empty or ".", assume it is top directory of the source tree.
619 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700620 return ""
621 }
622
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700623 found := false
624 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
625 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
626 if err != nil {
627 return err
628 }
629 if found {
630 return filepath.SkipDir
631 }
632 if info.IsDir() {
633 return nil
634 }
635 for _, buildFile := range buildFiles {
636 if info.Name() == buildFile {
637 found = true
638 return filepath.SkipDir
639 }
640 }
641 return nil
642 })
643 if err != nil {
644 ctx.Fatalf("Error finding Android build file: %v", err)
645 }
646
647 if found {
648 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700649 }
650 }
651
652 return ""
653}
654
655// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
656func splitArgs(args []string) (newArgs []string, dirs []string) {
657 specialArgs := map[string]bool{
658 "showcommands": true,
659 "snod": true,
660 "dist": true,
661 "checkbuild": true,
662 }
663
664 newArgs = []string{}
665 dirs = []string{}
666
667 for _, arg := range args {
668 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
669 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
670 newArgs = append(newArgs, arg)
671 continue
672 }
673
674 if _, ok := specialArgs[arg]; ok {
675 newArgs = append(newArgs, arg)
676 continue
677 }
678
679 dirs = append(dirs, arg)
680 }
681
682 return newArgs, dirs
683}
684
685// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
686// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
687// source root tree where the build action command was invoked. Each directory is validated if the
688// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700689func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700690 for _, dir := range dirs {
691 // The directory may have specified specific modules to build. ":" is the separator to separate
692 // the directory and the list of modules.
693 s := strings.Split(dir, ":")
694 l := len(s)
695 if l > 2 { // more than one ":" was specified.
696 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
697 }
698
699 dir = filepath.Join(relDir, s[0])
700 if _, err := os.Stat(dir); err != nil {
701 ctx.Fatalf("couldn't find directory %s", dir)
702 }
703
704 // Verify that if there are any targets specified after ":". Each target is separated by ",".
705 var newTargets []string
706 if l == 2 && s[1] != "" {
707 newTargets = strings.Split(s[1], ",")
708 if inList("", newTargets) {
709 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
710 }
711 }
712
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700713 // If there are specified targets to build in dir, an android build file must exist for the one
714 // shot build. For the non-targets case, find the appropriate build file and build all the
715 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700716 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700717 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700718 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
719 }
720 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700721 buildFile := findBuildFile(ctx, dir)
722 if buildFile == "" {
723 ctx.Fatalf("Build file not found for %s directory", dir)
724 }
725 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700726 }
727
Patrice Arruda13848222019-04-22 17:12:02 -0700728 targets = append(targets, newTargets...)
729 }
730
Dan Willemsence41e942019-07-29 23:39:30 -0700731 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700732}
733
Dan Willemsen9b587492017-07-10 22:13:00 -0700734func (c *configImpl) parseArgs(ctx Context, args []string) {
735 for i := 0; i < len(args); i++ {
736 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100737 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700738 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200739 } else if arg == "--empty-ninja-file" {
740 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100741 } else if arg == "--skip-ninja" {
742 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700743 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700744 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
745 // but it does run a Kati ninja file if the .kati_enabled marker file was created
746 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000747 c.skipConfig = true
748 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100749 } else if arg == "--soong-only" {
750 c.skipKati = true
751 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200752 } else if arg == "--config-only" {
753 c.skipKati = true
754 c.skipKatiNinja = true
755 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700756 } else if arg == "--skip-config" {
757 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700758 } else if arg == "--skip-soong-tests" {
759 c.skipSoongTests = true
MarkDacekd0e7cd32022-12-02 22:22:40 +0000760 } else if arg == "--skip-metrics-upload" {
761 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500762 } else if arg == "--mk-metrics" {
763 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000764 } else if arg == "--multitree-build" {
765 c.multitreeBuild = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400766 } else if arg == "--bazel-mode" {
767 c.bazelProdMode = true
768 } else if arg == "--bazel-mode-dev" {
769 c.bazelDevMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000770 } else if arg == "--bazel-mode-staging" {
771 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000772 } else if arg == "--search-api-dir" {
773 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900774 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
775 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
776 if source == "ninja_log" {
777 c.ninjaWeightListSource = NINJA_LOG
778 } else if source == "evenly_distributed" {
779 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
780 } else if source == "not_used" {
781 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900782 } else if source == "soong" {
783 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900784 } else if strings.HasPrefix(source, "file,") {
785 c.ninjaWeightListSource = EXTERNAL_FILE
786 filePath := strings.TrimPrefix(source, "file,")
787 err := validateNinjaWeightList(filePath)
788 if err != nil {
789 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
790 }
791 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
792 if err != nil {
793 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
794 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900795 } else {
796 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
797 }
Jihoon Kang1bff0342023-01-17 20:40:22 +0000798 } else if arg == "--build-from-text-stub" {
799 c.buildFromTextStub = true
MarkDacekb96561e2022-12-02 04:34:43 +0000800 } else if strings.HasPrefix(arg, "--build-command=") {
801 buildCmd := strings.TrimPrefix(arg, "--build-command=")
802 // remove quotations
803 buildCmd = strings.TrimPrefix(buildCmd, "\"")
804 buildCmd = strings.TrimSuffix(buildCmd, "\"")
805 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000806 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
807 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
MarkDacek6614d9c2022-12-07 21:57:38 +0000808 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
809 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
810 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
811 if err == nil {
812 c.buildStartedTime = val
813 } else {
814 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
815 }
MarkDacekf47e1422023-04-19 16:47:36 +0000816 } else if arg == "--ensure-allowlist-integrity" {
817 c.ensureAllowlistIntegrity = true
MarkDacekd33c2fd2023-05-04 20:40:04 +0000818 } else if strings.HasPrefix(arg, "--bazel-exit-code=") {
819 bazelExitCodeStr := strings.TrimPrefix(arg, "--bazel-exit-code=")
820 val, err := strconv.Atoi(bazelExitCodeStr)
821 if err == nil {
822 c.bazelExitCode = int32(val)
823 } else {
824 ctx.Fatalf("Error parsing bazel-exit-code", err)
825 }
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700826 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700827 parseArgNum := func(def int) int {
828 if len(arg) > 2 {
829 p, err := strconv.ParseUint(arg[2:], 10, 31)
830 if err != nil {
831 ctx.Fatalf("Failed to parse %q: %v", arg, err)
832 }
833 return int(p)
834 } else if i+1 < len(args) {
835 p, err := strconv.ParseUint(args[i+1], 10, 31)
836 if err == nil {
837 i++
838 return int(p)
839 }
840 }
841 return def
842 }
843
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700844 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700845 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700846 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700847 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700848 } else {
849 ctx.Fatalln("Unknown option:", arg)
850 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700851 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700852 if k == "OUT_DIR" {
853 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
854 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700855 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700856 } else if arg == "dist" {
857 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200858 } else if arg == "json-module-graph" {
859 c.jsonModuleGraph = true
860 } else if arg == "bp2build" {
861 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000862 } else if arg == "api_bp2build" {
863 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200864 } else if arg == "queryview" {
865 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200866 } else if arg == "soong_docs" {
867 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700868 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700869 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800870 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700871 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700872 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700873 }
874 }
Chris Parsonsb6e96902022-10-31 20:08:45 -0400875 if (!c.bazelProdMode) && (!c.bazelDevMode) && (!c.bazelStagingMode) {
876 c.bazelProdMode = defaultBazelProdMode(c)
877 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700878}
879
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900880func validateNinjaWeightList(weightListFilePath string) (err error) {
881 data, err := os.ReadFile(weightListFilePath)
882 if err != nil {
883 return
884 }
885 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
886 for _, line := range lines {
887 fields := strings.Split(line, ",")
888 if len(fields) != 2 {
889 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
890 }
891 _, err = strconv.Atoi(fields[1])
892 if err != nil {
893 return
894 }
895 }
896 return
897}
898
Dan Willemsened869522018-01-08 14:58:46 -0800899func (c *configImpl) configureLocale(ctx Context) {
900 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
901 output, err := cmd.Output()
902
903 var locales []string
904 if err == nil {
905 locales = strings.Split(string(output), "\n")
906 } else {
907 // If we're unable to list the locales, let's assume en_US.UTF-8
908 locales = []string{"en_US.UTF-8"}
909 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
910 }
911
912 // gettext uses LANGUAGE, which is passed directly through
913
914 // For LANG and LC_*, only preserve the evaluated version of
915 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800916 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800917 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800918 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800919 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800920 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800921 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800922 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800923 }
924
925 c.environ.UnsetWithPrefix("LC_")
926
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800927 if userLang != "" {
928 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800929 }
930
931 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
932 // for others)
933 if inList("C.UTF-8", locales) {
934 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500935 } else if inList("C.utf8", locales) {
936 // These normalize to the same thing
937 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800938 } else if inList("en_US.UTF-8", locales) {
939 c.environ.Set("LANG", "en_US.UTF-8")
940 } else if inList("en_US.utf8", locales) {
941 // These normalize to the same thing
942 c.environ.Set("LANG", "en_US.UTF-8")
943 } else {
944 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
945 }
946}
947
Dan Willemsen1e704462016-08-21 15:17:17 -0700948func (c *configImpl) Environment() *Environment {
949 return c.environ
950}
951
952func (c *configImpl) Arguments() []string {
953 return c.arguments
954}
955
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200956func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200957 if len(c.Arguments()) > 0 {
958 // Explicit targets requested that are not special targets like b2pbuild
959 // or the JSON module graph
960 return true
961 }
962
Spandan Das5af0bd32022-09-28 20:43:08 +0000963 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200964 // Command line was empty, the default Ninja target is built
965 return true
966 }
967
Liz Kammer88677422021-12-15 15:03:19 -0500968 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
969 if c.Dist() && !c.Bp2Build() {
970 return true
971 }
972
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200973 // build.ninja doesn't need to be generated
974 return false
975}
976
Dan Willemsen1e704462016-08-21 15:17:17 -0700977func (c *configImpl) OutDir() string {
978 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700979 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700980 }
981 return "out"
982}
983
Dan Willemsen8a073a82017-02-04 17:30:44 -0800984func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400985 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000986}
987
988func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700989 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800990}
991
Dan Willemsen1e704462016-08-21 15:17:17 -0700992func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000993 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700994 return c.arguments
995 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700996 return c.ninjaArgs
997}
998
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500999func (c *configImpl) BazelOutDir() string {
1000 return filepath.Join(c.OutDir(), "bazel")
1001}
1002
Liz Kammer2af5ea82022-11-11 14:21:03 -05001003func (c *configImpl) bazelOutputBase() string {
1004 return filepath.Join(c.BazelOutDir(), "output")
1005}
1006
Dan Willemsen1e704462016-08-21 15:17:17 -07001007func (c *configImpl) SoongOutDir() string {
1008 return filepath.Join(c.OutDir(), "soong")
1009}
1010
Spandan Das394aa322022-11-03 17:02:10 +00001011func (c *configImpl) ApiSurfacesOutDir() string {
1012 return filepath.Join(c.OutDir(), "api_surfaces")
1013}
1014
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001015func (c *configImpl) PrebuiltOS() string {
1016 switch runtime.GOOS {
1017 case "linux":
1018 return "linux-x86"
1019 case "darwin":
1020 return "darwin-x86"
1021 default:
1022 panic("Unknown GOOS")
1023 }
1024}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001025
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001026func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001027 if c.SkipKatiNinja() {
1028 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1029 } else {
1030 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1031 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001032}
1033
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001034func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001035 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001036}
1037
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001038func (c *configImpl) UsedEnvFile(tag string) string {
1039 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1040}
1041
Lukacs T. Berkic541cd22022-10-26 07:26:50 +00001042func (c *configImpl) Bp2BuildFilesMarkerFile() string {
1043 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
1044}
1045
1046func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001047 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +02001048}
1049
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001050func (c *configImpl) SoongDocsHtml() string {
1051 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1052}
1053
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001054func (c *configImpl) QueryviewMarkerFile() string {
1055 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1056}
1057
Spandan Das5af0bd32022-09-28 20:43:08 +00001058func (c *configImpl) ApiBp2buildMarkerFile() string {
1059 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
1060}
1061
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001062func (c *configImpl) ModuleGraphFile() string {
1063 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1064}
1065
kgui67007242022-01-25 13:50:25 +08001066func (c *configImpl) ModuleActionsFile() string {
1067 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1068}
1069
Jeff Gastonefc1b412017-03-29 17:29:06 -07001070func (c *configImpl) TempDir() string {
1071 return shared.TempDirForOutDir(c.SoongOutDir())
1072}
1073
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001074func (c *configImpl) FileListDir() string {
1075 return filepath.Join(c.OutDir(), ".module_paths")
1076}
1077
Dan Willemsen1e704462016-08-21 15:17:17 -07001078func (c *configImpl) KatiSuffix() string {
1079 if c.katiSuffix != "" {
1080 return c.katiSuffix
1081 }
1082 panic("SetKatiSuffix has not been called")
1083}
1084
Colin Cross37193492017-11-16 17:55:00 -08001085// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1086// user is interested in additional checks at the expense of build time.
1087func (c *configImpl) Checkbuild() bool {
1088 return c.checkbuild
1089}
1090
Dan Willemsen8a073a82017-02-04 17:30:44 -08001091func (c *configImpl) Dist() bool {
1092 return c.dist
1093}
1094
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001095func (c *configImpl) JsonModuleGraph() bool {
1096 return c.jsonModuleGraph
1097}
1098
1099func (c *configImpl) Bp2Build() bool {
1100 return c.bp2build
1101}
1102
Spandan Das5af0bd32022-09-28 20:43:08 +00001103func (c *configImpl) ApiBp2build() bool {
1104 return c.apiBp2build
1105}
1106
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001107func (c *configImpl) Queryview() bool {
1108 return c.queryview
1109}
1110
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001111func (c *configImpl) SoongDocs() bool {
1112 return c.soongDocs
1113}
1114
Dan Willemsen1e704462016-08-21 15:17:17 -07001115func (c *configImpl) IsVerbose() bool {
1116 return c.verbose
1117}
1118
LaMont Jones52a72432023-03-09 18:19:35 +00001119func (c *configImpl) MultitreeBuild() bool {
1120 return c.multitreeBuild
1121}
1122
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001123func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1124 return c.ninjaWeightListSource
1125}
1126
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001127func (c *configImpl) SkipKati() bool {
1128 return c.skipKati
1129}
1130
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001131func (c *configImpl) SkipKatiNinja() bool {
1132 return c.skipKatiNinja
1133}
1134
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001135func (c *configImpl) SkipSoong() bool {
1136 return c.skipSoong
1137}
1138
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001139func (c *configImpl) SkipNinja() bool {
1140 return c.skipNinja
1141}
1142
Anton Hansson5a7861a2021-06-04 10:09:01 +01001143func (c *configImpl) SetSkipNinja(v bool) {
1144 c.skipNinja = v
1145}
1146
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001147func (c *configImpl) SkipConfig() bool {
1148 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001149}
1150
Jihoon Kang1bff0342023-01-17 20:40:22 +00001151func (c *configImpl) BuildFromTextStub() bool {
1152 return c.buildFromTextStub
1153}
1154
Dan Willemsen1e704462016-08-21 15:17:17 -07001155func (c *configImpl) TargetProduct() string {
1156 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1157 return v
1158 }
1159 panic("TARGET_PRODUCT is not defined")
1160}
1161
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001162func (c *configImpl) TargetProductOrErr() (string, error) {
1163 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1164 return v, nil
1165 }
1166 return "", fmt.Errorf("TARGET_PRODUCT is not defined")
1167}
1168
Dan Willemsen02781d52017-05-12 19:28:13 -07001169func (c *configImpl) TargetDevice() string {
1170 return c.targetDevice
1171}
1172
1173func (c *configImpl) SetTargetDevice(device string) {
1174 c.targetDevice = device
1175}
1176
1177func (c *configImpl) TargetBuildVariant() string {
1178 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1179 return v
1180 }
1181 panic("TARGET_BUILD_VARIANT is not defined")
1182}
1183
Dan Willemsen1e704462016-08-21 15:17:17 -07001184func (c *configImpl) KatiArgs() []string {
1185 return c.katiArgs
1186}
1187
1188func (c *configImpl) Parallel() int {
1189 return c.parallel
1190}
1191
Sam Delmerico98a73292023-02-21 11:50:29 -05001192func (c *configImpl) GetSourceRootDirs() []string {
1193 return c.sourceRootDirs
1194}
1195
1196func (c *configImpl) SetSourceRootDirs(i []string) {
1197 c.sourceRootDirs = i
1198}
1199
Spandan Dasc5763832022-11-08 18:42:16 +00001200func (c *configImpl) GetIncludeTags() []string {
1201 return c.includeTags
1202}
1203
1204func (c *configImpl) SetIncludeTags(i []string) {
1205 c.includeTags = i
1206}
1207
MarkDacek6614d9c2022-12-07 21:57:38 +00001208func (c *configImpl) GetLogsPrefix() string {
1209 return c.logsPrefix
1210}
1211
1212func (c *configImpl) SetLogsPrefix(prefix string) {
1213 c.logsPrefix = prefix
1214}
1215
Colin Cross8b8bec32019-11-15 13:18:43 -08001216func (c *configImpl) HighmemParallel() int {
1217 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1218 return i
1219 }
1220
1221 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1222 parallel := c.Parallel()
1223 if c.UseRemoteBuild() {
1224 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1225 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1226 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1227 // Return 1/16th of the size of the local pool, rounding up.
1228 return (parallel + 15) / 16
1229 } else if c.totalRAM == 0 {
1230 // Couldn't detect the total RAM, don't restrict highmem processes.
1231 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001232 } else if c.totalRAM <= 16*1024*1024*1024 {
1233 // Less than 16GB of ram, restrict to 1 highmem processes
1234 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001235 } else if c.totalRAM <= 32*1024*1024*1024 {
1236 // Less than 32GB of ram, restrict to 2 highmem processes
1237 return 2
1238 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1239 // If less than 8GB total RAM per process, reduce the number of highmem processes
1240 return p
1241 }
1242 // No restriction on highmem processes
1243 return parallel
1244}
1245
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001246func (c *configImpl) TotalRAM() uint64 {
1247 return c.totalRAM
1248}
1249
Kousik Kumarec478642020-09-21 13:39:24 -04001250// ForceUseGoma determines whether we should override Goma deprecation
1251// and use Goma for the current build or not.
1252func (c *configImpl) ForceUseGoma() bool {
1253 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1254 v = strings.TrimSpace(v)
1255 if v != "" && v != "false" {
1256 return true
1257 }
1258 }
1259 return false
1260}
1261
Dan Willemsen1e704462016-08-21 15:17:17 -07001262func (c *configImpl) UseGoma() bool {
1263 if v, ok := c.environ.Get("USE_GOMA"); ok {
1264 v = strings.TrimSpace(v)
1265 if v != "" && v != "false" {
1266 return true
1267 }
1268 }
1269 return false
1270}
1271
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001272func (c *configImpl) StartGoma() bool {
1273 if !c.UseGoma() {
1274 return false
1275 }
1276
1277 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1278 v = strings.TrimSpace(v)
1279 if v != "" && v != "false" {
1280 return false
1281 }
1282 }
1283 return true
1284}
1285
Ramy Medhatbbf25672019-07-17 12:30:04 +00001286func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001287 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001288 v = strings.TrimSpace(v)
1289 if v != "" && v != "false" {
1290 return true
1291 }
1292 }
1293 return false
1294}
1295
Chris Parsonsef615e52022-08-18 22:04:11 -04001296func (c *configImpl) BazelBuildEnabled() bool {
MarkDacekb78465d2022-10-18 20:10:16 +00001297 return c.bazelProdMode || c.bazelDevMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001298}
1299
Ramy Medhatbbf25672019-07-17 12:30:04 +00001300func (c *configImpl) StartRBE() bool {
1301 if !c.UseRBE() {
1302 return false
1303 }
1304
1305 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1306 v = strings.TrimSpace(v)
1307 if v != "" && v != "false" {
1308 return false
1309 }
1310 }
1311 return true
1312}
1313
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001314func (c *configImpl) rbeProxyLogsDir() string {
1315 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001316 if v, ok := c.environ.Get(f); ok {
1317 return v
1318 }
1319 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001320 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1321 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001322}
1323
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001324func (c *configImpl) rbeCacheDir() string {
1325 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1326 if v, ok := c.environ.Get(f); ok {
1327 return v
1328 }
1329 }
1330 return shared.JoinPath(c.SoongOutDir(), "rbe")
1331}
1332
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001333func (c *configImpl) shouldCleanupRBELogsDir() bool {
1334 // Perform a log directory cleanup only when the log directory
1335 // is auto created by the build rather than user-specified.
1336 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1337 if _, ok := c.environ.Get(f); ok {
1338 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001339 }
1340 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001341 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001342}
1343
1344func (c *configImpl) rbeExecRoot() string {
1345 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1346 if v, ok := c.environ.Get(f); ok {
1347 return v
1348 }
1349 }
1350 wd, err := os.Getwd()
1351 if err != nil {
1352 return ""
1353 }
1354 return wd
1355}
1356
1357func (c *configImpl) rbeDir() string {
1358 if v, ok := c.environ.Get("RBE_DIR"); ok {
1359 return v
1360 }
1361 return "prebuilts/remoteexecution-client/live/"
1362}
1363
1364func (c *configImpl) rbeReproxy() string {
1365 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1366 if v, ok := c.environ.Get(f); ok {
1367 return v
1368 }
1369 }
1370 return filepath.Join(c.rbeDir(), "reproxy")
1371}
1372
1373func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001374 credFlags := []string{
1375 "use_application_default_credentials",
1376 "use_gce_credentials",
1377 "credential_file",
1378 "use_google_prod_creds",
1379 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001380 for _, cf := range credFlags {
1381 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1382 if v, ok := c.environ.Get(f); ok {
1383 v = strings.TrimSpace(v)
1384 if v != "" && v != "false" && v != "0" {
1385 return "RBE_" + cf, v
1386 }
1387 }
1388 }
1389 }
1390 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001391}
1392
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001393func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1394 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1395 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1396
1397 name := filepath.Join(dir, base)
1398 if len(name) < maxNameLen {
1399 return name, nil
1400 }
1401
1402 name = filepath.Join("/tmp", base)
1403 if len(name) < maxNameLen {
1404 return name, nil
1405 }
1406
1407 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1408}
1409
Kousik Kumar7bc78192022-04-27 14:52:56 -04001410// IsGooglerEnvironment returns true if the current build is running
1411// on a Google developer machine and false otherwise.
1412func (c *configImpl) IsGooglerEnvironment() bool {
1413 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1414 if v, ok := c.environ.Get(cf); ok {
1415 return v == "googler"
1416 }
1417 return false
1418}
1419
1420// GoogleProdCredsExist determine whether credentials exist on the
1421// Googler machine to use remote execution.
1422func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001423 if googleProdCredsExistCache {
1424 return googleProdCredsExistCache
1425 }
Saagar Jhaf513b232023-05-26 00:17:55 +00001426 if _, err := exec.Command("/usr/bin/gcertstatus").Output(); err != nil {
Kousik Kumar7bc78192022-04-27 14:52:56 -04001427 return false
1428 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001429 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001430 return true
1431}
1432
1433// UseRemoteBuild indicates whether to use a remote build acceleration system
1434// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001435func (c *configImpl) UseRemoteBuild() bool {
1436 return c.UseGoma() || c.UseRBE()
1437}
1438
Kousik Kumar7bc78192022-04-27 14:52:56 -04001439// StubbyExists checks whether the stubby binary exists on the machine running
1440// the build.
1441func (c *configImpl) StubbyExists() bool {
1442 if _, err := exec.LookPath("stubby"); err != nil {
1443 return false
1444 }
1445 return true
1446}
1447
Dan Willemsen1e704462016-08-21 15:17:17 -07001448// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001449// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001450// still limited by Parallel()
1451func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001452 if !c.UseRemoteBuild() {
1453 return 0
1454 }
1455 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1456 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001457 }
1458 return 500
1459}
1460
1461func (c *configImpl) SetKatiArgs(args []string) {
1462 c.katiArgs = args
1463}
1464
1465func (c *configImpl) SetNinjaArgs(args []string) {
1466 c.ninjaArgs = args
1467}
1468
1469func (c *configImpl) SetKatiSuffix(suffix string) {
1470 c.katiSuffix = suffix
1471}
1472
Dan Willemsene0879fc2017-08-04 15:06:27 -07001473func (c *configImpl) LastKatiSuffixFile() string {
1474 return filepath.Join(c.OutDir(), "last_kati_suffix")
1475}
1476
1477func (c *configImpl) HasKatiSuffix() bool {
1478 return c.katiSuffix != ""
1479}
1480
Dan Willemsen1e704462016-08-21 15:17:17 -07001481func (c *configImpl) KatiEnvFile() string {
1482 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1483}
1484
Dan Willemsen29971232018-09-26 14:58:30 -07001485func (c *configImpl) KatiBuildNinjaFile() string {
1486 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001487}
1488
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001489func (c *configImpl) KatiPackageNinjaFile() string {
1490 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1491}
1492
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001493func (c *configImpl) SoongVarsFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001494 targetProduct, err := c.TargetProductOrErr()
1495 if err != nil {
1496 return filepath.Join(c.SoongOutDir(), "soong.variables")
1497 } else {
1498 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+".variables")
1499 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001500}
1501
Dan Willemsen1e704462016-08-21 15:17:17 -07001502func (c *configImpl) SoongNinjaFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001503 targetProduct, err := c.TargetProductOrErr()
1504 if err != nil {
1505 return filepath.Join(c.SoongOutDir(), "build.ninja")
1506 } else {
1507 return filepath.Join(c.SoongOutDir(), "build."+targetProduct+".ninja")
1508 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001509}
1510
1511func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001512 if c.katiSuffix == "" {
1513 return filepath.Join(c.OutDir(), "combined.ninja")
1514 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001515 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1516}
1517
1518func (c *configImpl) SoongAndroidMk() string {
1519 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1520}
1521
1522func (c *configImpl) SoongMakeVarsMk() string {
1523 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1524}
1525
Dan Willemsenf052f782017-05-18 15:29:04 -07001526func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001527 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001528}
1529
Dan Willemsen02781d52017-05-12 19:28:13 -07001530func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001531 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1532}
1533
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001534func (c *configImpl) KatiPackageMkDir() string {
1535 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1536}
1537
Dan Willemsenf052f782017-05-18 15:29:04 -07001538func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001539 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001540}
1541
1542func (c *configImpl) HostOut() string {
1543 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1544}
1545
1546// This probably needs to be multi-valued, so not exporting it for now
1547func (c *configImpl) hostCrossOut() string {
1548 if runtime.GOOS == "linux" {
1549 return filepath.Join(c.hostOutRoot(), "windows-x86")
1550 } else {
1551 return ""
1552 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001553}
1554
Dan Willemsen1e704462016-08-21 15:17:17 -07001555func (c *configImpl) HostPrebuiltTag() string {
1556 if runtime.GOOS == "linux" {
1557 return "linux-x86"
1558 } else if runtime.GOOS == "darwin" {
1559 return "darwin-x86"
1560 } else {
1561 panic("Unsupported OS")
1562 }
1563}
Dan Willemsenf173d592017-04-27 14:28:00 -07001564
Dan Willemsen8122bd52017-10-12 20:20:41 -07001565func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001566 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1567 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001568 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1569 if _, err := os.Stat(asan); err == nil {
1570 return asan
1571 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001572 }
1573 }
1574 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1575}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001576
1577func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1578 c.brokenDupRules = val
1579}
1580
1581func (c *configImpl) BuildBrokenDupRules() bool {
1582 return c.brokenDupRules
1583}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001584
Dan Willemsen25e6f092019-04-09 10:22:43 -07001585func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1586 c.brokenUsesNetwork = val
1587}
1588
1589func (c *configImpl) BuildBrokenUsesNetwork() bool {
1590 return c.brokenUsesNetwork
1591}
1592
Dan Willemsene3336352020-01-02 19:10:38 -08001593func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1594 c.brokenNinjaEnvVars = val
1595}
1596
1597func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1598 return c.brokenNinjaEnvVars
1599}
1600
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001601func (c *configImpl) SetTargetDeviceDir(dir string) {
1602 c.targetDeviceDir = dir
1603}
1604
1605func (c *configImpl) TargetDeviceDir() string {
1606 return c.targetDeviceDir
1607}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001608
Patrice Arruda219eef32020-06-01 17:29:30 +00001609func (c *configImpl) BuildDateTime() string {
1610 return c.buildDateTime
1611}
1612
1613func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001614 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001615}
Patrice Arruda83842d72020-12-08 19:42:08 +00001616
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001617// LogsDir returns the absolute path to the logs directory where build log and
1618// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001619// directory. If the argument dist is specified, the logs directory
1620// is <dist_dir>/logs.
1621func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001622 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001623 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001624 // 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 -05001625 dir = filepath.Join(c.RealDistDir(), "logs")
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 absDir, err := filepath.Abs(dir)
1628 if err != nil {
1629 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1630 os.Exit(1)
1631 }
1632 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001633}
1634
1635// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1636// where the bazel profiles are located.
1637func (c *configImpl) BazelMetricsDir() string {
1638 return filepath.Join(c.LogsDir(), "bazel_metrics")
1639}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001640
Chris Parsons53f68ae2022-03-03 12:01:40 -05001641// MkFileMetrics returns the file path for make-related metrics.
1642func (c *configImpl) MkMetrics() string {
1643 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1644}
1645
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001646func (c *configImpl) SetEmptyNinjaFile(v bool) {
1647 c.emptyNinjaFile = v
1648}
1649
1650func (c *configImpl) EmptyNinjaFile() bool {
1651 return c.emptyNinjaFile
1652}
Yu Liu6e13b402021-07-27 14:29:06 -07001653
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001654func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1655 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1656}
1657
Chris Parsons9402ca82023-02-23 17:28:06 -05001658func (c *configImpl) IsPersistentBazelEnabled() bool {
1659 return c.Environment().IsEnvTrue("USE_PERSISTENT_BAZEL")
1660}
1661
Chris Parsonsc83398f2023-05-31 18:41:41 +00001662// GetBazeliskBazelVersion returns the Bazel version to use for this build,
1663// or the empty string if the current canonical prod Bazel should be used.
1664// This environment variable should only be set to debug the build system.
1665// The Bazel version, if set, will be passed to Bazelisk, and Bazelisk will
1666// handle downloading and invoking the correct Bazel binary.
1667func (c *configImpl) GetBazeliskBazelVersion() string {
1668 value, _ := c.Environment().Get("USE_BAZEL_VERSION")
1669 return value
1670}
1671
MarkDacekd06db5d2022-11-29 00:47:59 +00001672func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1673 return c.bazelForceEnabledModules
1674}
1675
MarkDacekd0e7cd32022-12-02 22:22:40 +00001676func (c *configImpl) SkipMetricsUpload() bool {
1677 return c.skipMetricsUpload
1678}
1679
MarkDacekf47e1422023-04-19 16:47:36 +00001680func (c *configImpl) EnsureAllowlistIntegrity() bool {
1681 return c.ensureAllowlistIntegrity
1682}
1683
MarkDacek6614d9c2022-12-07 21:57:38 +00001684// Returns a Time object if one was passed via a command-line flag.
1685// Otherwise returns the passed default.
1686func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1687 if c.buildStartedTime == 0 {
1688 return defaultTime
1689 }
1690 return time.UnixMilli(c.buildStartedTime)
1691}
1692
MarkDacekd33c2fd2023-05-04 20:40:04 +00001693func (c *configImpl) BazelExitCode() int32 {
1694 return c.bazelExitCode
1695}
1696
Yu Liu6e13b402021-07-27 14:29:06 -07001697func GetMetricsUploader(topDir string, env *Environment) string {
1698 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1699 metricsUploader := filepath.Join(topDir, p)
1700 if _, err := os.Stat(metricsUploader); err == nil {
1701 return metricsUploader
1702 }
1703 }
1704
1705 return ""
1706}