blob: 613fc65376a66b04e6e192b1653c02c3964996e4 [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"
LaMont Jones9a912862023-11-06 22:11:08 +000034 "android/soong/ui/metrics"
Kousik Kumarec478642020-09-21 13:39:24 -040035
Dan Willemsen4591b642021-05-24 14:24:12 -070036 "google.golang.org/protobuf/proto"
Patrice Arruda96850362020-08-11 20:41:11 +000037
38 smpb "android/soong/ui/metrics/metrics_proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070039)
40
Kousik Kumar3ff037e2022-01-25 22:11:01 -050041const (
Chris Parsons53f68ae2022-03-03 12:01:40 -050042 envConfigDir = "vendor/google/tools/soong_config"
43 jsonSuffix = "json"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050044)
45
Kousik Kumar4c180ad2022-05-27 07:48:37 -040046var (
Kevin Dagostino096ab2f2023-03-03 19:47:17 +000047 rbeRandPrefix int
48 googleProdCredsExistCache bool
Kousik Kumar4c180ad2022-05-27 07:48:37 -040049)
50
51func init() {
52 rand.Seed(time.Now().UnixNano())
53 rbeRandPrefix = rand.Intn(1000)
54}
55
Dan Willemsen1e704462016-08-21 15:17:17 -070056type Config struct{ *configImpl }
57
58type configImpl struct {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020059 // Some targets that are implemented in soong_build
60 // (bp2build, json-module-graph) are not here and have their own bits below.
Colin Cross28f527c2019-11-26 16:19:04 -080061 arguments []string
62 goma bool
63 environ *Environment
64 distDir string
65 buildDateTime string
MarkDacek6614d9c2022-12-07 21:57:38 +000066 logsPrefix string
Dan Willemsen1e704462016-08-21 15:17:17 -070067
68 // From the arguments
MarkDacekf47e1422023-04-19 16:47:36 +000069 parallel int
70 keepGoing int
71 verbose bool
72 checkbuild bool
73 dist bool
74 jsonModuleGraph bool
MarkDacekf47e1422023-04-19 16:47:36 +000075 bp2build bool
76 queryview bool
77 reportMkMetrics bool // Collect and report mk2bp migration progress metrics.
78 soongDocs bool
79 multitreeBuild bool // This is a multitree build.
80 skipConfig bool
81 skipKati bool
82 skipKatiNinja bool
83 skipSoong bool
84 skipNinja bool
85 skipSoongTests bool
86 searchApiDir bool // Scan the Android.bp files generated in out/api_surfaces
87 skipMetricsUpload bool
88 buildStartedTime int64 // For metrics-upload-only - manually specify a build-started time
Jihoon Kang2a929ad2023-06-08 19:02:07 +000089 buildFromSourceStub bool
MarkDacek396491e2023-06-14 19:41:18 +000090 ensureAllowlistIntegrity bool // For CI builds - make sure modules are mixed-built
91 bazelExitCode int32 // For b runs - necessary for updating NonZeroExit
92 besId string // For b runs, to identify the BuildEventService logs
Dan Willemsen1e704462016-08-21 15:17:17 -070093
94 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070095 katiArgs []string
96 ninjaArgs []string
97 katiSuffix string
98 targetDevice string
99 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +0000100 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -0700101
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800102 // Autodetected
103 totalRAM uint64
104
Dan Willemsene3336352020-01-02 19:10:38 -0800105 brokenDupRules bool
106 brokenUsesNetwork bool
107 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -0700108
109 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000110
MarkDacekb78465d2022-10-18 20:10:16 +0000111 bazelProdMode bool
MarkDacekb78465d2022-10-18 20:10:16 +0000112 bazelStagingMode bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000113
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700114 // Set by multiproduct_kati
115 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700116
117 metricsUploader string
MarkDacekd06db5d2022-11-29 00:47:59 +0000118
119 bazelForceEnabledModules string
Spandan Dasc5763832022-11-08 18:42:16 +0000120
Sam Delmerico98a73292023-02-21 11:50:29 -0500121 includeTags []string
122 sourceRootDirs []string
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900123
124 // Data source to write ninja weight list
125 ninjaWeightListSource NinjaWeightListSource
Dan Willemsen1e704462016-08-21 15:17:17 -0700126}
127
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900128type NinjaWeightListSource uint
129
130const (
131 // ninja doesn't use weight list.
132 NOT_USED NinjaWeightListSource = iota
133 // ninja uses weight list based on previous builds by ninja log
134 NINJA_LOG
135 // ninja thinks every task has the same weight.
136 EVENLY_DISTRIBUTED
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900137 // ninja uses an external custom weight list
138 EXTERNAL_FILE
Jeongik Chae114e602023-03-19 00:12:39 +0900139 // ninja uses a prioritized module list from Soong
140 HINT_FROM_SOONG
Jeongik Chaa87506f2023-06-01 23:16:41 +0900141 // If ninja log exists, use NINJA_LOG, if not, use HINT_FROM_SOONG instead.
142 // We can assume it is an incremental build if ninja log exists.
143 DEFAULT
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900144)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800145const srcDirFileCheck = "build/soong/root.bp"
146
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700147var buildFiles = []string{"Android.mk", "Android.bp"}
148
Patrice Arruda13848222019-04-22 17:12:02 -0700149type BuildAction uint
150
151const (
152 // Builds all of the modules and their dependencies of a specified directory, relative to the root
153 // directory of the source tree.
154 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
155
156 // Builds all of the modules and their dependencies of a list of specified directories. All specified
157 // directories are relative to the root directory of the source tree.
158 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700159
160 // Build a list of specified modules. If none was specified, simply build the whole source tree.
161 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700162)
163
164// checkTopDir validates that the current directory is at the root directory of the source tree.
165func checkTopDir(ctx Context) {
166 if _, err := os.Stat(srcDirFileCheck); err != nil {
167 if os.IsNotExist(err) {
168 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
169 }
170 ctx.Fatalln("Error verifying tree state:", err)
171 }
172}
173
MarkDacek7901e582023-01-09 19:48:01 +0000174func loadEnvConfig(ctx Context, config *configImpl, bc string) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500175 if bc == "" {
176 return nil
177 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500178
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500179 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500180 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500181 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500182 envConfigDir,
183 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500184 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500185 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
186 envVarsJSON, err := ioutil.ReadFile(cfgFile)
187 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500188 continue
189 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500190 ctx.Verbosef("Loading config file %v\n", cfgFile)
191 var envVars map[string]map[string]string
192 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
193 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
194 continue
195 }
196 for k, v := range envVars["env"] {
197 if os.Getenv(k) != "" {
198 continue
199 }
200 config.environ.Set(k, v)
201 }
202 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
203 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500204 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500205
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500206 return nil
207}
208
Dan Willemsen1e704462016-08-21 15:17:17 -0700209func NewConfig(ctx Context, args ...string) Config {
210 ret := &configImpl{
Jeongik Chaf2ecf762023-05-19 14:03:45 +0900211 environ: OsEnvironment(),
212 sandboxConfig: &SandboxConfig{},
Jeongik Chaa87506f2023-06-01 23:16:41 +0900213 ninjaWeightListSource: DEFAULT,
Dan Willemsen1e704462016-08-21 15:17:17 -0700214 }
215
Colin Cross106d6ef2023-10-24 10:34:56 -0700216 // Skip soong tests by default on Linux
217 if runtime.GOOS == "linux" {
218 ret.skipSoongTests = true
219 }
220
Patrice Arruda90109172020-07-28 18:07:27 +0000221 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700222 ret.parallel = runtime.NumCPU() + 2
223 ret.keepGoing = 1
224
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800225 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700226 ret.parseArgs(ctx, args)
Jeongik Chae114e602023-03-19 00:12:39 +0900227
228 if ret.ninjaWeightListSource == HINT_FROM_SOONG {
Jeongik Chaa87506f2023-06-01 23:16:41 +0900229 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "always")
230 } else if ret.ninjaWeightListSource == DEFAULT {
231 defaultNinjaWeightListSource := NINJA_LOG
232 if _, err := os.Stat(filepath.Join(ret.OutDir(), ninjaLogFileName)); errors.Is(err, os.ErrNotExist) {
233 ctx.Verboseln("$OUT/.ninja_log doesn't exist, use HINT_FROM_SOONG instead")
234 defaultNinjaWeightListSource = HINT_FROM_SOONG
235 } else {
236 ctx.Verboseln("$OUT/.ninja_log exist, use NINJA_LOG")
237 }
238 ret.ninjaWeightListSource = defaultNinjaWeightListSource
239 // soong_build generates ninja hint depending on ninja log existence.
240 // Set it "depend" to avoid soong re-run due to env variable change.
241 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "depend")
Jeongik Chae114e602023-03-19 00:12:39 +0900242 }
Jeongik Chaa87506f2023-06-01 23:16:41 +0900243
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800244 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700245 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
246 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
247 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800248 outDir := "out"
249 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
250 if wd, err := os.Getwd(); err != nil {
251 ctx.Fatalln("Failed to get working directory:", err)
252 } else {
253 outDir = filepath.Join(baseDir, filepath.Base(wd))
254 }
255 }
256 ret.environ.Set("OUT_DIR", outDir)
257 }
258
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500259 // loadEnvConfig needs to know what the OUT_DIR is, so it should
260 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000261 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
262
263 if bc != "" {
Kousik Kumarc8818332023-01-16 16:33:05 +0000264 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000265 ctx.Fatalln("Failed to parse env config files: %v", err)
266 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +0000267 if !ret.canSupportRBE() {
268 // Explicitly set USE_RBE env variable to false when we cannot run
269 // an RBE build to avoid ninja local execution pool issues.
270 ret.environ.Set("USE_RBE", "false")
271 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500272 }
273
Dan Willemsen2d31a442018-10-20 21:33:41 -0700274 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
275 ret.distDir = filepath.Clean(distDir)
276 } else {
277 ret.distDir = filepath.Join(ret.OutDir(), "dist")
278 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700279
Spandan Das05063612021-06-25 01:39:04 +0000280 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
281 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
282 }
283
Dan Willemsen1e704462016-08-21 15:17:17 -0700284 ret.environ.Unset(
285 // We're already using it
286 "USE_SOONG_UI",
287
288 // We should never use GOROOT/GOPATH from the shell environment
289 "GOROOT",
290 "GOPATH",
291
292 // These should only come from Soong, not the environment.
293 "CLANG",
294 "CLANG_CXX",
295 "CCC_CC",
296 "CCC_CXX",
297
298 // Used by the goma compiler wrapper, but should only be set by
299 // gomacc
300 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800301
302 // We handle this above
303 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700304
Dan Willemsen2d31a442018-10-20 21:33:41 -0700305 // This is handled above too, and set for individual commands later
306 "DIST_DIR",
307
Dan Willemsen68a09852017-04-18 13:56:57 -0700308 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000309 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700310 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700311 "DISPLAY",
312 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000313 "JAVAC",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700314 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700315 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700316
317 // Drop make flags
318 "MAKEFLAGS",
319 "MAKELEVEL",
320 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700321
322 // Set in envsetup.sh, reset in makefiles
323 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700324
325 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
326 "ANDROID_BUILD_TOP",
327 "ANDROID_HOST_OUT",
328 "ANDROID_PRODUCT_OUT",
329 "ANDROID_HOST_OUT_TESTCASES",
330 "ANDROID_TARGET_OUT_TESTCASES",
331 "ANDROID_TOOLCHAIN",
332 "ANDROID_TOOLCHAIN_2ND_ARCH",
333 "ANDROID_DEV_SCRIPTS",
334 "ANDROID_EMULATOR_PREBUILTS",
335 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700336 )
337
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400338 if ret.UseGoma() || ret.ForceUseGoma() {
339 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
340 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400341 }
342
Dan Willemsen1e704462016-08-21 15:17:17 -0700343 // Tell python not to spam the source tree with .pyc files.
344 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
345
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400346 tmpDir := absPath(ctx, ret.TempDir())
347 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800348
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700349 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
350 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
351 "llvm-binutils-stable/llvm-symbolizer")
352 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
353
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800354 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700355 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800356
Yu Liu6e13b402021-07-27 14:29:06 -0700357 srcDir := absPath(ctx, ".")
358 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700359 ctx.Println("You are building in a directory whose absolute path contains a space character:")
360 ctx.Println()
361 ctx.Printf("%q\n", srcDir)
362 ctx.Println()
363 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700364 }
365
Yu Liu6e13b402021-07-27 14:29:06 -0700366 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
367
Dan Willemsendb8457c2017-05-12 16:38:17 -0700368 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700369 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
370 ctx.Println()
371 ctx.Printf("%q\n", outDir)
372 ctx.Println()
373 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700374 }
375
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000376 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700377 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
378 ctx.Println()
379 ctx.Printf("%q\n", distDir)
380 ctx.Println()
381 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700382 }
383
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700384 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000385 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800386 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Sorin Basca0760c892023-11-29 19:13:55 +0000387 java21Home := filepath.Join("prebuilts/jdk/jdk21", 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 }
Sorin Basca0760c892023-11-29 19:13:55 +0000392 if ret.environ.IsEnvTrue("EXPERIMENTAL_USE_OPENJDK21_TOOLCHAIN") {
393 return java21Home
394 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000395 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
396 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 +0100397 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000398 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
399 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
400 }
401 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700402 }()
403 absJavaHome := absPath(ctx, javaHome)
404
Dan Willemsened869522018-01-08 14:58:46 -0800405 ret.configureLocale(ctx)
406
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700407 newPath := []string{filepath.Join(absJavaHome, "bin")}
408 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
409 newPath = append(newPath, path)
410 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100411
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700412 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
413 ret.environ.Set("JAVA_HOME", absJavaHome)
414 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000415 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700416 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
417
Colin Crossfe5ed4d2023-07-28 09:27:23 -0700418 // b/286885495, https://bugzilla.redhat.com/show_bug.cgi?id=2227130: some versions of Fedora include patches
419 // to unzip to enable zipbomb detection that incorrectly handle zip64 and data descriptors and fail on large
420 // zip files produced by soong_zip. Disable zipbomb detection.
421 ret.environ.Set("UNZIP_DISABLE_ZIPBOMB_DETECTION", "TRUE")
422
LaMont Jones52a72432023-03-09 18:19:35 +0000423 if ret.MultitreeBuild() {
424 ret.environ.Set("MULTITREE_BUILD", "true")
425 }
426
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800427 outDir := ret.OutDir()
428 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800429 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800430 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800431 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800432 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800433 }
Colin Cross28f527c2019-11-26 16:19:04 -0800434
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800435 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
436
Cole Faust583dfb42023-09-28 13:56:30 -0700437 if _, ok := ret.environ.Get("BUILD_USERNAME"); !ok {
438 username := "unknown"
439 if u, err := user.Current(); err == nil {
440 username = u.Username
441 } else {
442 ctx.Println("Failed to get current user:", err)
443 }
444 ret.environ.Set("BUILD_USERNAME", username)
445 }
446
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400447 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400448 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400449 ret.environ.Set(k, v)
450 }
451 }
452
Patrice Arruda83842d72020-12-08 19:42:08 +0000453 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800454 if err := os.RemoveAll(bpd); err != nil {
455 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
456 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000457
Patrice Arruda96850362020-08-11 20:41:11 +0000458 c := Config{ret}
459 storeConfigMetrics(ctx, c)
460 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700461}
462
Patrice Arruda13848222019-04-22 17:12:02 -0700463// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
464// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700465func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
466 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700467}
468
LaMont Jones9a912862023-11-06 22:11:08 +0000469// Prepare for getting make variables. For them to be accurate, we need to have
470// obtained PRODUCT_RELEASE_CONFIG_MAPS.
471//
472// Returns:
473//
474// Whether config should be called again.
475//
476// TODO: when converting product config to a declarative language, make sure
477// that PRODUCT_RELEASE_CONFIG_MAPS is properly handled as a separate step in
478// that process.
479func SetProductReleaseConfigMaps(ctx Context, config Config) bool {
480 ctx.BeginTrace(metrics.RunKati, "SetProductReleaseConfigMaps")
481 defer ctx.EndTrace()
482
483 if config.SkipConfig() {
484 // This duplicates the logic from Build to skip product config
485 // if the user has explicitly said to.
486 return false
487 }
488
489 releaseConfigVars := []string{
490 "PRODUCT_RELEASE_CONFIG_MAPS",
491 }
492
493 origValue, _ := config.environ.Get("PRODUCT_RELEASE_CONFIG_MAPS")
494 // Get the PRODUCT_RELEASE_CONFIG_MAPS for this product, to avoid polluting the environment
495 // when we run product config to get the rest of the make vars.
496 releaseMapVars, err := dumpMakeVars(ctx, config, nil, releaseConfigVars, false, "")
497 if err != nil {
498 ctx.Fatalln("Error getting PRODUCT_RELEASE_CONFIG_MAPS:", err)
499 }
500 productReleaseConfigMaps := releaseMapVars["PRODUCT_RELEASE_CONFIG_MAPS"]
501 os.Setenv("PRODUCT_RELEASE_CONFIG_MAPS", productReleaseConfigMaps)
502 return origValue != productReleaseConfigMaps
503}
504
Patrice Arruda96850362020-08-11 20:41:11 +0000505// storeConfigMetrics selects a set of configuration information and store in
506// the metrics system for further analysis.
507func storeConfigMetrics(ctx Context, config Config) {
508 if ctx.Metrics == nil {
509 return
510 }
511
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400512 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000513
514 s := &smpb.SystemResourceInfo{
515 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
516 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
517 }
518 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000519}
520
Jeongik Cha8d63d562023-03-17 03:52:13 +0900521func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900522 switch s {
523 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900524 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900525 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900526 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900527 case EXTERNAL_FILE:
528 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900529 case HINT_FROM_SOONG:
530 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900531 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900532 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900533 }
534}
535
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400536func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700537 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400538 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
539 UseGoma: proto.Bool(config.UseGoma()),
540 UseRbe: proto.Bool(config.UseRBE()),
541 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
542 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900543 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400544 }
Yu Liue737a992021-10-04 13:21:41 -0700545 c.Targets = append(c.Targets, config.arguments...)
546
547 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400548}
549
Patrice Arruda13848222019-04-22 17:12:02 -0700550// getConfigArgs processes the command arguments based on the build action and creates a set of new
551// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700552func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700553 // The next block of code verifies that the current directory is the root directory of the source
554 // tree. It then finds the relative path of dir based on the root directory of the source tree
555 // and verify that dir is inside of the source tree.
556 checkTopDir(ctx)
557 topDir, err := os.Getwd()
558 if err != nil {
559 ctx.Fatalf("Error retrieving top directory: %v", err)
560 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700561 dir, err = filepath.EvalSymlinks(dir)
562 if err != nil {
563 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
564 }
Patrice Arruda13848222019-04-22 17:12:02 -0700565 dir, err = filepath.Abs(dir)
566 if err != nil {
567 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
568 }
569 relDir, err := filepath.Rel(topDir, dir)
570 if err != nil {
571 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
572 }
573 // If there are ".." in the path, it's not in the source tree.
574 if strings.Contains(relDir, "..") {
575 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
576 }
577
578 configArgs := args[:]
579
580 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
581 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
582 targetNamePrefix := "MODULES-IN-"
583 if inList("GET-INSTALL-PATH", configArgs) {
584 targetNamePrefix = "GET-INSTALL-PATH-IN-"
585 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
586 }
587
Patrice Arruda13848222019-04-22 17:12:02 -0700588 var targets []string
589
590 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700591 case BUILD_MODULES:
592 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700593 case BUILD_MODULES_IN_A_DIRECTORY:
594 // If dir is the root source tree, all the modules are built of the source tree are built so
595 // no need to find the build file.
596 if topDir == dir {
597 break
598 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700599
Patrice Arruda13848222019-04-22 17:12:02 -0700600 buildFile := findBuildFile(ctx, relDir)
601 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700602 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700603 }
Patrice Arruda13848222019-04-22 17:12:02 -0700604 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
605 case BUILD_MODULES_IN_DIRECTORIES:
606 newConfigArgs, dirs := splitArgs(configArgs)
607 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700608 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700609 }
610
611 // Tidy only override all other specified targets.
612 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
613 if tidyOnly == "true" || tidyOnly == "1" {
614 configArgs = append(configArgs, "tidy_only")
615 } else {
616 configArgs = append(configArgs, targets...)
617 }
618
619 return configArgs
620}
621
622// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
623func convertToTarget(dir string, targetNamePrefix string) string {
624 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
625}
626
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700627// hasBuildFile returns true if dir contains an Android build file.
628func hasBuildFile(ctx Context, dir string) bool {
629 for _, buildFile := range buildFiles {
630 _, err := os.Stat(filepath.Join(dir, buildFile))
631 if err == nil {
632 return true
633 }
634 if !os.IsNotExist(err) {
635 ctx.Fatalf("Error retrieving the build file stats: %v", err)
636 }
637 }
638 return false
639}
640
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700641// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
642// in the current and any sub directory of dir. If a build file is not found, traverse the path
643// up by one directory and repeat again until either a build file is found or reached to the root
644// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
645// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700646func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700647 // If the string is empty or ".", assume it is top directory of the source tree.
648 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700649 return ""
650 }
651
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700652 found := false
653 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
654 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
655 if err != nil {
656 return err
657 }
658 if found {
659 return filepath.SkipDir
660 }
661 if info.IsDir() {
662 return nil
663 }
664 for _, buildFile := range buildFiles {
665 if info.Name() == buildFile {
666 found = true
667 return filepath.SkipDir
668 }
669 }
670 return nil
671 })
672 if err != nil {
673 ctx.Fatalf("Error finding Android build file: %v", err)
674 }
675
676 if found {
677 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700678 }
679 }
680
681 return ""
682}
683
684// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
685func splitArgs(args []string) (newArgs []string, dirs []string) {
686 specialArgs := map[string]bool{
687 "showcommands": true,
688 "snod": true,
689 "dist": true,
690 "checkbuild": true,
691 }
692
693 newArgs = []string{}
694 dirs = []string{}
695
696 for _, arg := range args {
697 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
698 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
699 newArgs = append(newArgs, arg)
700 continue
701 }
702
703 if _, ok := specialArgs[arg]; ok {
704 newArgs = append(newArgs, arg)
705 continue
706 }
707
708 dirs = append(dirs, arg)
709 }
710
711 return newArgs, dirs
712}
713
714// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
715// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
716// source root tree where the build action command was invoked. Each directory is validated if the
717// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700718func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700719 for _, dir := range dirs {
720 // The directory may have specified specific modules to build. ":" is the separator to separate
721 // the directory and the list of modules.
722 s := strings.Split(dir, ":")
723 l := len(s)
724 if l > 2 { // more than one ":" was specified.
725 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
726 }
727
728 dir = filepath.Join(relDir, s[0])
729 if _, err := os.Stat(dir); err != nil {
730 ctx.Fatalf("couldn't find directory %s", dir)
731 }
732
733 // Verify that if there are any targets specified after ":". Each target is separated by ",".
734 var newTargets []string
735 if l == 2 && s[1] != "" {
736 newTargets = strings.Split(s[1], ",")
737 if inList("", newTargets) {
738 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
739 }
740 }
741
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700742 // If there are specified targets to build in dir, an android build file must exist for the one
743 // shot build. For the non-targets case, find the appropriate build file and build all the
744 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700745 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700746 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700747 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
748 }
749 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700750 buildFile := findBuildFile(ctx, dir)
751 if buildFile == "" {
752 ctx.Fatalf("Build file not found for %s directory", dir)
753 }
754 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700755 }
756
Patrice Arruda13848222019-04-22 17:12:02 -0700757 targets = append(targets, newTargets...)
758 }
759
Dan Willemsence41e942019-07-29 23:39:30 -0700760 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700761}
762
Dan Willemsen9b587492017-07-10 22:13:00 -0700763func (c *configImpl) parseArgs(ctx Context, args []string) {
764 for i := 0; i < len(args); i++ {
765 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100766 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700767 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200768 } else if arg == "--empty-ninja-file" {
769 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100770 } else if arg == "--skip-ninja" {
771 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700772 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700773 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
774 // but it does run a Kati ninja file if the .kati_enabled marker file was created
775 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000776 c.skipConfig = true
777 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100778 } else if arg == "--soong-only" {
779 c.skipKati = true
780 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200781 } else if arg == "--config-only" {
782 c.skipKati = true
783 c.skipKatiNinja = true
784 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700785 } else if arg == "--skip-config" {
786 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700787 } else if arg == "--skip-soong-tests" {
788 c.skipSoongTests = true
Colin Cross106d6ef2023-10-24 10:34:56 -0700789 } else if arg == "--no-skip-soong-tests" {
790 c.skipSoongTests = false
MarkDacekd0e7cd32022-12-02 22:22:40 +0000791 } else if arg == "--skip-metrics-upload" {
792 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500793 } else if arg == "--mk-metrics" {
794 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000795 } else if arg == "--multitree-build" {
796 c.multitreeBuild = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400797 } else if arg == "--bazel-mode" {
798 c.bazelProdMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000799 } else if arg == "--bazel-mode-staging" {
800 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000801 } else if arg == "--search-api-dir" {
802 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900803 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
804 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
805 if source == "ninja_log" {
806 c.ninjaWeightListSource = NINJA_LOG
807 } else if source == "evenly_distributed" {
808 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
809 } else if source == "not_used" {
810 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900811 } else if source == "soong" {
812 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900813 } else if strings.HasPrefix(source, "file,") {
814 c.ninjaWeightListSource = EXTERNAL_FILE
815 filePath := strings.TrimPrefix(source, "file,")
816 err := validateNinjaWeightList(filePath)
817 if err != nil {
818 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
819 }
820 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
821 if err != nil {
822 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
823 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900824 } else {
825 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
826 }
Jihoon Kang2a929ad2023-06-08 19:02:07 +0000827 } else if arg == "--build-from-source-stub" {
828 c.buildFromSourceStub = true
MarkDacekb96561e2022-12-02 04:34:43 +0000829 } else if strings.HasPrefix(arg, "--build-command=") {
830 buildCmd := strings.TrimPrefix(arg, "--build-command=")
831 // remove quotations
832 buildCmd = strings.TrimPrefix(buildCmd, "\"")
833 buildCmd = strings.TrimSuffix(buildCmd, "\"")
834 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000835 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
836 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
MarkDacek6614d9c2022-12-07 21:57:38 +0000837 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
838 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
839 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
840 if err == nil {
841 c.buildStartedTime = val
842 } else {
843 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
844 }
MarkDacekf47e1422023-04-19 16:47:36 +0000845 } else if arg == "--ensure-allowlist-integrity" {
846 c.ensureAllowlistIntegrity = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700847 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700848 parseArgNum := func(def int) int {
849 if len(arg) > 2 {
850 p, err := strconv.ParseUint(arg[2:], 10, 31)
851 if err != nil {
852 ctx.Fatalf("Failed to parse %q: %v", arg, err)
853 }
854 return int(p)
855 } else if i+1 < len(args) {
856 p, err := strconv.ParseUint(args[i+1], 10, 31)
857 if err == nil {
858 i++
859 return int(p)
860 }
861 }
862 return def
863 }
864
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700865 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700866 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700867 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700868 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700869 } else {
870 ctx.Fatalln("Unknown option:", arg)
871 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700872 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700873 if k == "OUT_DIR" {
874 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
875 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700876 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700877 } else if arg == "dist" {
878 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200879 } else if arg == "json-module-graph" {
880 c.jsonModuleGraph = true
881 } else if arg == "bp2build" {
882 c.bp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200883 } else if arg == "queryview" {
884 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200885 } else if arg == "soong_docs" {
886 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700887 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700888 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800889 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700890 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700891 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700892 }
893 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700894}
895
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900896func validateNinjaWeightList(weightListFilePath string) (err error) {
897 data, err := os.ReadFile(weightListFilePath)
898 if err != nil {
899 return
900 }
901 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
902 for _, line := range lines {
903 fields := strings.Split(line, ",")
904 if len(fields) != 2 {
905 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
906 }
907 _, err = strconv.Atoi(fields[1])
908 if err != nil {
909 return
910 }
911 }
912 return
913}
914
Dan Willemsened869522018-01-08 14:58:46 -0800915func (c *configImpl) configureLocale(ctx Context) {
916 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
917 output, err := cmd.Output()
918
919 var locales []string
920 if err == nil {
921 locales = strings.Split(string(output), "\n")
922 } else {
923 // If we're unable to list the locales, let's assume en_US.UTF-8
924 locales = []string{"en_US.UTF-8"}
925 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
926 }
927
928 // gettext uses LANGUAGE, which is passed directly through
929
930 // For LANG and LC_*, only preserve the evaluated version of
931 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800932 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800933 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800934 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800935 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800936 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800937 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800938 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800939 }
940
941 c.environ.UnsetWithPrefix("LC_")
942
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800943 if userLang != "" {
944 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800945 }
946
947 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
948 // for others)
949 if inList("C.UTF-8", locales) {
950 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500951 } else if inList("C.utf8", locales) {
952 // These normalize to the same thing
953 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800954 } else if inList("en_US.UTF-8", locales) {
955 c.environ.Set("LANG", "en_US.UTF-8")
956 } else if inList("en_US.utf8", locales) {
957 // These normalize to the same thing
958 c.environ.Set("LANG", "en_US.UTF-8")
959 } else {
960 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
961 }
962}
963
Dan Willemsen1e704462016-08-21 15:17:17 -0700964func (c *configImpl) Environment() *Environment {
965 return c.environ
966}
967
968func (c *configImpl) Arguments() []string {
969 return c.arguments
970}
971
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200972func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200973 if len(c.Arguments()) > 0 {
974 // Explicit targets requested that are not special targets like b2pbuild
975 // or the JSON module graph
976 return true
977 }
978
Chris Parsons73f411b2023-06-20 21:46:57 +0000979 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200980 // Command line was empty, the default Ninja target is built
981 return true
982 }
983
Liz Kammer88677422021-12-15 15:03:19 -0500984 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
985 if c.Dist() && !c.Bp2Build() {
986 return true
987 }
988
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200989 // build.ninja doesn't need to be generated
990 return false
991}
992
Dan Willemsen1e704462016-08-21 15:17:17 -0700993func (c *configImpl) OutDir() string {
994 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700995 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700996 }
997 return "out"
998}
999
Dan Willemsen8a073a82017-02-04 17:30:44 -08001000func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -04001001 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001002}
1003
1004func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -07001005 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -08001006}
1007
Dan Willemsen1e704462016-08-21 15:17:17 -07001008func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001009 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001010 return c.arguments
1011 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001012 return c.ninjaArgs
1013}
1014
Jingwen Chen7c6089a2020-11-02 02:56:20 -05001015func (c *configImpl) BazelOutDir() string {
1016 return filepath.Join(c.OutDir(), "bazel")
1017}
1018
Liz Kammer2af5ea82022-11-11 14:21:03 -05001019func (c *configImpl) bazelOutputBase() string {
1020 return filepath.Join(c.BazelOutDir(), "output")
1021}
1022
Dan Willemsen1e704462016-08-21 15:17:17 -07001023func (c *configImpl) SoongOutDir() string {
1024 return filepath.Join(c.OutDir(), "soong")
1025}
1026
Spandan Das394aa322022-11-03 17:02:10 +00001027func (c *configImpl) ApiSurfacesOutDir() string {
1028 return filepath.Join(c.OutDir(), "api_surfaces")
1029}
1030
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001031func (c *configImpl) PrebuiltOS() string {
1032 switch runtime.GOOS {
1033 case "linux":
1034 return "linux-x86"
1035 case "darwin":
1036 return "darwin-x86"
1037 default:
1038 panic("Unknown GOOS")
1039 }
1040}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001041
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001042func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001043 if c.SkipKatiNinja() {
1044 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1045 } else {
1046 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1047 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001048}
1049
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001050func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001051 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001052}
1053
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001054func (c *configImpl) UsedEnvFile(tag string) string {
Kiyoung Kimeaa55a82023-06-05 16:56:49 +09001055 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1056 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+v+"."+tag)
1057 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001058 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1059}
1060
Lukacs T. Berkic541cd22022-10-26 07:26:50 +00001061func (c *configImpl) Bp2BuildFilesMarkerFile() string {
1062 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
1063}
1064
1065func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001066 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +02001067}
1068
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001069func (c *configImpl) SoongDocsHtml() string {
1070 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1071}
1072
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001073func (c *configImpl) QueryviewMarkerFile() string {
1074 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1075}
1076
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001077func (c *configImpl) ModuleGraphFile() string {
1078 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1079}
1080
kgui67007242022-01-25 13:50:25 +08001081func (c *configImpl) ModuleActionsFile() string {
1082 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1083}
1084
Jeff Gastonefc1b412017-03-29 17:29:06 -07001085func (c *configImpl) TempDir() string {
1086 return shared.TempDirForOutDir(c.SoongOutDir())
1087}
1088
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001089func (c *configImpl) FileListDir() string {
1090 return filepath.Join(c.OutDir(), ".module_paths")
1091}
1092
Dan Willemsen1e704462016-08-21 15:17:17 -07001093func (c *configImpl) KatiSuffix() string {
1094 if c.katiSuffix != "" {
1095 return c.katiSuffix
1096 }
1097 panic("SetKatiSuffix has not been called")
1098}
1099
Colin Cross37193492017-11-16 17:55:00 -08001100// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1101// user is interested in additional checks at the expense of build time.
1102func (c *configImpl) Checkbuild() bool {
1103 return c.checkbuild
1104}
1105
Dan Willemsen8a073a82017-02-04 17:30:44 -08001106func (c *configImpl) Dist() bool {
1107 return c.dist
1108}
1109
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001110func (c *configImpl) JsonModuleGraph() bool {
1111 return c.jsonModuleGraph
1112}
1113
1114func (c *configImpl) Bp2Build() bool {
1115 return c.bp2build
1116}
1117
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001118func (c *configImpl) Queryview() bool {
1119 return c.queryview
1120}
1121
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001122func (c *configImpl) SoongDocs() bool {
1123 return c.soongDocs
1124}
1125
Dan Willemsen1e704462016-08-21 15:17:17 -07001126func (c *configImpl) IsVerbose() bool {
1127 return c.verbose
1128}
1129
LaMont Jones52a72432023-03-09 18:19:35 +00001130func (c *configImpl) MultitreeBuild() bool {
1131 return c.multitreeBuild
1132}
1133
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001134func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1135 return c.ninjaWeightListSource
1136}
1137
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001138func (c *configImpl) SkipKati() bool {
1139 return c.skipKati
1140}
1141
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001142func (c *configImpl) SkipKatiNinja() bool {
1143 return c.skipKatiNinja
1144}
1145
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001146func (c *configImpl) SkipSoong() bool {
1147 return c.skipSoong
1148}
1149
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001150func (c *configImpl) SkipNinja() bool {
1151 return c.skipNinja
1152}
1153
Anton Hansson5a7861a2021-06-04 10:09:01 +01001154func (c *configImpl) SetSkipNinja(v bool) {
1155 c.skipNinja = v
1156}
1157
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001158func (c *configImpl) SkipConfig() bool {
1159 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001160}
1161
Jihoon Kang1bff0342023-01-17 20:40:22 +00001162func (c *configImpl) BuildFromTextStub() bool {
Jihoon Kang2a929ad2023-06-08 19:02:07 +00001163 return !c.buildFromSourceStub
Jihoon Kang1bff0342023-01-17 20:40:22 +00001164}
1165
Dan Willemsen1e704462016-08-21 15:17:17 -07001166func (c *configImpl) TargetProduct() string {
1167 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1168 return v
1169 }
1170 panic("TARGET_PRODUCT is not defined")
1171}
1172
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001173func (c *configImpl) TargetProductOrErr() (string, error) {
1174 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1175 return v, nil
1176 }
1177 return "", fmt.Errorf("TARGET_PRODUCT is not defined")
1178}
1179
Dan Willemsen02781d52017-05-12 19:28:13 -07001180func (c *configImpl) TargetDevice() string {
1181 return c.targetDevice
1182}
1183
1184func (c *configImpl) SetTargetDevice(device string) {
1185 c.targetDevice = device
1186}
1187
1188func (c *configImpl) TargetBuildVariant() string {
1189 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1190 return v
1191 }
1192 panic("TARGET_BUILD_VARIANT is not defined")
1193}
1194
Dan Willemsen1e704462016-08-21 15:17:17 -07001195func (c *configImpl) KatiArgs() []string {
1196 return c.katiArgs
1197}
1198
1199func (c *configImpl) Parallel() int {
1200 return c.parallel
1201}
1202
Sam Delmerico98a73292023-02-21 11:50:29 -05001203func (c *configImpl) GetSourceRootDirs() []string {
1204 return c.sourceRootDirs
1205}
1206
1207func (c *configImpl) SetSourceRootDirs(i []string) {
1208 c.sourceRootDirs = i
1209}
1210
Spandan Dasc5763832022-11-08 18:42:16 +00001211func (c *configImpl) GetIncludeTags() []string {
1212 return c.includeTags
1213}
1214
1215func (c *configImpl) SetIncludeTags(i []string) {
1216 c.includeTags = i
1217}
1218
MarkDacek6614d9c2022-12-07 21:57:38 +00001219func (c *configImpl) GetLogsPrefix() string {
1220 return c.logsPrefix
1221}
1222
1223func (c *configImpl) SetLogsPrefix(prefix string) {
1224 c.logsPrefix = prefix
1225}
1226
Colin Cross8b8bec32019-11-15 13:18:43 -08001227func (c *configImpl) HighmemParallel() int {
1228 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1229 return i
1230 }
1231
1232 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1233 parallel := c.Parallel()
1234 if c.UseRemoteBuild() {
1235 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1236 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1237 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1238 // Return 1/16th of the size of the local pool, rounding up.
1239 return (parallel + 15) / 16
1240 } else if c.totalRAM == 0 {
1241 // Couldn't detect the total RAM, don't restrict highmem processes.
1242 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001243 } else if c.totalRAM <= 16*1024*1024*1024 {
1244 // Less than 16GB of ram, restrict to 1 highmem processes
1245 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001246 } else if c.totalRAM <= 32*1024*1024*1024 {
1247 // Less than 32GB of ram, restrict to 2 highmem processes
1248 return 2
1249 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1250 // If less than 8GB total RAM per process, reduce the number of highmem processes
1251 return p
1252 }
1253 // No restriction on highmem processes
1254 return parallel
1255}
1256
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001257func (c *configImpl) TotalRAM() uint64 {
1258 return c.totalRAM
1259}
1260
Kousik Kumarec478642020-09-21 13:39:24 -04001261// ForceUseGoma determines whether we should override Goma deprecation
1262// and use Goma for the current build or not.
1263func (c *configImpl) ForceUseGoma() bool {
1264 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1265 v = strings.TrimSpace(v)
1266 if v != "" && v != "false" {
1267 return true
1268 }
1269 }
1270 return false
1271}
1272
Dan Willemsen1e704462016-08-21 15:17:17 -07001273func (c *configImpl) UseGoma() bool {
1274 if v, ok := c.environ.Get("USE_GOMA"); ok {
1275 v = strings.TrimSpace(v)
1276 if v != "" && v != "false" {
1277 return true
1278 }
1279 }
1280 return false
1281}
1282
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001283func (c *configImpl) StartGoma() bool {
1284 if !c.UseGoma() {
1285 return false
1286 }
1287
1288 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1289 v = strings.TrimSpace(v)
1290 if v != "" && v != "false" {
1291 return false
1292 }
1293 }
1294 return true
1295}
1296
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001297func (c *configImpl) canSupportRBE() bool {
1298 // Do not use RBE with prod credentials in scenarios when stubby doesn't exist, since
1299 // its unlikely that we will be able to obtain necessary creds without stubby.
1300 authType, _ := c.rbeAuth()
1301 if !c.StubbyExists() && strings.Contains(authType, "use_google_prod_creds") {
1302 return false
1303 }
1304 return true
1305}
1306
Ramy Medhatbbf25672019-07-17 12:30:04 +00001307func (c *configImpl) UseRBE() bool {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001308 // These alternate modes of running Soong do not use RBE / reclient.
Chris Parsons73f411b2023-06-20 21:46:57 +00001309 if c.Bp2Build() || c.Queryview() || c.JsonModuleGraph() {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001310 return false
1311 }
1312
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001313 if !c.canSupportRBE() {
Kousik Kumar67ad4342023-06-06 15:09:27 -04001314 return false
1315 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001316
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001317 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001318 v = strings.TrimSpace(v)
1319 if v != "" && v != "false" {
1320 return true
1321 }
1322 }
1323 return false
1324}
1325
Chris Parsonsef615e52022-08-18 22:04:11 -04001326func (c *configImpl) BazelBuildEnabled() bool {
Chris Parsons21f80272023-06-15 04:02:28 +00001327 return c.bazelProdMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001328}
1329
Ramy Medhatbbf25672019-07-17 12:30:04 +00001330func (c *configImpl) StartRBE() bool {
1331 if !c.UseRBE() {
1332 return false
1333 }
1334
1335 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1336 v = strings.TrimSpace(v)
1337 if v != "" && v != "false" {
1338 return false
1339 }
1340 }
1341 return true
1342}
1343
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001344func (c *configImpl) rbeProxyLogsDir() string {
1345 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001346 if v, ok := c.environ.Get(f); ok {
1347 return v
1348 }
1349 }
Ramy Medhatbc061762023-10-10 18:36:59 +00001350 return c.rbeTmpDir()
1351}
1352
1353func (c *configImpl) rbeDownloadTmpDir() string {
Cole Faust06ea5312023-10-18 17:38:40 -07001354 for _, f := range []string{"RBE_download_tmp_dir", "FLAG_download_tmp_dir"} {
Ramy Medhatbc061762023-10-10 18:36:59 +00001355 if v, ok := c.environ.Get(f); ok {
1356 return v
1357 }
1358 }
1359 return c.rbeTmpDir()
1360}
1361
1362func (c *configImpl) rbeTmpDir() string {
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001363 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1364 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001365}
1366
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001367func (c *configImpl) rbeCacheDir() string {
1368 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1369 if v, ok := c.environ.Get(f); ok {
1370 return v
1371 }
1372 }
1373 return shared.JoinPath(c.SoongOutDir(), "rbe")
1374}
1375
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001376func (c *configImpl) shouldCleanupRBELogsDir() bool {
1377 // Perform a log directory cleanup only when the log directory
1378 // is auto created by the build rather than user-specified.
1379 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1380 if _, ok := c.environ.Get(f); ok {
1381 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001382 }
1383 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001384 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001385}
1386
1387func (c *configImpl) rbeExecRoot() string {
1388 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1389 if v, ok := c.environ.Get(f); ok {
1390 return v
1391 }
1392 }
1393 wd, err := os.Getwd()
1394 if err != nil {
1395 return ""
1396 }
1397 return wd
1398}
1399
1400func (c *configImpl) rbeDir() string {
1401 if v, ok := c.environ.Get("RBE_DIR"); ok {
1402 return v
1403 }
1404 return "prebuilts/remoteexecution-client/live/"
1405}
1406
1407func (c *configImpl) rbeReproxy() string {
1408 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1409 if v, ok := c.environ.Get(f); ok {
1410 return v
1411 }
1412 }
1413 return filepath.Join(c.rbeDir(), "reproxy")
1414}
1415
1416func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001417 credFlags := []string{
1418 "use_application_default_credentials",
1419 "use_gce_credentials",
1420 "credential_file",
1421 "use_google_prod_creds",
1422 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001423 for _, cf := range credFlags {
1424 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1425 if v, ok := c.environ.Get(f); ok {
1426 v = strings.TrimSpace(v)
1427 if v != "" && v != "false" && v != "0" {
1428 return "RBE_" + cf, v
1429 }
1430 }
1431 }
1432 }
1433 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001434}
1435
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001436func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1437 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1438 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1439
1440 name := filepath.Join(dir, base)
1441 if len(name) < maxNameLen {
1442 return name, nil
1443 }
1444
1445 name = filepath.Join("/tmp", base)
1446 if len(name) < maxNameLen {
1447 return name, nil
1448 }
1449
1450 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1451}
1452
Kousik Kumar7bc78192022-04-27 14:52:56 -04001453// IsGooglerEnvironment returns true if the current build is running
1454// on a Google developer machine and false otherwise.
1455func (c *configImpl) IsGooglerEnvironment() bool {
1456 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1457 if v, ok := c.environ.Get(cf); ok {
1458 return v == "googler"
1459 }
1460 return false
1461}
1462
1463// GoogleProdCredsExist determine whether credentials exist on the
1464// Googler machine to use remote execution.
1465func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001466 if googleProdCredsExistCache {
1467 return googleProdCredsExistCache
1468 }
andusyu0b3dc032023-06-21 17:29:32 -04001469 if _, err := exec.Command("/usr/bin/gcertstatus", "-nocheck_ssh").Output(); err != nil {
Kousik Kumar7bc78192022-04-27 14:52:56 -04001470 return false
1471 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001472 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001473 return true
1474}
1475
1476// UseRemoteBuild indicates whether to use a remote build acceleration system
1477// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001478func (c *configImpl) UseRemoteBuild() bool {
1479 return c.UseGoma() || c.UseRBE()
1480}
1481
Kousik Kumar7bc78192022-04-27 14:52:56 -04001482// StubbyExists checks whether the stubby binary exists on the machine running
1483// the build.
1484func (c *configImpl) StubbyExists() bool {
1485 if _, err := exec.LookPath("stubby"); err != nil {
1486 return false
1487 }
1488 return true
1489}
1490
Dan Willemsen1e704462016-08-21 15:17:17 -07001491// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001492// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001493// still limited by Parallel()
1494func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001495 if !c.UseRemoteBuild() {
1496 return 0
1497 }
1498 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1499 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001500 }
1501 return 500
1502}
1503
1504func (c *configImpl) SetKatiArgs(args []string) {
1505 c.katiArgs = args
1506}
1507
1508func (c *configImpl) SetNinjaArgs(args []string) {
1509 c.ninjaArgs = args
1510}
1511
1512func (c *configImpl) SetKatiSuffix(suffix string) {
1513 c.katiSuffix = suffix
1514}
1515
Dan Willemsene0879fc2017-08-04 15:06:27 -07001516func (c *configImpl) LastKatiSuffixFile() string {
1517 return filepath.Join(c.OutDir(), "last_kati_suffix")
1518}
1519
1520func (c *configImpl) HasKatiSuffix() bool {
1521 return c.katiSuffix != ""
1522}
1523
Dan Willemsen1e704462016-08-21 15:17:17 -07001524func (c *configImpl) KatiEnvFile() string {
1525 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1526}
1527
Dan Willemsen29971232018-09-26 14:58:30 -07001528func (c *configImpl) KatiBuildNinjaFile() string {
1529 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001530}
1531
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001532func (c *configImpl) KatiPackageNinjaFile() string {
1533 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1534}
1535
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001536func (c *configImpl) SoongVarsFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001537 targetProduct, err := c.TargetProductOrErr()
1538 if err != nil {
1539 return filepath.Join(c.SoongOutDir(), "soong.variables")
1540 } else {
1541 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+".variables")
1542 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001543}
1544
Dan Willemsen1e704462016-08-21 15:17:17 -07001545func (c *configImpl) SoongNinjaFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001546 targetProduct, err := c.TargetProductOrErr()
1547 if err != nil {
1548 return filepath.Join(c.SoongOutDir(), "build.ninja")
1549 } else {
1550 return filepath.Join(c.SoongOutDir(), "build."+targetProduct+".ninja")
1551 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001552}
1553
1554func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001555 if c.katiSuffix == "" {
1556 return filepath.Join(c.OutDir(), "combined.ninja")
1557 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001558 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1559}
1560
1561func (c *configImpl) SoongAndroidMk() string {
1562 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1563}
1564
1565func (c *configImpl) SoongMakeVarsMk() string {
1566 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1567}
1568
Colin Crossaa9a2732023-10-27 10:54:27 -07001569func (c *configImpl) SoongBuildMetrics() string {
Colin Crossb67b0612023-10-31 10:02:45 -07001570 return filepath.Join(c.LogsDir(), "soong_build_metrics.pb")
Colin Crossaa9a2732023-10-27 10:54:27 -07001571}
1572
Dan Willemsenf052f782017-05-18 15:29:04 -07001573func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001574 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001575}
1576
Dan Willemsen02781d52017-05-12 19:28:13 -07001577func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001578 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1579}
1580
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001581func (c *configImpl) KatiPackageMkDir() string {
1582 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1583}
1584
Dan Willemsenf052f782017-05-18 15:29:04 -07001585func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001586 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001587}
1588
1589func (c *configImpl) HostOut() string {
1590 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1591}
1592
1593// This probably needs to be multi-valued, so not exporting it for now
1594func (c *configImpl) hostCrossOut() string {
1595 if runtime.GOOS == "linux" {
1596 return filepath.Join(c.hostOutRoot(), "windows-x86")
1597 } else {
1598 return ""
1599 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001600}
1601
Dan Willemsen1e704462016-08-21 15:17:17 -07001602func (c *configImpl) HostPrebuiltTag() string {
1603 if runtime.GOOS == "linux" {
1604 return "linux-x86"
1605 } else if runtime.GOOS == "darwin" {
1606 return "darwin-x86"
1607 } else {
1608 panic("Unsupported OS")
1609 }
1610}
Dan Willemsenf173d592017-04-27 14:28:00 -07001611
Dan Willemsen8122bd52017-10-12 20:20:41 -07001612func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001613 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1614 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001615 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1616 if _, err := os.Stat(asan); err == nil {
1617 return asan
1618 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001619 }
1620 }
1621 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1622}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001623
1624func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1625 c.brokenDupRules = val
1626}
1627
1628func (c *configImpl) BuildBrokenDupRules() bool {
1629 return c.brokenDupRules
1630}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001631
Dan Willemsen25e6f092019-04-09 10:22:43 -07001632func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1633 c.brokenUsesNetwork = val
1634}
1635
1636func (c *configImpl) BuildBrokenUsesNetwork() bool {
1637 return c.brokenUsesNetwork
1638}
1639
Dan Willemsene3336352020-01-02 19:10:38 -08001640func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1641 c.brokenNinjaEnvVars = val
1642}
1643
1644func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1645 return c.brokenNinjaEnvVars
1646}
1647
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001648func (c *configImpl) SetTargetDeviceDir(dir string) {
1649 c.targetDeviceDir = dir
1650}
1651
1652func (c *configImpl) TargetDeviceDir() string {
1653 return c.targetDeviceDir
1654}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001655
Patrice Arruda219eef32020-06-01 17:29:30 +00001656func (c *configImpl) BuildDateTime() string {
1657 return c.buildDateTime
1658}
1659
1660func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001661 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001662}
Patrice Arruda83842d72020-12-08 19:42:08 +00001663
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001664// LogsDir returns the absolute path to the logs directory where build log and
1665// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001666// directory. If the argument dist is specified, the logs directory
1667// is <dist_dir>/logs.
1668func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001669 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001670 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001671 // 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 -05001672 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001673 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001674 absDir, err := filepath.Abs(dir)
1675 if err != nil {
1676 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1677 os.Exit(1)
1678 }
1679 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001680}
1681
1682// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1683// where the bazel profiles are located.
1684func (c *configImpl) BazelMetricsDir() string {
1685 return filepath.Join(c.LogsDir(), "bazel_metrics")
1686}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001687
Chris Parsons53f68ae2022-03-03 12:01:40 -05001688// MkFileMetrics returns the file path for make-related metrics.
1689func (c *configImpl) MkMetrics() string {
1690 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1691}
1692
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001693func (c *configImpl) SetEmptyNinjaFile(v bool) {
1694 c.emptyNinjaFile = v
1695}
1696
1697func (c *configImpl) EmptyNinjaFile() bool {
1698 return c.emptyNinjaFile
1699}
Yu Liu6e13b402021-07-27 14:29:06 -07001700
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001701func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1702 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1703}
1704
Chris Parsons9402ca82023-02-23 17:28:06 -05001705func (c *configImpl) IsPersistentBazelEnabled() bool {
1706 return c.Environment().IsEnvTrue("USE_PERSISTENT_BAZEL")
1707}
1708
Chris Parsonsc83398f2023-05-31 18:41:41 +00001709// GetBazeliskBazelVersion returns the Bazel version to use for this build,
1710// or the empty string if the current canonical prod Bazel should be used.
1711// This environment variable should only be set to debug the build system.
1712// The Bazel version, if set, will be passed to Bazelisk, and Bazelisk will
1713// handle downloading and invoking the correct Bazel binary.
1714func (c *configImpl) GetBazeliskBazelVersion() string {
1715 value, _ := c.Environment().Get("USE_BAZEL_VERSION")
1716 return value
1717}
1718
MarkDacekd06db5d2022-11-29 00:47:59 +00001719func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1720 return c.bazelForceEnabledModules
1721}
1722
MarkDacekd0e7cd32022-12-02 22:22:40 +00001723func (c *configImpl) SkipMetricsUpload() bool {
1724 return c.skipMetricsUpload
1725}
1726
MarkDacekf47e1422023-04-19 16:47:36 +00001727func (c *configImpl) EnsureAllowlistIntegrity() bool {
1728 return c.ensureAllowlistIntegrity
1729}
1730
MarkDacek6614d9c2022-12-07 21:57:38 +00001731// Returns a Time object if one was passed via a command-line flag.
1732// Otherwise returns the passed default.
1733func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1734 if c.buildStartedTime == 0 {
1735 return defaultTime
1736 }
1737 return time.UnixMilli(c.buildStartedTime)
1738}
1739
MarkDacekd33c2fd2023-05-04 20:40:04 +00001740func (c *configImpl) BazelExitCode() int32 {
1741 return c.bazelExitCode
1742}
1743
Yu Liu6e13b402021-07-27 14:29:06 -07001744func GetMetricsUploader(topDir string, env *Environment) string {
1745 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1746 metricsUploader := filepath.Join(topDir, p)
1747 if _, err := os.Stat(metricsUploader); err == nil {
1748 return metricsUploader
1749 }
1750 }
1751
1752 return ""
1753}