blob: 52c5e233c5abd8f404458fa9bc4a0a9e8b491cde [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 queryview bool
76 reportMkMetrics bool // Collect and report mk2bp migration progress metrics.
77 soongDocs bool
MarkDacekf47e1422023-04-19 16:47:36 +000078 skipConfig bool
79 skipKati bool
80 skipKatiNinja bool
81 skipSoong bool
82 skipNinja bool
83 skipSoongTests bool
84 searchApiDir bool // Scan the Android.bp files generated in out/api_surfaces
85 skipMetricsUpload bool
86 buildStartedTime int64 // For metrics-upload-only - manually specify a build-started time
Jihoon Kang2a929ad2023-06-08 19:02:07 +000087 buildFromSourceStub bool
Yu Liufa297642024-06-11 00:13:02 +000088 incrementalBuildActions bool
Colin Cross8d411ff2023-12-07 10:31:24 -080089 ensureAllowlistIntegrity bool // For CI builds - make sure modules are mixed-built
Dan Willemsen1e704462016-08-21 15:17:17 -070090
91 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070092 katiArgs []string
93 ninjaArgs []string
94 katiSuffix string
95 targetDevice string
96 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +000097 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -070098
Dan Willemsen2bb82d02019-12-27 09:35:42 -080099 // Autodetected
100 totalRAM uint64
101
Spandan Das28a6f192024-07-01 21:00:25 +0000102 brokenDupRules bool
103 brokenUsesNetwork bool
104 brokenNinjaEnvVars []string
105 brokenMissingOutputs bool
Dan Willemsen18490112018-05-25 16:30:04 -0700106
107 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000108
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700109 // Set by multiproduct_kati
110 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700111
112 metricsUploader string
MarkDacekd06db5d2022-11-29 00:47:59 +0000113
Sam Delmerico98a73292023-02-21 11:50:29 -0500114 includeTags []string
115 sourceRootDirs []string
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900116
117 // Data source to write ninja weight list
118 ninjaWeightListSource NinjaWeightListSource
Joe Onoratoe5ed3472024-02-02 14:52:05 -0800119
120 // This file is a detailed dump of all soong-defined modules for debugging purposes.
121 // There's quite a bit of overlap with module-info.json and soong module graph. We
122 // could consider merging them.
123 moduleDebugFile string
Dan Willemsen1e704462016-08-21 15:17:17 -0700124}
125
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900126type NinjaWeightListSource uint
127
128const (
129 // ninja doesn't use weight list.
130 NOT_USED NinjaWeightListSource = iota
131 // ninja uses weight list based on previous builds by ninja log
132 NINJA_LOG
133 // ninja thinks every task has the same weight.
134 EVENLY_DISTRIBUTED
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900135 // ninja uses an external custom weight list
136 EXTERNAL_FILE
Jeongik Chae114e602023-03-19 00:12:39 +0900137 // ninja uses a prioritized module list from Soong
138 HINT_FROM_SOONG
Jeongik Chaa87506f2023-06-01 23:16:41 +0900139 // If ninja log exists, use NINJA_LOG, if not, use HINT_FROM_SOONG instead.
140 // We can assume it is an incremental build if ninja log exists.
141 DEFAULT
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900142)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800143const srcDirFileCheck = "build/soong/root.bp"
144
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700145var buildFiles = []string{"Android.mk", "Android.bp"}
146
Patrice Arruda13848222019-04-22 17:12:02 -0700147type BuildAction uint
148
149const (
150 // Builds all of the modules and their dependencies of a specified directory, relative to the root
151 // directory of the source tree.
152 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
153
154 // Builds all of the modules and their dependencies of a list of specified directories. All specified
155 // directories are relative to the root directory of the source tree.
156 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700157
158 // Build a list of specified modules. If none was specified, simply build the whole source tree.
159 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700160)
161
162// checkTopDir validates that the current directory is at the root directory of the source tree.
163func checkTopDir(ctx Context) {
164 if _, err := os.Stat(srcDirFileCheck); err != nil {
165 if os.IsNotExist(err) {
166 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
167 }
168 ctx.Fatalln("Error verifying tree state:", err)
169 }
170}
171
MarkDacek7901e582023-01-09 19:48:01 +0000172func loadEnvConfig(ctx Context, config *configImpl, bc string) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500173 if bc == "" {
174 return nil
175 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500176
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500177 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500178 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500179 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500180 envConfigDir,
181 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500182 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500183 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
184 envVarsJSON, err := ioutil.ReadFile(cfgFile)
185 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500186 continue
187 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500188 ctx.Verbosef("Loading config file %v\n", cfgFile)
189 var envVars map[string]map[string]string
190 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
191 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
192 continue
193 }
194 for k, v := range envVars["env"] {
195 if os.Getenv(k) != "" {
196 continue
197 }
198 config.environ.Set(k, v)
199 }
200 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
201 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500202 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500203
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500204 return nil
205}
206
Dan Willemsen1e704462016-08-21 15:17:17 -0700207func NewConfig(ctx Context, args ...string) Config {
208 ret := &configImpl{
Jeongik Chaf2ecf762023-05-19 14:03:45 +0900209 environ: OsEnvironment(),
210 sandboxConfig: &SandboxConfig{},
Jeongik Chaa87506f2023-06-01 23:16:41 +0900211 ninjaWeightListSource: DEFAULT,
Dan Willemsen1e704462016-08-21 15:17:17 -0700212 }
213
Colin Cross106d6ef2023-10-24 10:34:56 -0700214 // Skip soong tests by default on Linux
215 if runtime.GOOS == "linux" {
216 ret.skipSoongTests = true
217 }
218
Patrice Arruda90109172020-07-28 18:07:27 +0000219 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700220 ret.parallel = runtime.NumCPU() + 2
221 ret.keepGoing = 1
222
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800223 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700224 ret.parseArgs(ctx, args)
Jeongik Chae114e602023-03-19 00:12:39 +0900225
226 if ret.ninjaWeightListSource == HINT_FROM_SOONG {
Jeongik Chaa87506f2023-06-01 23:16:41 +0900227 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "always")
228 } else if ret.ninjaWeightListSource == DEFAULT {
229 defaultNinjaWeightListSource := NINJA_LOG
230 if _, err := os.Stat(filepath.Join(ret.OutDir(), ninjaLogFileName)); errors.Is(err, os.ErrNotExist) {
231 ctx.Verboseln("$OUT/.ninja_log doesn't exist, use HINT_FROM_SOONG instead")
232 defaultNinjaWeightListSource = HINT_FROM_SOONG
233 } else {
234 ctx.Verboseln("$OUT/.ninja_log exist, use NINJA_LOG")
235 }
236 ret.ninjaWeightListSource = defaultNinjaWeightListSource
237 // soong_build generates ninja hint depending on ninja log existence.
238 // Set it "depend" to avoid soong re-run due to env variable change.
239 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "depend")
Jeongik Chae114e602023-03-19 00:12:39 +0900240 }
Jeongik Chaa87506f2023-06-01 23:16:41 +0900241
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800242 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700243 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
244 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
245 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800246 outDir := "out"
247 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
248 if wd, err := os.Getwd(); err != nil {
249 ctx.Fatalln("Failed to get working directory:", err)
250 } else {
251 outDir = filepath.Join(baseDir, filepath.Base(wd))
252 }
253 }
254 ret.environ.Set("OUT_DIR", outDir)
255 }
256
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500257 // loadEnvConfig needs to know what the OUT_DIR is, so it should
258 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000259 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
260
261 if bc != "" {
Kousik Kumarc8818332023-01-16 16:33:05 +0000262 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000263 ctx.Fatalln("Failed to parse env config files: %v", err)
264 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +0000265 if !ret.canSupportRBE() {
266 // Explicitly set USE_RBE env variable to false when we cannot run
267 // an RBE build to avoid ninja local execution pool issues.
268 ret.environ.Set("USE_RBE", "false")
269 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500270 }
271
Dan Willemsen2d31a442018-10-20 21:33:41 -0700272 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
273 ret.distDir = filepath.Clean(distDir)
274 } else {
275 ret.distDir = filepath.Join(ret.OutDir(), "dist")
276 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700277
Spandan Das05063612021-06-25 01:39:04 +0000278 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
279 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
280 }
281
Joe Onoratoe5ed3472024-02-02 14:52:05 -0800282 if os.Getenv("GENERATE_SOONG_DEBUG") == "true" {
283 ret.moduleDebugFile, _ = filepath.Abs(shared.JoinPath(ret.SoongOutDir(), "soong-debug-info.json"))
284 }
285
Dan Willemsen1e704462016-08-21 15:17:17 -0700286 ret.environ.Unset(
287 // We're already using it
288 "USE_SOONG_UI",
289
290 // We should never use GOROOT/GOPATH from the shell environment
291 "GOROOT",
292 "GOPATH",
293
294 // These should only come from Soong, not the environment.
295 "CLANG",
296 "CLANG_CXX",
297 "CCC_CC",
298 "CCC_CXX",
299
300 // Used by the goma compiler wrapper, but should only be set by
301 // gomacc
302 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800303
304 // We handle this above
305 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700306
Dan Willemsen2d31a442018-10-20 21:33:41 -0700307 // This is handled above too, and set for individual commands later
308 "DIST_DIR",
309
Dan Willemsen68a09852017-04-18 13:56:57 -0700310 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000311 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700312 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700313 "DISPLAY",
314 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000315 "JAVAC",
Nathan Egge978c9342024-07-03 21:13:03 +0000316 "LEX",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700317 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700318 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700319
320 // Drop make flags
321 "MAKEFLAGS",
322 "MAKELEVEL",
323 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700324
325 // Set in envsetup.sh, reset in makefiles
326 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700327
328 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
329 "ANDROID_BUILD_TOP",
330 "ANDROID_HOST_OUT",
331 "ANDROID_PRODUCT_OUT",
332 "ANDROID_HOST_OUT_TESTCASES",
333 "ANDROID_TARGET_OUT_TESTCASES",
334 "ANDROID_TOOLCHAIN",
335 "ANDROID_TOOLCHAIN_2ND_ARCH",
336 "ANDROID_DEV_SCRIPTS",
337 "ANDROID_EMULATOR_PREBUILTS",
338 "ANDROID_PRE_BUILD_PATHS",
Joe Onoratoe5ed3472024-02-02 14:52:05 -0800339
340 // We read it here already, don't let others share in the fun
341 "GENERATE_SOONG_DEBUG",
Dan Willemsen1e704462016-08-21 15:17:17 -0700342 )
343
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400344 if ret.UseGoma() || ret.ForceUseGoma() {
345 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
346 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400347 }
348
Dan Willemsen1e704462016-08-21 15:17:17 -0700349 // Tell python not to spam the source tree with .pyc files.
350 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
351
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400352 tmpDir := absPath(ctx, ret.TempDir())
353 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800354
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700355 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
356 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
357 "llvm-binutils-stable/llvm-symbolizer")
358 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
359
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800360 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700361 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800362
Yu Liu6e13b402021-07-27 14:29:06 -0700363 srcDir := absPath(ctx, ".")
364 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700365 ctx.Println("You are building in a directory whose absolute path contains a space character:")
366 ctx.Println()
367 ctx.Printf("%q\n", srcDir)
368 ctx.Println()
369 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700370 }
371
Yu Liu6e13b402021-07-27 14:29:06 -0700372 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
373
Dan Willemsendb8457c2017-05-12 16:38:17 -0700374 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700375 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
376 ctx.Println()
377 ctx.Printf("%q\n", outDir)
378 ctx.Println()
379 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700380 }
381
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000382 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700383 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
384 ctx.Println()
385 ctx.Printf("%q\n", distDir)
386 ctx.Println()
387 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700388 }
389
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700390 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000391 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
Sorin Basca0760c892023-11-29 19:13:55 +0000392 java21Home := filepath.Join("prebuilts/jdk/jdk21", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700393 javaHome := func() string {
394 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
395 return override
396 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000397 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
Sorin Basca5dfa2382024-03-11 17:23:06 +0000398 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN is no longer supported. An OpenJDK 21 toolchain is now the global default.")
Pete Gillin1f52e932019-10-09 17:10:08 +0100399 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000400 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
Sorin Basca5dfa2382024-03-11 17:23:06 +0000401 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 21 toolchain is now the global default.")
Sorin Basca7e094b32022-10-05 08:20:12 +0000402 }
Sorin Basca5dfa2382024-03-11 17:23:06 +0000403 if toolchain21, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK21_TOOLCHAIN"); ok && toolchain21 != "true" {
404 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK21_TOOLCHAIN is no longer supported. An OpenJDK 21 toolchain is now the global default.")
405 }
406 return java21Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700407 }()
408 absJavaHome := absPath(ctx, javaHome)
409
Dan Willemsened869522018-01-08 14:58:46 -0800410 ret.configureLocale(ctx)
411
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700412 newPath := []string{filepath.Join(absJavaHome, "bin")}
413 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
414 newPath = append(newPath, path)
415 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100416
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700417 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
418 ret.environ.Set("JAVA_HOME", absJavaHome)
419 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000420 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700421 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
422
Colin Crossfe5ed4d2023-07-28 09:27:23 -0700423 // b/286885495, https://bugzilla.redhat.com/show_bug.cgi?id=2227130: some versions of Fedora include patches
424 // to unzip to enable zipbomb detection that incorrectly handle zip64 and data descriptors and fail on large
425 // zip files produced by soong_zip. Disable zipbomb detection.
426 ret.environ.Set("UNZIP_DISABLE_ZIPBOMB_DETECTION", "TRUE")
427
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800428 outDir := ret.OutDir()
429 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800430 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800431 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800432 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800433 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800434 }
Colin Cross28f527c2019-11-26 16:19:04 -0800435
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800436 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
437
Cole Faust583dfb42023-09-28 13:56:30 -0700438 if _, ok := ret.environ.Get("BUILD_USERNAME"); !ok {
439 username := "unknown"
440 if u, err := user.Current(); err == nil {
441 username = u.Username
442 } else {
443 ctx.Println("Failed to get current user:", err)
444 }
445 ret.environ.Set("BUILD_USERNAME", username)
446 }
447
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400448 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400449 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400450 ret.environ.Set(k, v)
451 }
452 }
453
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{
Colin Cross8d411ff2023-12-07 10:31:24 -0800534 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
535 UseGoma: proto.Bool(config.UseGoma()),
536 UseRbe: proto.Bool(config.UseRBE()),
537 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400538 }
Yu Liue737a992021-10-04 13:21:41 -0700539 c.Targets = append(c.Targets, config.arguments...)
540
541 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400542}
543
Patrice Arruda13848222019-04-22 17:12:02 -0700544// getConfigArgs processes the command arguments based on the build action and creates a set of new
545// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700546func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700547 // The next block of code verifies that the current directory is the root directory of the source
548 // tree. It then finds the relative path of dir based on the root directory of the source tree
549 // and verify that dir is inside of the source tree.
550 checkTopDir(ctx)
551 topDir, err := os.Getwd()
552 if err != nil {
553 ctx.Fatalf("Error retrieving top directory: %v", err)
554 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700555 dir, err = filepath.EvalSymlinks(dir)
556 if err != nil {
557 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
558 }
Patrice Arruda13848222019-04-22 17:12:02 -0700559 dir, err = filepath.Abs(dir)
560 if err != nil {
561 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
562 }
563 relDir, err := filepath.Rel(topDir, dir)
564 if err != nil {
565 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
566 }
567 // If there are ".." in the path, it's not in the source tree.
568 if strings.Contains(relDir, "..") {
569 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
570 }
571
572 configArgs := args[:]
573
574 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
575 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
576 targetNamePrefix := "MODULES-IN-"
577 if inList("GET-INSTALL-PATH", configArgs) {
578 targetNamePrefix = "GET-INSTALL-PATH-IN-"
579 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
580 }
581
Patrice Arruda13848222019-04-22 17:12:02 -0700582 var targets []string
583
584 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700585 case BUILD_MODULES:
586 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700587 case BUILD_MODULES_IN_A_DIRECTORY:
588 // If dir is the root source tree, all the modules are built of the source tree are built so
589 // no need to find the build file.
590 if topDir == dir {
591 break
592 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700593
Patrice Arruda13848222019-04-22 17:12:02 -0700594 buildFile := findBuildFile(ctx, relDir)
595 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700596 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700597 }
Patrice Arruda13848222019-04-22 17:12:02 -0700598 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
599 case BUILD_MODULES_IN_DIRECTORIES:
600 newConfigArgs, dirs := splitArgs(configArgs)
601 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700602 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700603 }
604
605 // Tidy only override all other specified targets.
606 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
607 if tidyOnly == "true" || tidyOnly == "1" {
608 configArgs = append(configArgs, "tidy_only")
609 } else {
610 configArgs = append(configArgs, targets...)
611 }
612
613 return configArgs
614}
615
616// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
617func convertToTarget(dir string, targetNamePrefix string) string {
618 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
619}
620
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700621// hasBuildFile returns true if dir contains an Android build file.
622func hasBuildFile(ctx Context, dir string) bool {
623 for _, buildFile := range buildFiles {
624 _, err := os.Stat(filepath.Join(dir, buildFile))
625 if err == nil {
626 return true
627 }
628 if !os.IsNotExist(err) {
629 ctx.Fatalf("Error retrieving the build file stats: %v", err)
630 }
631 }
632 return false
633}
634
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700635// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
636// in the current and any sub directory of dir. If a build file is not found, traverse the path
637// up by one directory and repeat again until either a build file is found or reached to the root
638// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
639// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700640func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700641 // If the string is empty or ".", assume it is top directory of the source tree.
642 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700643 return ""
644 }
645
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700646 found := false
647 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
648 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
649 if err != nil {
650 return err
651 }
652 if found {
653 return filepath.SkipDir
654 }
655 if info.IsDir() {
656 return nil
657 }
658 for _, buildFile := range buildFiles {
659 if info.Name() == buildFile {
660 found = true
661 return filepath.SkipDir
662 }
663 }
664 return nil
665 })
666 if err != nil {
667 ctx.Fatalf("Error finding Android build file: %v", err)
668 }
669
670 if found {
671 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700672 }
673 }
674
675 return ""
676}
677
678// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
679func splitArgs(args []string) (newArgs []string, dirs []string) {
680 specialArgs := map[string]bool{
681 "showcommands": true,
682 "snod": true,
683 "dist": true,
684 "checkbuild": true,
685 }
686
687 newArgs = []string{}
688 dirs = []string{}
689
690 for _, arg := range args {
691 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
692 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
693 newArgs = append(newArgs, arg)
694 continue
695 }
696
697 if _, ok := specialArgs[arg]; ok {
698 newArgs = append(newArgs, arg)
699 continue
700 }
701
702 dirs = append(dirs, arg)
703 }
704
705 return newArgs, dirs
706}
707
708// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
709// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
710// source root tree where the build action command was invoked. Each directory is validated if the
711// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700712func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700713 for _, dir := range dirs {
714 // The directory may have specified specific modules to build. ":" is the separator to separate
715 // the directory and the list of modules.
716 s := strings.Split(dir, ":")
717 l := len(s)
718 if l > 2 { // more than one ":" was specified.
719 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
720 }
721
722 dir = filepath.Join(relDir, s[0])
723 if _, err := os.Stat(dir); err != nil {
724 ctx.Fatalf("couldn't find directory %s", dir)
725 }
726
727 // Verify that if there are any targets specified after ":". Each target is separated by ",".
728 var newTargets []string
729 if l == 2 && s[1] != "" {
730 newTargets = strings.Split(s[1], ",")
731 if inList("", newTargets) {
732 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
733 }
734 }
735
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700736 // If there are specified targets to build in dir, an android build file must exist for the one
737 // shot build. For the non-targets case, find the appropriate build file and build all the
738 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700739 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700740 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700741 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
742 }
743 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700744 buildFile := findBuildFile(ctx, dir)
745 if buildFile == "" {
746 ctx.Fatalf("Build file not found for %s directory", dir)
747 }
748 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700749 }
750
Patrice Arruda13848222019-04-22 17:12:02 -0700751 targets = append(targets, newTargets...)
752 }
753
Dan Willemsence41e942019-07-29 23:39:30 -0700754 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700755}
756
Dan Willemsen9b587492017-07-10 22:13:00 -0700757func (c *configImpl) parseArgs(ctx Context, args []string) {
758 for i := 0; i < len(args); i++ {
759 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100760 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700761 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200762 } else if arg == "--empty-ninja-file" {
763 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100764 } else if arg == "--skip-ninja" {
765 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700766 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700767 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
768 // but it does run a Kati ninja file if the .kati_enabled marker file was created
769 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000770 c.skipConfig = true
771 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100772 } else if arg == "--soong-only" {
773 c.skipKati = true
774 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200775 } else if arg == "--config-only" {
776 c.skipKati = true
777 c.skipKatiNinja = true
778 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700779 } else if arg == "--skip-config" {
780 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700781 } else if arg == "--skip-soong-tests" {
782 c.skipSoongTests = true
Colin Cross106d6ef2023-10-24 10:34:56 -0700783 } else if arg == "--no-skip-soong-tests" {
784 c.skipSoongTests = false
MarkDacekd0e7cd32022-12-02 22:22:40 +0000785 } else if arg == "--skip-metrics-upload" {
786 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500787 } else if arg == "--mk-metrics" {
788 c.reportMkMetrics = true
Spandan Das394aa322022-11-03 17:02:10 +0000789 } else if arg == "--search-api-dir" {
790 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900791 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
792 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
793 if source == "ninja_log" {
794 c.ninjaWeightListSource = NINJA_LOG
795 } else if source == "evenly_distributed" {
796 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
797 } else if source == "not_used" {
798 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900799 } else if source == "soong" {
800 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900801 } else if strings.HasPrefix(source, "file,") {
802 c.ninjaWeightListSource = EXTERNAL_FILE
803 filePath := strings.TrimPrefix(source, "file,")
804 err := validateNinjaWeightList(filePath)
805 if err != nil {
806 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
807 }
808 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
809 if err != nil {
810 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
811 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900812 } else {
813 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
814 }
Jihoon Kang2a929ad2023-06-08 19:02:07 +0000815 } else if arg == "--build-from-source-stub" {
816 c.buildFromSourceStub = true
Yu Liufa297642024-06-11 00:13:02 +0000817 } else if arg == "--incremental-build-actions" {
818 c.incrementalBuildActions = true
MarkDacekb96561e2022-12-02 04:34:43 +0000819 } else if strings.HasPrefix(arg, "--build-command=") {
820 buildCmd := strings.TrimPrefix(arg, "--build-command=")
821 // remove quotations
822 buildCmd = strings.TrimPrefix(buildCmd, "\"")
823 buildCmd = strings.TrimSuffix(buildCmd, "\"")
824 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacek6614d9c2022-12-07 21:57:38 +0000825 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
826 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
827 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
828 if err == nil {
829 c.buildStartedTime = val
830 } else {
831 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
832 }
MarkDacekf47e1422023-04-19 16:47:36 +0000833 } else if arg == "--ensure-allowlist-integrity" {
834 c.ensureAllowlistIntegrity = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700835 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700836 parseArgNum := func(def int) int {
837 if len(arg) > 2 {
838 p, err := strconv.ParseUint(arg[2:], 10, 31)
839 if err != nil {
840 ctx.Fatalf("Failed to parse %q: %v", arg, err)
841 }
842 return int(p)
843 } else if i+1 < len(args) {
844 p, err := strconv.ParseUint(args[i+1], 10, 31)
845 if err == nil {
846 i++
847 return int(p)
848 }
849 }
850 return def
851 }
852
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700853 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700854 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700855 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700856 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700857 } else {
858 ctx.Fatalln("Unknown option:", arg)
859 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700860 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700861 if k == "OUT_DIR" {
862 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
863 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700864 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700865 } else if arg == "dist" {
866 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200867 } else if arg == "json-module-graph" {
868 c.jsonModuleGraph = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200869 } else if arg == "queryview" {
870 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200871 } else if arg == "soong_docs" {
872 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700873 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700874 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800875 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700876 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700877 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700878 }
879 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700880}
881
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900882func validateNinjaWeightList(weightListFilePath string) (err error) {
883 data, err := os.ReadFile(weightListFilePath)
884 if err != nil {
885 return
886 }
887 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
888 for _, line := range lines {
889 fields := strings.Split(line, ",")
890 if len(fields) != 2 {
891 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
892 }
893 _, err = strconv.Atoi(fields[1])
894 if err != nil {
895 return
896 }
897 }
898 return
899}
900
Dan Willemsened869522018-01-08 14:58:46 -0800901func (c *configImpl) configureLocale(ctx Context) {
902 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
903 output, err := cmd.Output()
904
905 var locales []string
906 if err == nil {
907 locales = strings.Split(string(output), "\n")
908 } else {
909 // If we're unable to list the locales, let's assume en_US.UTF-8
910 locales = []string{"en_US.UTF-8"}
911 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
912 }
913
914 // gettext uses LANGUAGE, which is passed directly through
915
916 // For LANG and LC_*, only preserve the evaluated version of
917 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800918 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800919 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800920 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800921 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800922 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800923 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800924 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800925 }
926
927 c.environ.UnsetWithPrefix("LC_")
928
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800929 if userLang != "" {
930 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800931 }
932
933 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
934 // for others)
935 if inList("C.UTF-8", locales) {
936 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500937 } else if inList("C.utf8", locales) {
938 // These normalize to the same thing
939 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800940 } else if inList("en_US.UTF-8", locales) {
941 c.environ.Set("LANG", "en_US.UTF-8")
942 } else if inList("en_US.utf8", locales) {
943 // These normalize to the same thing
944 c.environ.Set("LANG", "en_US.UTF-8")
945 } else {
946 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
947 }
948}
949
Dan Willemsen1e704462016-08-21 15:17:17 -0700950func (c *configImpl) Environment() *Environment {
951 return c.environ
952}
953
954func (c *configImpl) Arguments() []string {
955 return c.arguments
956}
957
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200958func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200959 if len(c.Arguments()) > 0 {
960 // Explicit targets requested that are not special targets like b2pbuild
961 // or the JSON module graph
962 return true
963 }
964
Colin Cross8d411ff2023-12-07 10:31:24 -0800965 if !c.JsonModuleGraph() && !c.Queryview() && !c.SoongDocs() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200966 // Command line was empty, the default Ninja target is built
967 return true
968 }
969
Colin Cross8d411ff2023-12-07 10:31:24 -0800970 if c.Dist() {
Liz Kammer88677422021-12-15 15:03:19 -0500971 return true
972 }
973
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200974 // build.ninja doesn't need to be generated
975 return false
976}
977
Dan Willemsen1e704462016-08-21 15:17:17 -0700978func (c *configImpl) OutDir() string {
979 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700980 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700981 }
982 return "out"
983}
984
Dan Willemsen8a073a82017-02-04 17:30:44 -0800985func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400986 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000987}
988
989func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700990 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800991}
992
Dan Willemsen1e704462016-08-21 15:17:17 -0700993func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000994 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700995 return c.arguments
996 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700997 return c.ninjaArgs
998}
999
1000func (c *configImpl) SoongOutDir() string {
1001 return filepath.Join(c.OutDir(), "soong")
1002}
1003
Spandan Das394aa322022-11-03 17:02:10 +00001004func (c *configImpl) ApiSurfacesOutDir() string {
1005 return filepath.Join(c.OutDir(), "api_surfaces")
1006}
1007
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001008func (c *configImpl) PrebuiltOS() string {
1009 switch runtime.GOOS {
1010 case "linux":
1011 return "linux-x86"
1012 case "darwin":
1013 return "darwin-x86"
1014 default:
1015 panic("Unknown GOOS")
1016 }
1017}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001018
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001019func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001020 if c.SkipKatiNinja() {
1021 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1022 } else {
1023 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1024 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001025}
1026
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001027func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001028 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001029}
1030
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001031func (c *configImpl) UsedEnvFile(tag string) string {
Kiyoung Kimeaa55a82023-06-05 16:56:49 +09001032 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1033 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+v+"."+tag)
1034 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001035 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1036}
1037
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001038func (c *configImpl) SoongDocsHtml() string {
1039 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1040}
1041
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001042func (c *configImpl) QueryviewMarkerFile() string {
1043 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1044}
1045
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001046func (c *configImpl) ModuleGraphFile() string {
1047 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1048}
1049
kgui67007242022-01-25 13:50:25 +08001050func (c *configImpl) ModuleActionsFile() string {
1051 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1052}
1053
Jeff Gastonefc1b412017-03-29 17:29:06 -07001054func (c *configImpl) TempDir() string {
1055 return shared.TempDirForOutDir(c.SoongOutDir())
1056}
1057
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001058func (c *configImpl) FileListDir() string {
1059 return filepath.Join(c.OutDir(), ".module_paths")
1060}
1061
Dan Willemsen1e704462016-08-21 15:17:17 -07001062func (c *configImpl) KatiSuffix() string {
1063 if c.katiSuffix != "" {
1064 return c.katiSuffix
1065 }
1066 panic("SetKatiSuffix has not been called")
1067}
1068
Colin Cross37193492017-11-16 17:55:00 -08001069// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1070// user is interested in additional checks at the expense of build time.
1071func (c *configImpl) Checkbuild() bool {
1072 return c.checkbuild
1073}
1074
Dan Willemsen8a073a82017-02-04 17:30:44 -08001075func (c *configImpl) Dist() bool {
1076 return c.dist
1077}
1078
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001079func (c *configImpl) JsonModuleGraph() bool {
1080 return c.jsonModuleGraph
1081}
1082
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001083func (c *configImpl) Queryview() bool {
1084 return c.queryview
1085}
1086
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001087func (c *configImpl) SoongDocs() bool {
1088 return c.soongDocs
1089}
1090
Dan Willemsen1e704462016-08-21 15:17:17 -07001091func (c *configImpl) IsVerbose() bool {
1092 return c.verbose
1093}
1094
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001095func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1096 return c.ninjaWeightListSource
1097}
1098
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001099func (c *configImpl) SkipKati() bool {
1100 return c.skipKati
1101}
1102
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001103func (c *configImpl) SkipKatiNinja() bool {
1104 return c.skipKatiNinja
1105}
1106
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001107func (c *configImpl) SkipSoong() bool {
1108 return c.skipSoong
1109}
1110
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001111func (c *configImpl) SkipNinja() bool {
1112 return c.skipNinja
1113}
1114
Anton Hansson5a7861a2021-06-04 10:09:01 +01001115func (c *configImpl) SetSkipNinja(v bool) {
1116 c.skipNinja = v
1117}
1118
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001119func (c *configImpl) SkipConfig() bool {
1120 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001121}
1122
Jihoon Kang1bff0342023-01-17 20:40:22 +00001123func (c *configImpl) BuildFromTextStub() bool {
Jihoon Kang2a929ad2023-06-08 19:02:07 +00001124 return !c.buildFromSourceStub
Jihoon Kang1bff0342023-01-17 20:40:22 +00001125}
1126
Dan Willemsen1e704462016-08-21 15:17:17 -07001127func (c *configImpl) TargetProduct() string {
1128 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1129 return v
1130 }
1131 panic("TARGET_PRODUCT is not defined")
1132}
1133
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001134func (c *configImpl) TargetProductOrErr() (string, error) {
1135 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1136 return v, nil
1137 }
1138 return "", fmt.Errorf("TARGET_PRODUCT is not defined")
1139}
1140
Dan Willemsen02781d52017-05-12 19:28:13 -07001141func (c *configImpl) TargetDevice() string {
1142 return c.targetDevice
1143}
1144
1145func (c *configImpl) SetTargetDevice(device string) {
1146 c.targetDevice = device
1147}
1148
1149func (c *configImpl) TargetBuildVariant() string {
1150 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1151 return v
1152 }
1153 panic("TARGET_BUILD_VARIANT is not defined")
1154}
1155
Dan Willemsen1e704462016-08-21 15:17:17 -07001156func (c *configImpl) KatiArgs() []string {
1157 return c.katiArgs
1158}
1159
1160func (c *configImpl) Parallel() int {
1161 return c.parallel
1162}
1163
Sam Delmerico98a73292023-02-21 11:50:29 -05001164func (c *configImpl) GetSourceRootDirs() []string {
1165 return c.sourceRootDirs
1166}
1167
1168func (c *configImpl) SetSourceRootDirs(i []string) {
1169 c.sourceRootDirs = i
1170}
1171
MarkDacek6614d9c2022-12-07 21:57:38 +00001172func (c *configImpl) GetLogsPrefix() string {
1173 return c.logsPrefix
1174}
1175
1176func (c *configImpl) SetLogsPrefix(prefix string) {
1177 c.logsPrefix = prefix
1178}
1179
Colin Cross8b8bec32019-11-15 13:18:43 -08001180func (c *configImpl) HighmemParallel() int {
1181 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1182 return i
1183 }
1184
1185 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1186 parallel := c.Parallel()
1187 if c.UseRemoteBuild() {
1188 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1189 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1190 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1191 // Return 1/16th of the size of the local pool, rounding up.
1192 return (parallel + 15) / 16
1193 } else if c.totalRAM == 0 {
1194 // Couldn't detect the total RAM, don't restrict highmem processes.
1195 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001196 } else if c.totalRAM <= 16*1024*1024*1024 {
1197 // Less than 16GB of ram, restrict to 1 highmem processes
1198 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001199 } else if c.totalRAM <= 32*1024*1024*1024 {
1200 // Less than 32GB of ram, restrict to 2 highmem processes
1201 return 2
1202 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1203 // If less than 8GB total RAM per process, reduce the number of highmem processes
1204 return p
1205 }
1206 // No restriction on highmem processes
1207 return parallel
1208}
1209
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001210func (c *configImpl) TotalRAM() uint64 {
1211 return c.totalRAM
1212}
1213
Kousik Kumarec478642020-09-21 13:39:24 -04001214// ForceUseGoma determines whether we should override Goma deprecation
1215// and use Goma for the current build or not.
1216func (c *configImpl) ForceUseGoma() bool {
1217 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1218 v = strings.TrimSpace(v)
1219 if v != "" && v != "false" {
1220 return true
1221 }
1222 }
1223 return false
1224}
1225
Dan Willemsen1e704462016-08-21 15:17:17 -07001226func (c *configImpl) UseGoma() bool {
1227 if v, ok := c.environ.Get("USE_GOMA"); ok {
1228 v = strings.TrimSpace(v)
1229 if v != "" && v != "false" {
1230 return true
1231 }
1232 }
1233 return false
1234}
1235
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001236func (c *configImpl) StartGoma() bool {
1237 if !c.UseGoma() {
1238 return false
1239 }
1240
1241 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1242 v = strings.TrimSpace(v)
1243 if v != "" && v != "false" {
1244 return false
1245 }
1246 }
1247 return true
1248}
1249
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001250func (c *configImpl) canSupportRBE() bool {
Joe Onorato86f50e72024-06-24 14:28:25 -07001251 // Only supported on linux
1252 if runtime.GOOS != "linux" {
1253 return false
1254 }
1255
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001256 // Do not use RBE with prod credentials in scenarios when stubby doesn't exist, since
1257 // its unlikely that we will be able to obtain necessary creds without stubby.
1258 authType, _ := c.rbeAuth()
1259 if !c.StubbyExists() && strings.Contains(authType, "use_google_prod_creds") {
1260 return false
1261 }
1262 return true
1263}
1264
Ramy Medhatbbf25672019-07-17 12:30:04 +00001265func (c *configImpl) UseRBE() bool {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001266 // These alternate modes of running Soong do not use RBE / reclient.
Colin Cross8d411ff2023-12-07 10:31:24 -08001267 if c.Queryview() || c.JsonModuleGraph() {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001268 return false
1269 }
1270
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001271 if !c.canSupportRBE() {
Kousik Kumar67ad4342023-06-06 15:09:27 -04001272 return false
1273 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001274
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001275 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001276 v = strings.TrimSpace(v)
1277 if v != "" && v != "false" {
1278 return true
1279 }
1280 }
1281 return false
1282}
1283
1284func (c *configImpl) StartRBE() bool {
1285 if !c.UseRBE() {
1286 return false
1287 }
1288
1289 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1290 v = strings.TrimSpace(v)
1291 if v != "" && v != "false" {
1292 return false
1293 }
1294 }
1295 return true
1296}
1297
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001298func (c *configImpl) rbeProxyLogsDir() string {
1299 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001300 if v, ok := c.environ.Get(f); ok {
1301 return v
1302 }
1303 }
Ramy Medhatbc061762023-10-10 18:36:59 +00001304 return c.rbeTmpDir()
1305}
1306
1307func (c *configImpl) rbeDownloadTmpDir() string {
Cole Faust06ea5312023-10-18 17:38:40 -07001308 for _, f := range []string{"RBE_download_tmp_dir", "FLAG_download_tmp_dir"} {
Ramy Medhatbc061762023-10-10 18:36:59 +00001309 if v, ok := c.environ.Get(f); ok {
1310 return v
1311 }
1312 }
1313 return c.rbeTmpDir()
1314}
1315
1316func (c *configImpl) rbeTmpDir() string {
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001317 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1318 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001319}
1320
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001321func (c *configImpl) rbeCacheDir() string {
1322 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1323 if v, ok := c.environ.Get(f); ok {
1324 return v
1325 }
1326 }
1327 return shared.JoinPath(c.SoongOutDir(), "rbe")
1328}
1329
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001330func (c *configImpl) shouldCleanupRBELogsDir() bool {
1331 // Perform a log directory cleanup only when the log directory
1332 // is auto created by the build rather than user-specified.
1333 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1334 if _, ok := c.environ.Get(f); ok {
1335 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001336 }
1337 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001338 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001339}
1340
1341func (c *configImpl) rbeExecRoot() string {
1342 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1343 if v, ok := c.environ.Get(f); ok {
1344 return v
1345 }
1346 }
1347 wd, err := os.Getwd()
1348 if err != nil {
1349 return ""
1350 }
1351 return wd
1352}
1353
1354func (c *configImpl) rbeDir() string {
1355 if v, ok := c.environ.Get("RBE_DIR"); ok {
1356 return v
1357 }
1358 return "prebuilts/remoteexecution-client/live/"
1359}
1360
1361func (c *configImpl) rbeReproxy() string {
1362 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1363 if v, ok := c.environ.Get(f); ok {
1364 return v
1365 }
1366 }
1367 return filepath.Join(c.rbeDir(), "reproxy")
1368}
1369
1370func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001371 credFlags := []string{
1372 "use_application_default_credentials",
1373 "use_gce_credentials",
1374 "credential_file",
1375 "use_google_prod_creds",
1376 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001377 for _, cf := range credFlags {
1378 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1379 if v, ok := c.environ.Get(f); ok {
1380 v = strings.TrimSpace(v)
1381 if v != "" && v != "false" && v != "0" {
1382 return "RBE_" + cf, v
1383 }
1384 }
1385 }
1386 }
1387 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001388}
1389
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001390func (c *configImpl) rbeSockAddr(dir string) (string, error) {
Andus Yuc917eb82024-03-06 21:54:15 +00001391 // Absolute path socket addresses have a prefix of //. This should
1392 // be included in the length limit.
1393 maxNameLen := len(syscall.RawSockaddrUnix{}.Path) - 2
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001394 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1395
1396 name := filepath.Join(dir, base)
1397 if len(name) < maxNameLen {
1398 return name, nil
1399 }
1400
1401 name = filepath.Join("/tmp", base)
1402 if len(name) < maxNameLen {
1403 return name, nil
1404 }
1405
1406 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1407}
1408
Kousik Kumar7bc78192022-04-27 14:52:56 -04001409// IsGooglerEnvironment returns true if the current build is running
1410// on a Google developer machine and false otherwise.
1411func (c *configImpl) IsGooglerEnvironment() bool {
1412 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1413 if v, ok := c.environ.Get(cf); ok {
1414 return v == "googler"
1415 }
1416 return false
1417}
1418
1419// GoogleProdCredsExist determine whether credentials exist on the
1420// Googler machine to use remote execution.
1421func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001422 if googleProdCredsExistCache {
1423 return googleProdCredsExistCache
1424 }
andusyu0b3dc032023-06-21 17:29:32 -04001425 if _, err := exec.Command("/usr/bin/gcertstatus", "-nocheck_ssh").Output(); err != nil {
Kousik Kumar7bc78192022-04-27 14:52:56 -04001426 return false
1427 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001428 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001429 return true
1430}
1431
1432// UseRemoteBuild indicates whether to use a remote build acceleration system
1433// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001434func (c *configImpl) UseRemoteBuild() bool {
1435 return c.UseGoma() || c.UseRBE()
1436}
1437
Kousik Kumar7bc78192022-04-27 14:52:56 -04001438// StubbyExists checks whether the stubby binary exists on the machine running
1439// the build.
1440func (c *configImpl) StubbyExists() bool {
1441 if _, err := exec.LookPath("stubby"); err != nil {
1442 return false
1443 }
1444 return true
1445}
1446
Dan Willemsen1e704462016-08-21 15:17:17 -07001447// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001448// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001449// still limited by Parallel()
1450func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001451 if !c.UseRemoteBuild() {
1452 return 0
1453 }
1454 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1455 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001456 }
1457 return 500
1458}
1459
1460func (c *configImpl) SetKatiArgs(args []string) {
1461 c.katiArgs = args
1462}
1463
1464func (c *configImpl) SetNinjaArgs(args []string) {
1465 c.ninjaArgs = args
1466}
1467
1468func (c *configImpl) SetKatiSuffix(suffix string) {
1469 c.katiSuffix = suffix
1470}
1471
Dan Willemsene0879fc2017-08-04 15:06:27 -07001472func (c *configImpl) LastKatiSuffixFile() string {
1473 return filepath.Join(c.OutDir(), "last_kati_suffix")
1474}
1475
1476func (c *configImpl) HasKatiSuffix() bool {
1477 return c.katiSuffix != ""
1478}
1479
Dan Willemsen1e704462016-08-21 15:17:17 -07001480func (c *configImpl) KatiEnvFile() string {
1481 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1482}
1483
Dan Willemsen29971232018-09-26 14:58:30 -07001484func (c *configImpl) KatiBuildNinjaFile() string {
1485 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001486}
1487
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001488func (c *configImpl) KatiPackageNinjaFile() string {
1489 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1490}
1491
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001492func (c *configImpl) SoongVarsFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001493 targetProduct, err := c.TargetProductOrErr()
1494 if err != nil {
1495 return filepath.Join(c.SoongOutDir(), "soong.variables")
1496 } else {
1497 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+".variables")
1498 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001499}
1500
Inseob Kim58c802f2024-06-11 10:59:00 +09001501func (c *configImpl) SoongExtraVarsFile() string {
1502 targetProduct, err := c.TargetProductOrErr()
1503 if err != nil {
1504 return filepath.Join(c.SoongOutDir(), "soong.extra.variables")
1505 } else {
1506 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+".extra.variables")
1507 }
1508}
1509
Dan Willemsen1e704462016-08-21 15:17:17 -07001510func (c *configImpl) SoongNinjaFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001511 targetProduct, err := c.TargetProductOrErr()
1512 if err != nil {
1513 return filepath.Join(c.SoongOutDir(), "build.ninja")
1514 } else {
1515 return filepath.Join(c.SoongOutDir(), "build."+targetProduct+".ninja")
1516 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001517}
1518
1519func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001520 if c.katiSuffix == "" {
1521 return filepath.Join(c.OutDir(), "combined.ninja")
1522 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001523 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1524}
1525
1526func (c *configImpl) SoongAndroidMk() string {
1527 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1528}
1529
1530func (c *configImpl) SoongMakeVarsMk() string {
1531 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1532}
1533
Colin Crossaa9a2732023-10-27 10:54:27 -07001534func (c *configImpl) SoongBuildMetrics() string {
Colin Crossb67b0612023-10-31 10:02:45 -07001535 return filepath.Join(c.LogsDir(), "soong_build_metrics.pb")
Colin Crossaa9a2732023-10-27 10:54:27 -07001536}
1537
Dan Willemsenf052f782017-05-18 15:29:04 -07001538func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001539 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001540}
1541
Dan Willemsen02781d52017-05-12 19:28:13 -07001542func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001543 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1544}
1545
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001546func (c *configImpl) KatiPackageMkDir() string {
1547 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1548}
1549
Dan Willemsenf052f782017-05-18 15:29:04 -07001550func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001551 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001552}
1553
1554func (c *configImpl) HostOut() string {
1555 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1556}
1557
1558// This probably needs to be multi-valued, so not exporting it for now
1559func (c *configImpl) hostCrossOut() string {
1560 if runtime.GOOS == "linux" {
1561 return filepath.Join(c.hostOutRoot(), "windows-x86")
1562 } else {
1563 return ""
1564 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001565}
1566
Dan Willemsen1e704462016-08-21 15:17:17 -07001567func (c *configImpl) HostPrebuiltTag() string {
1568 if runtime.GOOS == "linux" {
1569 return "linux-x86"
1570 } else if runtime.GOOS == "darwin" {
1571 return "darwin-x86"
1572 } else {
1573 panic("Unsupported OS")
1574 }
1575}
Dan Willemsenf173d592017-04-27 14:28:00 -07001576
Dan Willemsen8122bd52017-10-12 20:20:41 -07001577func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001578 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1579 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001580 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1581 if _, err := os.Stat(asan); err == nil {
1582 return asan
1583 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001584 }
1585 }
1586 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1587}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001588
1589func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1590 c.brokenDupRules = val
1591}
1592
1593func (c *configImpl) BuildBrokenDupRules() bool {
1594 return c.brokenDupRules
1595}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001596
Dan Willemsen25e6f092019-04-09 10:22:43 -07001597func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1598 c.brokenUsesNetwork = val
1599}
1600
1601func (c *configImpl) BuildBrokenUsesNetwork() bool {
1602 return c.brokenUsesNetwork
1603}
1604
Dan Willemsene3336352020-01-02 19:10:38 -08001605func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1606 c.brokenNinjaEnvVars = val
1607}
1608
1609func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1610 return c.brokenNinjaEnvVars
1611}
1612
Spandan Das28a6f192024-07-01 21:00:25 +00001613func (c *configImpl) SetBuildBrokenMissingOutputs(val bool) {
1614 c.brokenMissingOutputs = val
1615}
1616
1617func (c *configImpl) BuildBrokenMissingOutputs() bool {
1618 return c.brokenMissingOutputs
1619}
1620
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001621func (c *configImpl) SetTargetDeviceDir(dir string) {
1622 c.targetDeviceDir = dir
1623}
1624
1625func (c *configImpl) TargetDeviceDir() string {
1626 return c.targetDeviceDir
1627}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001628
Patrice Arruda219eef32020-06-01 17:29:30 +00001629func (c *configImpl) BuildDateTime() string {
1630 return c.buildDateTime
1631}
1632
1633func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001634 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001635}
Patrice Arruda83842d72020-12-08 19:42:08 +00001636
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001637// LogsDir returns the absolute path to the logs directory where build log and
1638// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001639// directory. If the argument dist is specified, the logs directory
1640// is <dist_dir>/logs.
1641func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001642 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001643 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001644 // 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 -05001645 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001646 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001647 absDir, err := filepath.Abs(dir)
1648 if err != nil {
1649 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1650 os.Exit(1)
1651 }
1652 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001653}
1654
Chris Parsons53f68ae2022-03-03 12:01:40 -05001655// MkFileMetrics returns the file path for make-related metrics.
1656func (c *configImpl) MkMetrics() string {
1657 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1658}
1659
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001660func (c *configImpl) SetEmptyNinjaFile(v bool) {
1661 c.emptyNinjaFile = v
1662}
1663
1664func (c *configImpl) EmptyNinjaFile() bool {
1665 return c.emptyNinjaFile
1666}
Yu Liu6e13b402021-07-27 14:29:06 -07001667
MarkDacekd0e7cd32022-12-02 22:22:40 +00001668func (c *configImpl) SkipMetricsUpload() bool {
1669 return c.skipMetricsUpload
1670}
1671
MarkDacekf47e1422023-04-19 16:47:36 +00001672func (c *configImpl) EnsureAllowlistIntegrity() bool {
1673 return c.ensureAllowlistIntegrity
1674}
1675
MarkDacek6614d9c2022-12-07 21:57:38 +00001676// Returns a Time object if one was passed via a command-line flag.
1677// Otherwise returns the passed default.
1678func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1679 if c.buildStartedTime == 0 {
1680 return defaultTime
1681 }
1682 return time.UnixMilli(c.buildStartedTime)
1683}
1684
Yu Liu6e13b402021-07-27 14:29:06 -07001685func GetMetricsUploader(topDir string, env *Environment) string {
1686 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1687 metricsUploader := filepath.Join(topDir, p)
1688 if _, err := os.Stat(metricsUploader); err == nil {
1689 return metricsUploader
1690 }
1691 }
1692
1693 return ""
1694}