blob: d345415b5bf290cfbb603bb61c76ba754ad554fe [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())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700387 javaHome := func() string {
388 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
389 return override
390 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000391 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
392 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 +0100393 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000394 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
395 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
396 }
397 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700398 }()
399 absJavaHome := absPath(ctx, javaHome)
400
Dan Willemsened869522018-01-08 14:58:46 -0800401 ret.configureLocale(ctx)
402
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700403 newPath := []string{filepath.Join(absJavaHome, "bin")}
404 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
405 newPath = append(newPath, path)
406 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100407
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700408 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
409 ret.environ.Set("JAVA_HOME", absJavaHome)
410 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000411 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700412 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
413
Colin Crossfe5ed4d2023-07-28 09:27:23 -0700414 // b/286885495, https://bugzilla.redhat.com/show_bug.cgi?id=2227130: some versions of Fedora include patches
415 // to unzip to enable zipbomb detection that incorrectly handle zip64 and data descriptors and fail on large
416 // zip files produced by soong_zip. Disable zipbomb detection.
417 ret.environ.Set("UNZIP_DISABLE_ZIPBOMB_DETECTION", "TRUE")
418
LaMont Jones52a72432023-03-09 18:19:35 +0000419 if ret.MultitreeBuild() {
420 ret.environ.Set("MULTITREE_BUILD", "true")
421 }
422
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800423 outDir := ret.OutDir()
424 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800425 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800426 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800427 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800428 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800429 }
Colin Cross28f527c2019-11-26 16:19:04 -0800430
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800431 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
432
Cole Faust583dfb42023-09-28 13:56:30 -0700433 if _, ok := ret.environ.Get("BUILD_USERNAME"); !ok {
434 username := "unknown"
435 if u, err := user.Current(); err == nil {
436 username = u.Username
437 } else {
438 ctx.Println("Failed to get current user:", err)
439 }
440 ret.environ.Set("BUILD_USERNAME", username)
441 }
442
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400443 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400444 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400445 ret.environ.Set(k, v)
446 }
447 }
448
Patrice Arruda83842d72020-12-08 19:42:08 +0000449 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800450 if err := os.RemoveAll(bpd); err != nil {
451 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
452 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000453
Patrice Arruda96850362020-08-11 20:41:11 +0000454 c := Config{ret}
455 storeConfigMetrics(ctx, c)
456 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700457}
458
Patrice Arruda13848222019-04-22 17:12:02 -0700459// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
460// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700461func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
462 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700463}
464
LaMont Jones9a912862023-11-06 22:11:08 +0000465// Prepare for getting make variables. For them to be accurate, we need to have
466// obtained PRODUCT_RELEASE_CONFIG_MAPS.
467//
468// Returns:
469//
470// Whether config should be called again.
471//
472// TODO: when converting product config to a declarative language, make sure
473// that PRODUCT_RELEASE_CONFIG_MAPS is properly handled as a separate step in
474// that process.
475func SetProductReleaseConfigMaps(ctx Context, config Config) bool {
476 ctx.BeginTrace(metrics.RunKati, "SetProductReleaseConfigMaps")
477 defer ctx.EndTrace()
478
479 if config.SkipConfig() {
480 // This duplicates the logic from Build to skip product config
481 // if the user has explicitly said to.
482 return false
483 }
484
485 releaseConfigVars := []string{
486 "PRODUCT_RELEASE_CONFIG_MAPS",
487 }
488
489 origValue, _ := config.environ.Get("PRODUCT_RELEASE_CONFIG_MAPS")
490 // Get the PRODUCT_RELEASE_CONFIG_MAPS for this product, to avoid polluting the environment
491 // when we run product config to get the rest of the make vars.
492 releaseMapVars, err := dumpMakeVars(ctx, config, nil, releaseConfigVars, false, "")
493 if err != nil {
494 ctx.Fatalln("Error getting PRODUCT_RELEASE_CONFIG_MAPS:", err)
495 }
496 productReleaseConfigMaps := releaseMapVars["PRODUCT_RELEASE_CONFIG_MAPS"]
497 os.Setenv("PRODUCT_RELEASE_CONFIG_MAPS", productReleaseConfigMaps)
498 return origValue != productReleaseConfigMaps
499}
500
Patrice Arruda96850362020-08-11 20:41:11 +0000501// storeConfigMetrics selects a set of configuration information and store in
502// the metrics system for further analysis.
503func storeConfigMetrics(ctx Context, config Config) {
504 if ctx.Metrics == nil {
505 return
506 }
507
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400508 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000509
510 s := &smpb.SystemResourceInfo{
511 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
512 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
513 }
514 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000515}
516
Jeongik Cha8d63d562023-03-17 03:52:13 +0900517func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900518 switch s {
519 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900520 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900521 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900522 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900523 case EXTERNAL_FILE:
524 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900525 case HINT_FROM_SOONG:
526 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900527 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900528 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900529 }
530}
531
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400532func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700533 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400534 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
535 UseGoma: proto.Bool(config.UseGoma()),
536 UseRbe: proto.Bool(config.UseRBE()),
537 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
538 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900539 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400540 }
Yu Liue737a992021-10-04 13:21:41 -0700541 c.Targets = append(c.Targets, config.arguments...)
542
543 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400544}
545
Patrice Arruda13848222019-04-22 17:12:02 -0700546// getConfigArgs processes the command arguments based on the build action and creates a set of new
547// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700548func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700549 // The next block of code verifies that the current directory is the root directory of the source
550 // tree. It then finds the relative path of dir based on the root directory of the source tree
551 // and verify that dir is inside of the source tree.
552 checkTopDir(ctx)
553 topDir, err := os.Getwd()
554 if err != nil {
555 ctx.Fatalf("Error retrieving top directory: %v", err)
556 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700557 dir, err = filepath.EvalSymlinks(dir)
558 if err != nil {
559 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
560 }
Patrice Arruda13848222019-04-22 17:12:02 -0700561 dir, err = filepath.Abs(dir)
562 if err != nil {
563 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
564 }
565 relDir, err := filepath.Rel(topDir, dir)
566 if err != nil {
567 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
568 }
569 // If there are ".." in the path, it's not in the source tree.
570 if strings.Contains(relDir, "..") {
571 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
572 }
573
574 configArgs := args[:]
575
576 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
577 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
578 targetNamePrefix := "MODULES-IN-"
579 if inList("GET-INSTALL-PATH", configArgs) {
580 targetNamePrefix = "GET-INSTALL-PATH-IN-"
581 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
582 }
583
Patrice Arruda13848222019-04-22 17:12:02 -0700584 var targets []string
585
586 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700587 case BUILD_MODULES:
588 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700589 case BUILD_MODULES_IN_A_DIRECTORY:
590 // If dir is the root source tree, all the modules are built of the source tree are built so
591 // no need to find the build file.
592 if topDir == dir {
593 break
594 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700595
Patrice Arruda13848222019-04-22 17:12:02 -0700596 buildFile := findBuildFile(ctx, relDir)
597 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700598 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700599 }
Patrice Arruda13848222019-04-22 17:12:02 -0700600 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
601 case BUILD_MODULES_IN_DIRECTORIES:
602 newConfigArgs, dirs := splitArgs(configArgs)
603 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700604 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700605 }
606
607 // Tidy only override all other specified targets.
608 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
609 if tidyOnly == "true" || tidyOnly == "1" {
610 configArgs = append(configArgs, "tidy_only")
611 } else {
612 configArgs = append(configArgs, targets...)
613 }
614
615 return configArgs
616}
617
618// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
619func convertToTarget(dir string, targetNamePrefix string) string {
620 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
621}
622
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700623// hasBuildFile returns true if dir contains an Android build file.
624func hasBuildFile(ctx Context, dir string) bool {
625 for _, buildFile := range buildFiles {
626 _, err := os.Stat(filepath.Join(dir, buildFile))
627 if err == nil {
628 return true
629 }
630 if !os.IsNotExist(err) {
631 ctx.Fatalf("Error retrieving the build file stats: %v", err)
632 }
633 }
634 return false
635}
636
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700637// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
638// in the current and any sub directory of dir. If a build file is not found, traverse the path
639// up by one directory and repeat again until either a build file is found or reached to the root
640// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
641// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700642func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700643 // If the string is empty or ".", assume it is top directory of the source tree.
644 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700645 return ""
646 }
647
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700648 found := false
649 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
650 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
651 if err != nil {
652 return err
653 }
654 if found {
655 return filepath.SkipDir
656 }
657 if info.IsDir() {
658 return nil
659 }
660 for _, buildFile := range buildFiles {
661 if info.Name() == buildFile {
662 found = true
663 return filepath.SkipDir
664 }
665 }
666 return nil
667 })
668 if err != nil {
669 ctx.Fatalf("Error finding Android build file: %v", err)
670 }
671
672 if found {
673 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700674 }
675 }
676
677 return ""
678}
679
680// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
681func splitArgs(args []string) (newArgs []string, dirs []string) {
682 specialArgs := map[string]bool{
683 "showcommands": true,
684 "snod": true,
685 "dist": true,
686 "checkbuild": true,
687 }
688
689 newArgs = []string{}
690 dirs = []string{}
691
692 for _, arg := range args {
693 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
694 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
695 newArgs = append(newArgs, arg)
696 continue
697 }
698
699 if _, ok := specialArgs[arg]; ok {
700 newArgs = append(newArgs, arg)
701 continue
702 }
703
704 dirs = append(dirs, arg)
705 }
706
707 return newArgs, dirs
708}
709
710// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
711// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
712// source root tree where the build action command was invoked. Each directory is validated if the
713// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700714func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700715 for _, dir := range dirs {
716 // The directory may have specified specific modules to build. ":" is the separator to separate
717 // the directory and the list of modules.
718 s := strings.Split(dir, ":")
719 l := len(s)
720 if l > 2 { // more than one ":" was specified.
721 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
722 }
723
724 dir = filepath.Join(relDir, s[0])
725 if _, err := os.Stat(dir); err != nil {
726 ctx.Fatalf("couldn't find directory %s", dir)
727 }
728
729 // Verify that if there are any targets specified after ":". Each target is separated by ",".
730 var newTargets []string
731 if l == 2 && s[1] != "" {
732 newTargets = strings.Split(s[1], ",")
733 if inList("", newTargets) {
734 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
735 }
736 }
737
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700738 // If there are specified targets to build in dir, an android build file must exist for the one
739 // shot build. For the non-targets case, find the appropriate build file and build all the
740 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700741 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700742 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700743 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
744 }
745 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700746 buildFile := findBuildFile(ctx, dir)
747 if buildFile == "" {
748 ctx.Fatalf("Build file not found for %s directory", dir)
749 }
750 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700751 }
752
Patrice Arruda13848222019-04-22 17:12:02 -0700753 targets = append(targets, newTargets...)
754 }
755
Dan Willemsence41e942019-07-29 23:39:30 -0700756 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700757}
758
Dan Willemsen9b587492017-07-10 22:13:00 -0700759func (c *configImpl) parseArgs(ctx Context, args []string) {
760 for i := 0; i < len(args); i++ {
761 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100762 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700763 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200764 } else if arg == "--empty-ninja-file" {
765 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100766 } else if arg == "--skip-ninja" {
767 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700768 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700769 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
770 // but it does run a Kati ninja file if the .kati_enabled marker file was created
771 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000772 c.skipConfig = true
773 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100774 } else if arg == "--soong-only" {
775 c.skipKati = true
776 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200777 } else if arg == "--config-only" {
778 c.skipKati = true
779 c.skipKatiNinja = true
780 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700781 } else if arg == "--skip-config" {
782 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700783 } else if arg == "--skip-soong-tests" {
784 c.skipSoongTests = true
Colin Cross106d6ef2023-10-24 10:34:56 -0700785 } else if arg == "--no-skip-soong-tests" {
786 c.skipSoongTests = false
MarkDacekd0e7cd32022-12-02 22:22:40 +0000787 } else if arg == "--skip-metrics-upload" {
788 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500789 } else if arg == "--mk-metrics" {
790 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000791 } else if arg == "--multitree-build" {
792 c.multitreeBuild = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400793 } else if arg == "--bazel-mode" {
794 c.bazelProdMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000795 } else if arg == "--bazel-mode-staging" {
796 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000797 } else if arg == "--search-api-dir" {
798 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900799 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
800 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
801 if source == "ninja_log" {
802 c.ninjaWeightListSource = NINJA_LOG
803 } else if source == "evenly_distributed" {
804 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
805 } else if source == "not_used" {
806 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900807 } else if source == "soong" {
808 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900809 } else if strings.HasPrefix(source, "file,") {
810 c.ninjaWeightListSource = EXTERNAL_FILE
811 filePath := strings.TrimPrefix(source, "file,")
812 err := validateNinjaWeightList(filePath)
813 if err != nil {
814 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
815 }
816 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
817 if err != nil {
818 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
819 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900820 } else {
821 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
822 }
Jihoon Kang2a929ad2023-06-08 19:02:07 +0000823 } else if arg == "--build-from-source-stub" {
824 c.buildFromSourceStub = true
MarkDacekb96561e2022-12-02 04:34:43 +0000825 } else if strings.HasPrefix(arg, "--build-command=") {
826 buildCmd := strings.TrimPrefix(arg, "--build-command=")
827 // remove quotations
828 buildCmd = strings.TrimPrefix(buildCmd, "\"")
829 buildCmd = strings.TrimSuffix(buildCmd, "\"")
830 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000831 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
832 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
MarkDacek6614d9c2022-12-07 21:57:38 +0000833 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
834 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
835 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
836 if err == nil {
837 c.buildStartedTime = val
838 } else {
839 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
840 }
MarkDacekf47e1422023-04-19 16:47:36 +0000841 } else if arg == "--ensure-allowlist-integrity" {
842 c.ensureAllowlistIntegrity = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700843 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700844 parseArgNum := func(def int) int {
845 if len(arg) > 2 {
846 p, err := strconv.ParseUint(arg[2:], 10, 31)
847 if err != nil {
848 ctx.Fatalf("Failed to parse %q: %v", arg, err)
849 }
850 return int(p)
851 } else if i+1 < len(args) {
852 p, err := strconv.ParseUint(args[i+1], 10, 31)
853 if err == nil {
854 i++
855 return int(p)
856 }
857 }
858 return def
859 }
860
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700861 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700862 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700863 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700864 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700865 } else {
866 ctx.Fatalln("Unknown option:", arg)
867 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700868 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700869 if k == "OUT_DIR" {
870 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
871 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700872 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700873 } else if arg == "dist" {
874 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200875 } else if arg == "json-module-graph" {
876 c.jsonModuleGraph = true
877 } else if arg == "bp2build" {
878 c.bp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200879 } else if arg == "queryview" {
880 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200881 } else if arg == "soong_docs" {
882 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700883 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700884 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800885 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700886 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700887 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700888 }
889 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700890}
891
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900892func validateNinjaWeightList(weightListFilePath string) (err error) {
893 data, err := os.ReadFile(weightListFilePath)
894 if err != nil {
895 return
896 }
897 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
898 for _, line := range lines {
899 fields := strings.Split(line, ",")
900 if len(fields) != 2 {
901 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
902 }
903 _, err = strconv.Atoi(fields[1])
904 if err != nil {
905 return
906 }
907 }
908 return
909}
910
Dan Willemsened869522018-01-08 14:58:46 -0800911func (c *configImpl) configureLocale(ctx Context) {
912 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
913 output, err := cmd.Output()
914
915 var locales []string
916 if err == nil {
917 locales = strings.Split(string(output), "\n")
918 } else {
919 // If we're unable to list the locales, let's assume en_US.UTF-8
920 locales = []string{"en_US.UTF-8"}
921 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
922 }
923
924 // gettext uses LANGUAGE, which is passed directly through
925
926 // For LANG and LC_*, only preserve the evaluated version of
927 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800928 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800929 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800930 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800931 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800932 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800933 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800934 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800935 }
936
937 c.environ.UnsetWithPrefix("LC_")
938
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800939 if userLang != "" {
940 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800941 }
942
943 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
944 // for others)
945 if inList("C.UTF-8", locales) {
946 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500947 } else if inList("C.utf8", locales) {
948 // These normalize to the same thing
949 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800950 } else if inList("en_US.UTF-8", locales) {
951 c.environ.Set("LANG", "en_US.UTF-8")
952 } else if inList("en_US.utf8", locales) {
953 // These normalize to the same thing
954 c.environ.Set("LANG", "en_US.UTF-8")
955 } else {
956 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
957 }
958}
959
Dan Willemsen1e704462016-08-21 15:17:17 -0700960func (c *configImpl) Environment() *Environment {
961 return c.environ
962}
963
964func (c *configImpl) Arguments() []string {
965 return c.arguments
966}
967
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200968func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200969 if len(c.Arguments()) > 0 {
970 // Explicit targets requested that are not special targets like b2pbuild
971 // or the JSON module graph
972 return true
973 }
974
Chris Parsons73f411b2023-06-20 21:46:57 +0000975 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200976 // Command line was empty, the default Ninja target is built
977 return true
978 }
979
Liz Kammer88677422021-12-15 15:03:19 -0500980 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
981 if c.Dist() && !c.Bp2Build() {
982 return true
983 }
984
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200985 // build.ninja doesn't need to be generated
986 return false
987}
988
Dan Willemsen1e704462016-08-21 15:17:17 -0700989func (c *configImpl) OutDir() string {
990 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700991 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700992 }
993 return "out"
994}
995
Dan Willemsen8a073a82017-02-04 17:30:44 -0800996func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400997 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000998}
999
1000func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -07001001 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -08001002}
1003
Dan Willemsen1e704462016-08-21 15:17:17 -07001004func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001005 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001006 return c.arguments
1007 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001008 return c.ninjaArgs
1009}
1010
Jingwen Chen7c6089a2020-11-02 02:56:20 -05001011func (c *configImpl) BazelOutDir() string {
1012 return filepath.Join(c.OutDir(), "bazel")
1013}
1014
Liz Kammer2af5ea82022-11-11 14:21:03 -05001015func (c *configImpl) bazelOutputBase() string {
1016 return filepath.Join(c.BazelOutDir(), "output")
1017}
1018
Dan Willemsen1e704462016-08-21 15:17:17 -07001019func (c *configImpl) SoongOutDir() string {
1020 return filepath.Join(c.OutDir(), "soong")
1021}
1022
Spandan Das394aa322022-11-03 17:02:10 +00001023func (c *configImpl) ApiSurfacesOutDir() string {
1024 return filepath.Join(c.OutDir(), "api_surfaces")
1025}
1026
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001027func (c *configImpl) PrebuiltOS() string {
1028 switch runtime.GOOS {
1029 case "linux":
1030 return "linux-x86"
1031 case "darwin":
1032 return "darwin-x86"
1033 default:
1034 panic("Unknown GOOS")
1035 }
1036}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001037
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001038func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001039 if c.SkipKatiNinja() {
1040 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1041 } else {
1042 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1043 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001044}
1045
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001046func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001047 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001048}
1049
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001050func (c *configImpl) UsedEnvFile(tag string) string {
Kiyoung Kimeaa55a82023-06-05 16:56:49 +09001051 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1052 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+v+"."+tag)
1053 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001054 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1055}
1056
Lukacs T. Berkic541cd22022-10-26 07:26:50 +00001057func (c *configImpl) Bp2BuildFilesMarkerFile() string {
1058 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
1059}
1060
1061func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001062 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +02001063}
1064
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001065func (c *configImpl) SoongDocsHtml() string {
1066 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1067}
1068
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001069func (c *configImpl) QueryviewMarkerFile() string {
1070 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1071}
1072
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001073func (c *configImpl) ModuleGraphFile() string {
1074 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1075}
1076
kgui67007242022-01-25 13:50:25 +08001077func (c *configImpl) ModuleActionsFile() string {
1078 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1079}
1080
Jeff Gastonefc1b412017-03-29 17:29:06 -07001081func (c *configImpl) TempDir() string {
1082 return shared.TempDirForOutDir(c.SoongOutDir())
1083}
1084
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001085func (c *configImpl) FileListDir() string {
1086 return filepath.Join(c.OutDir(), ".module_paths")
1087}
1088
Dan Willemsen1e704462016-08-21 15:17:17 -07001089func (c *configImpl) KatiSuffix() string {
1090 if c.katiSuffix != "" {
1091 return c.katiSuffix
1092 }
1093 panic("SetKatiSuffix has not been called")
1094}
1095
Colin Cross37193492017-11-16 17:55:00 -08001096// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1097// user is interested in additional checks at the expense of build time.
1098func (c *configImpl) Checkbuild() bool {
1099 return c.checkbuild
1100}
1101
Dan Willemsen8a073a82017-02-04 17:30:44 -08001102func (c *configImpl) Dist() bool {
1103 return c.dist
1104}
1105
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001106func (c *configImpl) JsonModuleGraph() bool {
1107 return c.jsonModuleGraph
1108}
1109
1110func (c *configImpl) Bp2Build() bool {
1111 return c.bp2build
1112}
1113
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001114func (c *configImpl) Queryview() bool {
1115 return c.queryview
1116}
1117
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001118func (c *configImpl) SoongDocs() bool {
1119 return c.soongDocs
1120}
1121
Dan Willemsen1e704462016-08-21 15:17:17 -07001122func (c *configImpl) IsVerbose() bool {
1123 return c.verbose
1124}
1125
LaMont Jones52a72432023-03-09 18:19:35 +00001126func (c *configImpl) MultitreeBuild() bool {
1127 return c.multitreeBuild
1128}
1129
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001130func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1131 return c.ninjaWeightListSource
1132}
1133
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001134func (c *configImpl) SkipKati() bool {
1135 return c.skipKati
1136}
1137
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001138func (c *configImpl) SkipKatiNinja() bool {
1139 return c.skipKatiNinja
1140}
1141
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001142func (c *configImpl) SkipSoong() bool {
1143 return c.skipSoong
1144}
1145
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001146func (c *configImpl) SkipNinja() bool {
1147 return c.skipNinja
1148}
1149
Anton Hansson5a7861a2021-06-04 10:09:01 +01001150func (c *configImpl) SetSkipNinja(v bool) {
1151 c.skipNinja = v
1152}
1153
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001154func (c *configImpl) SkipConfig() bool {
1155 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001156}
1157
Jihoon Kang1bff0342023-01-17 20:40:22 +00001158func (c *configImpl) BuildFromTextStub() bool {
Jihoon Kang2a929ad2023-06-08 19:02:07 +00001159 return !c.buildFromSourceStub
Jihoon Kang1bff0342023-01-17 20:40:22 +00001160}
1161
Dan Willemsen1e704462016-08-21 15:17:17 -07001162func (c *configImpl) TargetProduct() string {
1163 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1164 return v
1165 }
1166 panic("TARGET_PRODUCT is not defined")
1167}
1168
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001169func (c *configImpl) TargetProductOrErr() (string, error) {
1170 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1171 return v, nil
1172 }
1173 return "", fmt.Errorf("TARGET_PRODUCT is not defined")
1174}
1175
Dan Willemsen02781d52017-05-12 19:28:13 -07001176func (c *configImpl) TargetDevice() string {
1177 return c.targetDevice
1178}
1179
1180func (c *configImpl) SetTargetDevice(device string) {
1181 c.targetDevice = device
1182}
1183
1184func (c *configImpl) TargetBuildVariant() string {
1185 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1186 return v
1187 }
1188 panic("TARGET_BUILD_VARIANT is not defined")
1189}
1190
Dan Willemsen1e704462016-08-21 15:17:17 -07001191func (c *configImpl) KatiArgs() []string {
1192 return c.katiArgs
1193}
1194
1195func (c *configImpl) Parallel() int {
1196 return c.parallel
1197}
1198
Sam Delmerico98a73292023-02-21 11:50:29 -05001199func (c *configImpl) GetSourceRootDirs() []string {
1200 return c.sourceRootDirs
1201}
1202
1203func (c *configImpl) SetSourceRootDirs(i []string) {
1204 c.sourceRootDirs = i
1205}
1206
Spandan Dasc5763832022-11-08 18:42:16 +00001207func (c *configImpl) GetIncludeTags() []string {
1208 return c.includeTags
1209}
1210
1211func (c *configImpl) SetIncludeTags(i []string) {
1212 c.includeTags = i
1213}
1214
MarkDacek6614d9c2022-12-07 21:57:38 +00001215func (c *configImpl) GetLogsPrefix() string {
1216 return c.logsPrefix
1217}
1218
1219func (c *configImpl) SetLogsPrefix(prefix string) {
1220 c.logsPrefix = prefix
1221}
1222
Colin Cross8b8bec32019-11-15 13:18:43 -08001223func (c *configImpl) HighmemParallel() int {
1224 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1225 return i
1226 }
1227
1228 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1229 parallel := c.Parallel()
1230 if c.UseRemoteBuild() {
1231 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1232 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1233 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1234 // Return 1/16th of the size of the local pool, rounding up.
1235 return (parallel + 15) / 16
1236 } else if c.totalRAM == 0 {
1237 // Couldn't detect the total RAM, don't restrict highmem processes.
1238 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001239 } else if c.totalRAM <= 16*1024*1024*1024 {
1240 // Less than 16GB of ram, restrict to 1 highmem processes
1241 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001242 } else if c.totalRAM <= 32*1024*1024*1024 {
1243 // Less than 32GB of ram, restrict to 2 highmem processes
1244 return 2
1245 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1246 // If less than 8GB total RAM per process, reduce the number of highmem processes
1247 return p
1248 }
1249 // No restriction on highmem processes
1250 return parallel
1251}
1252
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001253func (c *configImpl) TotalRAM() uint64 {
1254 return c.totalRAM
1255}
1256
Kousik Kumarec478642020-09-21 13:39:24 -04001257// ForceUseGoma determines whether we should override Goma deprecation
1258// and use Goma for the current build or not.
1259func (c *configImpl) ForceUseGoma() bool {
1260 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1261 v = strings.TrimSpace(v)
1262 if v != "" && v != "false" {
1263 return true
1264 }
1265 }
1266 return false
1267}
1268
Dan Willemsen1e704462016-08-21 15:17:17 -07001269func (c *configImpl) UseGoma() bool {
1270 if v, ok := c.environ.Get("USE_GOMA"); ok {
1271 v = strings.TrimSpace(v)
1272 if v != "" && v != "false" {
1273 return true
1274 }
1275 }
1276 return false
1277}
1278
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001279func (c *configImpl) StartGoma() bool {
1280 if !c.UseGoma() {
1281 return false
1282 }
1283
1284 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1285 v = strings.TrimSpace(v)
1286 if v != "" && v != "false" {
1287 return false
1288 }
1289 }
1290 return true
1291}
1292
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001293func (c *configImpl) canSupportRBE() bool {
1294 // Do not use RBE with prod credentials in scenarios when stubby doesn't exist, since
1295 // its unlikely that we will be able to obtain necessary creds without stubby.
1296 authType, _ := c.rbeAuth()
1297 if !c.StubbyExists() && strings.Contains(authType, "use_google_prod_creds") {
1298 return false
1299 }
1300 return true
1301}
1302
Ramy Medhatbbf25672019-07-17 12:30:04 +00001303func (c *configImpl) UseRBE() bool {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001304 // These alternate modes of running Soong do not use RBE / reclient.
Chris Parsons73f411b2023-06-20 21:46:57 +00001305 if c.Bp2Build() || c.Queryview() || c.JsonModuleGraph() {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001306 return false
1307 }
1308
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001309 if !c.canSupportRBE() {
Kousik Kumar67ad4342023-06-06 15:09:27 -04001310 return false
1311 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001312
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001313 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001314 v = strings.TrimSpace(v)
1315 if v != "" && v != "false" {
1316 return true
1317 }
1318 }
1319 return false
1320}
1321
Chris Parsonsef615e52022-08-18 22:04:11 -04001322func (c *configImpl) BazelBuildEnabled() bool {
Chris Parsons21f80272023-06-15 04:02:28 +00001323 return c.bazelProdMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001324}
1325
Ramy Medhatbbf25672019-07-17 12:30:04 +00001326func (c *configImpl) StartRBE() bool {
1327 if !c.UseRBE() {
1328 return false
1329 }
1330
1331 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1332 v = strings.TrimSpace(v)
1333 if v != "" && v != "false" {
1334 return false
1335 }
1336 }
1337 return true
1338}
1339
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001340func (c *configImpl) rbeProxyLogsDir() string {
1341 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001342 if v, ok := c.environ.Get(f); ok {
1343 return v
1344 }
1345 }
Ramy Medhatbc061762023-10-10 18:36:59 +00001346 return c.rbeTmpDir()
1347}
1348
1349func (c *configImpl) rbeDownloadTmpDir() string {
Cole Faust06ea5312023-10-18 17:38:40 -07001350 for _, f := range []string{"RBE_download_tmp_dir", "FLAG_download_tmp_dir"} {
Ramy Medhatbc061762023-10-10 18:36:59 +00001351 if v, ok := c.environ.Get(f); ok {
1352 return v
1353 }
1354 }
1355 return c.rbeTmpDir()
1356}
1357
1358func (c *configImpl) rbeTmpDir() string {
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001359 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1360 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001361}
1362
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001363func (c *configImpl) rbeCacheDir() string {
1364 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1365 if v, ok := c.environ.Get(f); ok {
1366 return v
1367 }
1368 }
1369 return shared.JoinPath(c.SoongOutDir(), "rbe")
1370}
1371
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001372func (c *configImpl) shouldCleanupRBELogsDir() bool {
1373 // Perform a log directory cleanup only when the log directory
1374 // is auto created by the build rather than user-specified.
1375 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1376 if _, ok := c.environ.Get(f); ok {
1377 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001378 }
1379 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001380 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001381}
1382
1383func (c *configImpl) rbeExecRoot() string {
1384 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1385 if v, ok := c.environ.Get(f); ok {
1386 return v
1387 }
1388 }
1389 wd, err := os.Getwd()
1390 if err != nil {
1391 return ""
1392 }
1393 return wd
1394}
1395
1396func (c *configImpl) rbeDir() string {
1397 if v, ok := c.environ.Get("RBE_DIR"); ok {
1398 return v
1399 }
1400 return "prebuilts/remoteexecution-client/live/"
1401}
1402
1403func (c *configImpl) rbeReproxy() string {
1404 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1405 if v, ok := c.environ.Get(f); ok {
1406 return v
1407 }
1408 }
1409 return filepath.Join(c.rbeDir(), "reproxy")
1410}
1411
1412func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001413 credFlags := []string{
1414 "use_application_default_credentials",
1415 "use_gce_credentials",
1416 "credential_file",
1417 "use_google_prod_creds",
1418 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001419 for _, cf := range credFlags {
1420 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1421 if v, ok := c.environ.Get(f); ok {
1422 v = strings.TrimSpace(v)
1423 if v != "" && v != "false" && v != "0" {
1424 return "RBE_" + cf, v
1425 }
1426 }
1427 }
1428 }
1429 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001430}
1431
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001432func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1433 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1434 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1435
1436 name := filepath.Join(dir, base)
1437 if len(name) < maxNameLen {
1438 return name, nil
1439 }
1440
1441 name = filepath.Join("/tmp", base)
1442 if len(name) < maxNameLen {
1443 return name, nil
1444 }
1445
1446 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1447}
1448
Kousik Kumar7bc78192022-04-27 14:52:56 -04001449// IsGooglerEnvironment returns true if the current build is running
1450// on a Google developer machine and false otherwise.
1451func (c *configImpl) IsGooglerEnvironment() bool {
1452 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1453 if v, ok := c.environ.Get(cf); ok {
1454 return v == "googler"
1455 }
1456 return false
1457}
1458
1459// GoogleProdCredsExist determine whether credentials exist on the
1460// Googler machine to use remote execution.
1461func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001462 if googleProdCredsExistCache {
1463 return googleProdCredsExistCache
1464 }
andusyu0b3dc032023-06-21 17:29:32 -04001465 if _, err := exec.Command("/usr/bin/gcertstatus", "-nocheck_ssh").Output(); err != nil {
Kousik Kumar7bc78192022-04-27 14:52:56 -04001466 return false
1467 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001468 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001469 return true
1470}
1471
1472// UseRemoteBuild indicates whether to use a remote build acceleration system
1473// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001474func (c *configImpl) UseRemoteBuild() bool {
1475 return c.UseGoma() || c.UseRBE()
1476}
1477
Kousik Kumar7bc78192022-04-27 14:52:56 -04001478// StubbyExists checks whether the stubby binary exists on the machine running
1479// the build.
1480func (c *configImpl) StubbyExists() bool {
1481 if _, err := exec.LookPath("stubby"); err != nil {
1482 return false
1483 }
1484 return true
1485}
1486
Dan Willemsen1e704462016-08-21 15:17:17 -07001487// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001488// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001489// still limited by Parallel()
1490func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001491 if !c.UseRemoteBuild() {
1492 return 0
1493 }
1494 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1495 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001496 }
1497 return 500
1498}
1499
1500func (c *configImpl) SetKatiArgs(args []string) {
1501 c.katiArgs = args
1502}
1503
1504func (c *configImpl) SetNinjaArgs(args []string) {
1505 c.ninjaArgs = args
1506}
1507
1508func (c *configImpl) SetKatiSuffix(suffix string) {
1509 c.katiSuffix = suffix
1510}
1511
Dan Willemsene0879fc2017-08-04 15:06:27 -07001512func (c *configImpl) LastKatiSuffixFile() string {
1513 return filepath.Join(c.OutDir(), "last_kati_suffix")
1514}
1515
1516func (c *configImpl) HasKatiSuffix() bool {
1517 return c.katiSuffix != ""
1518}
1519
Dan Willemsen1e704462016-08-21 15:17:17 -07001520func (c *configImpl) KatiEnvFile() string {
1521 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1522}
1523
Dan Willemsen29971232018-09-26 14:58:30 -07001524func (c *configImpl) KatiBuildNinjaFile() string {
1525 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001526}
1527
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001528func (c *configImpl) KatiPackageNinjaFile() string {
1529 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1530}
1531
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001532func (c *configImpl) SoongVarsFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001533 targetProduct, err := c.TargetProductOrErr()
1534 if err != nil {
1535 return filepath.Join(c.SoongOutDir(), "soong.variables")
1536 } else {
1537 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+".variables")
1538 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001539}
1540
Dan Willemsen1e704462016-08-21 15:17:17 -07001541func (c *configImpl) SoongNinjaFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001542 targetProduct, err := c.TargetProductOrErr()
1543 if err != nil {
1544 return filepath.Join(c.SoongOutDir(), "build.ninja")
1545 } else {
1546 return filepath.Join(c.SoongOutDir(), "build."+targetProduct+".ninja")
1547 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001548}
1549
1550func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001551 if c.katiSuffix == "" {
1552 return filepath.Join(c.OutDir(), "combined.ninja")
1553 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001554 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1555}
1556
1557func (c *configImpl) SoongAndroidMk() string {
1558 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1559}
1560
1561func (c *configImpl) SoongMakeVarsMk() string {
1562 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1563}
1564
Colin Crossaa9a2732023-10-27 10:54:27 -07001565func (c *configImpl) SoongBuildMetrics() string {
Colin Crossb67b0612023-10-31 10:02:45 -07001566 return filepath.Join(c.LogsDir(), "soong_build_metrics.pb")
Colin Crossaa9a2732023-10-27 10:54:27 -07001567}
1568
Dan Willemsenf052f782017-05-18 15:29:04 -07001569func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001570 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001571}
1572
Dan Willemsen02781d52017-05-12 19:28:13 -07001573func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001574 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1575}
1576
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001577func (c *configImpl) KatiPackageMkDir() string {
1578 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1579}
1580
Dan Willemsenf052f782017-05-18 15:29:04 -07001581func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001582 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001583}
1584
1585func (c *configImpl) HostOut() string {
1586 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1587}
1588
1589// This probably needs to be multi-valued, so not exporting it for now
1590func (c *configImpl) hostCrossOut() string {
1591 if runtime.GOOS == "linux" {
1592 return filepath.Join(c.hostOutRoot(), "windows-x86")
1593 } else {
1594 return ""
1595 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001596}
1597
Dan Willemsen1e704462016-08-21 15:17:17 -07001598func (c *configImpl) HostPrebuiltTag() string {
1599 if runtime.GOOS == "linux" {
1600 return "linux-x86"
1601 } else if runtime.GOOS == "darwin" {
1602 return "darwin-x86"
1603 } else {
1604 panic("Unsupported OS")
1605 }
1606}
Dan Willemsenf173d592017-04-27 14:28:00 -07001607
Dan Willemsen8122bd52017-10-12 20:20:41 -07001608func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001609 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1610 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001611 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1612 if _, err := os.Stat(asan); err == nil {
1613 return asan
1614 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001615 }
1616 }
1617 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1618}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001619
1620func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1621 c.brokenDupRules = val
1622}
1623
1624func (c *configImpl) BuildBrokenDupRules() bool {
1625 return c.brokenDupRules
1626}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001627
Dan Willemsen25e6f092019-04-09 10:22:43 -07001628func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1629 c.brokenUsesNetwork = val
1630}
1631
1632func (c *configImpl) BuildBrokenUsesNetwork() bool {
1633 return c.brokenUsesNetwork
1634}
1635
Dan Willemsene3336352020-01-02 19:10:38 -08001636func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1637 c.brokenNinjaEnvVars = val
1638}
1639
1640func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1641 return c.brokenNinjaEnvVars
1642}
1643
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001644func (c *configImpl) SetTargetDeviceDir(dir string) {
1645 c.targetDeviceDir = dir
1646}
1647
1648func (c *configImpl) TargetDeviceDir() string {
1649 return c.targetDeviceDir
1650}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001651
Patrice Arruda219eef32020-06-01 17:29:30 +00001652func (c *configImpl) BuildDateTime() string {
1653 return c.buildDateTime
1654}
1655
1656func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001657 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001658}
Patrice Arruda83842d72020-12-08 19:42:08 +00001659
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001660// LogsDir returns the absolute path to the logs directory where build log and
1661// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001662// directory. If the argument dist is specified, the logs directory
1663// is <dist_dir>/logs.
1664func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001665 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001666 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001667 // 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 -05001668 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001669 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001670 absDir, err := filepath.Abs(dir)
1671 if err != nil {
1672 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1673 os.Exit(1)
1674 }
1675 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001676}
1677
1678// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1679// where the bazel profiles are located.
1680func (c *configImpl) BazelMetricsDir() string {
1681 return filepath.Join(c.LogsDir(), "bazel_metrics")
1682}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001683
Chris Parsons53f68ae2022-03-03 12:01:40 -05001684// MkFileMetrics returns the file path for make-related metrics.
1685func (c *configImpl) MkMetrics() string {
1686 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1687}
1688
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001689func (c *configImpl) SetEmptyNinjaFile(v bool) {
1690 c.emptyNinjaFile = v
1691}
1692
1693func (c *configImpl) EmptyNinjaFile() bool {
1694 return c.emptyNinjaFile
1695}
Yu Liu6e13b402021-07-27 14:29:06 -07001696
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001697func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1698 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1699}
1700
Chris Parsons9402ca82023-02-23 17:28:06 -05001701func (c *configImpl) IsPersistentBazelEnabled() bool {
1702 return c.Environment().IsEnvTrue("USE_PERSISTENT_BAZEL")
1703}
1704
Chris Parsonsc83398f2023-05-31 18:41:41 +00001705// GetBazeliskBazelVersion returns the Bazel version to use for this build,
1706// or the empty string if the current canonical prod Bazel should be used.
1707// This environment variable should only be set to debug the build system.
1708// The Bazel version, if set, will be passed to Bazelisk, and Bazelisk will
1709// handle downloading and invoking the correct Bazel binary.
1710func (c *configImpl) GetBazeliskBazelVersion() string {
1711 value, _ := c.Environment().Get("USE_BAZEL_VERSION")
1712 return value
1713}
1714
MarkDacekd06db5d2022-11-29 00:47:59 +00001715func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1716 return c.bazelForceEnabledModules
1717}
1718
MarkDacekd0e7cd32022-12-02 22:22:40 +00001719func (c *configImpl) SkipMetricsUpload() bool {
1720 return c.skipMetricsUpload
1721}
1722
MarkDacekf47e1422023-04-19 16:47:36 +00001723func (c *configImpl) EnsureAllowlistIntegrity() bool {
1724 return c.ensureAllowlistIntegrity
1725}
1726
MarkDacek6614d9c2022-12-07 21:57:38 +00001727// Returns a Time object if one was passed via a command-line flag.
1728// Otherwise returns the passed default.
1729func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1730 if c.buildStartedTime == 0 {
1731 return defaultTime
1732 }
1733 return time.UnixMilli(c.buildStartedTime)
1734}
1735
MarkDacekd33c2fd2023-05-04 20:40:04 +00001736func (c *configImpl) BazelExitCode() int32 {
1737 return c.bazelExitCode
1738}
1739
Yu Liu6e13b402021-07-27 14:29:06 -07001740func GetMetricsUploader(topDir string, env *Environment) string {
1741 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1742 metricsUploader := filepath.Join(topDir, p)
1743 if _, err := os.Stat(metricsUploader); err == nil {
1744 return metricsUploader
1745 }
1746 }
1747
1748 return ""
1749}