blob: 90b98f560d029d00af2612a7626637cbf8053f17 [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
Cole Faustbee030d2024-01-03 13:45:48 -0800124
125 // Whether to use n2 instead of ninja. This is controlled with the
126 // environment variable SOONG_USE_N2
127 useN2 bool
Dan Willemsen1e704462016-08-21 15:17:17 -0700128}
129
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900130type NinjaWeightListSource uint
131
132const (
133 // ninja doesn't use weight list.
134 NOT_USED NinjaWeightListSource = iota
135 // ninja uses weight list based on previous builds by ninja log
136 NINJA_LOG
137 // ninja thinks every task has the same weight.
138 EVENLY_DISTRIBUTED
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900139 // ninja uses an external custom weight list
140 EXTERNAL_FILE
Jeongik Chae114e602023-03-19 00:12:39 +0900141 // ninja uses a prioritized module list from Soong
142 HINT_FROM_SOONG
Jeongik Chaa87506f2023-06-01 23:16:41 +0900143 // If ninja log exists, use NINJA_LOG, if not, use HINT_FROM_SOONG instead.
144 // We can assume it is an incremental build if ninja log exists.
145 DEFAULT
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900146)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800147const srcDirFileCheck = "build/soong/root.bp"
148
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700149var buildFiles = []string{"Android.mk", "Android.bp"}
150
Patrice Arruda13848222019-04-22 17:12:02 -0700151type BuildAction uint
152
153const (
154 // Builds all of the modules and their dependencies of a specified directory, relative to the root
155 // directory of the source tree.
156 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
157
158 // Builds all of the modules and their dependencies of a list of specified directories. All specified
159 // directories are relative to the root directory of the source tree.
160 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700161
162 // Build a list of specified modules. If none was specified, simply build the whole source tree.
163 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700164)
165
166// checkTopDir validates that the current directory is at the root directory of the source tree.
167func checkTopDir(ctx Context) {
168 if _, err := os.Stat(srcDirFileCheck); err != nil {
169 if os.IsNotExist(err) {
170 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
171 }
172 ctx.Fatalln("Error verifying tree state:", err)
173 }
174}
175
MarkDacek7901e582023-01-09 19:48:01 +0000176func loadEnvConfig(ctx Context, config *configImpl, bc string) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500177 if bc == "" {
178 return nil
179 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500180
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500181 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500182 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500183 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500184 envConfigDir,
185 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500186 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500187 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
188 envVarsJSON, err := ioutil.ReadFile(cfgFile)
189 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500190 continue
191 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500192 ctx.Verbosef("Loading config file %v\n", cfgFile)
193 var envVars map[string]map[string]string
194 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
195 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
196 continue
197 }
198 for k, v := range envVars["env"] {
199 if os.Getenv(k) != "" {
200 continue
201 }
202 config.environ.Set(k, v)
203 }
204 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
205 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500206 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500207
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500208 return nil
209}
210
Dan Willemsen1e704462016-08-21 15:17:17 -0700211func NewConfig(ctx Context, args ...string) Config {
212 ret := &configImpl{
Jeongik Chaf2ecf762023-05-19 14:03:45 +0900213 environ: OsEnvironment(),
214 sandboxConfig: &SandboxConfig{},
Jeongik Chaa87506f2023-06-01 23:16:41 +0900215 ninjaWeightListSource: DEFAULT,
Dan Willemsen1e704462016-08-21 15:17:17 -0700216 }
Taylor Santiago0af8ea12024-08-20 14:10:50 -0700217 wd, err := os.Getwd()
218 if err != nil {
219 ctx.Fatalln("Failed to get working directory:", err)
220 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700221
Colin Cross106d6ef2023-10-24 10:34:56 -0700222 // Skip soong tests by default on Linux
223 if runtime.GOOS == "linux" {
224 ret.skipSoongTests = true
225 }
226
Patrice Arruda90109172020-07-28 18:07:27 +0000227 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700228 ret.parallel = runtime.NumCPU() + 2
229 ret.keepGoing = 1
230
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800231 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700232 ret.parseArgs(ctx, args)
Jeongik Chae114e602023-03-19 00:12:39 +0900233
234 if ret.ninjaWeightListSource == HINT_FROM_SOONG {
Jeongik Chaa87506f2023-06-01 23:16:41 +0900235 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "always")
236 } else if ret.ninjaWeightListSource == DEFAULT {
237 defaultNinjaWeightListSource := NINJA_LOG
238 if _, err := os.Stat(filepath.Join(ret.OutDir(), ninjaLogFileName)); errors.Is(err, os.ErrNotExist) {
239 ctx.Verboseln("$OUT/.ninja_log doesn't exist, use HINT_FROM_SOONG instead")
240 defaultNinjaWeightListSource = HINT_FROM_SOONG
241 } else {
242 ctx.Verboseln("$OUT/.ninja_log exist, use NINJA_LOG")
243 }
244 ret.ninjaWeightListSource = defaultNinjaWeightListSource
245 // soong_build generates ninja hint depending on ninja log existence.
246 // Set it "depend" to avoid soong re-run due to env variable change.
247 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "depend")
Jeongik Chae114e602023-03-19 00:12:39 +0900248 }
Jeongik Chaa87506f2023-06-01 23:16:41 +0900249
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800250 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700251 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
Taylor Santiago0af8ea12024-08-20 14:10:50 -0700252 ret.environ.Set("OUT_DIR", ret.sandboxPath(wd, filepath.Clean(outDir)))
Dan Willemsen02f3add2017-05-12 13:50:19 -0700253 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800254 outDir := "out"
255 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
Taylor Santiago0af8ea12024-08-20 14:10:50 -0700256 outDir = filepath.Join(baseDir, filepath.Base(wd))
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800257 }
Taylor Santiago0af8ea12024-08-20 14:10:50 -0700258 ret.environ.Set("OUT_DIR", ret.sandboxPath(wd, outDir))
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800259 }
260
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500261 // loadEnvConfig needs to know what the OUT_DIR is, so it should
262 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000263 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
264
265 if bc != "" {
Kousik Kumarc8818332023-01-16 16:33:05 +0000266 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000267 ctx.Fatalln("Failed to parse env config files: %v", err)
268 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +0000269 if !ret.canSupportRBE() {
270 // Explicitly set USE_RBE env variable to false when we cannot run
271 // an RBE build to avoid ninja local execution pool issues.
272 ret.environ.Set("USE_RBE", "false")
273 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500274 }
275
Dan Willemsen2d31a442018-10-20 21:33:41 -0700276 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
277 ret.distDir = filepath.Clean(distDir)
278 } else {
279 ret.distDir = filepath.Join(ret.OutDir(), "dist")
280 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700281
Spandan Das05063612021-06-25 01:39:04 +0000282 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
283 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
284 }
285
Joe Onoratoe5ed3472024-02-02 14:52:05 -0800286 if os.Getenv("GENERATE_SOONG_DEBUG") == "true" {
287 ret.moduleDebugFile, _ = filepath.Abs(shared.JoinPath(ret.SoongOutDir(), "soong-debug-info.json"))
288 }
289
Cole Faustbee030d2024-01-03 13:45:48 -0800290 if os.Getenv("SOONG_USE_N2") == "true" {
291 ret.useN2 = true
292 }
293
Dan Willemsen1e704462016-08-21 15:17:17 -0700294 ret.environ.Unset(
295 // We're already using it
296 "USE_SOONG_UI",
297
298 // We should never use GOROOT/GOPATH from the shell environment
299 "GOROOT",
300 "GOPATH",
301
302 // These should only come from Soong, not the environment.
303 "CLANG",
304 "CLANG_CXX",
305 "CCC_CC",
306 "CCC_CXX",
307
308 // Used by the goma compiler wrapper, but should only be set by
309 // gomacc
310 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800311
312 // We handle this above
313 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700314
Dan Willemsen2d31a442018-10-20 21:33:41 -0700315 // This is handled above too, and set for individual commands later
316 "DIST_DIR",
317
Dan Willemsen68a09852017-04-18 13:56:57 -0700318 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000319 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700320 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700321 "DISPLAY",
322 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000323 "JAVAC",
Nathan Egge978c9342024-07-03 21:13:03 +0000324 "LEX",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700325 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700326 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700327
328 // Drop make flags
329 "MAKEFLAGS",
330 "MAKELEVEL",
331 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700332
333 // Set in envsetup.sh, reset in makefiles
334 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700335
336 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
337 "ANDROID_BUILD_TOP",
338 "ANDROID_HOST_OUT",
339 "ANDROID_PRODUCT_OUT",
340 "ANDROID_HOST_OUT_TESTCASES",
341 "ANDROID_TARGET_OUT_TESTCASES",
342 "ANDROID_TOOLCHAIN",
343 "ANDROID_TOOLCHAIN_2ND_ARCH",
344 "ANDROID_DEV_SCRIPTS",
345 "ANDROID_EMULATOR_PREBUILTS",
346 "ANDROID_PRE_BUILD_PATHS",
Joe Onoratoe5ed3472024-02-02 14:52:05 -0800347
348 // We read it here already, don't let others share in the fun
349 "GENERATE_SOONG_DEBUG",
Cole Faustbee030d2024-01-03 13:45:48 -0800350
351 // Use config.useN2 instead.
352 "SOONG_USE_N2",
Taylor Santiago0af8ea12024-08-20 14:10:50 -0700353
354 // Leaks usernames into environment.
355 "HOME",
Dan Willemsen1e704462016-08-21 15:17:17 -0700356 )
357
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400358 if ret.UseGoma() || ret.ForceUseGoma() {
359 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
360 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400361 }
362
Dan Willemsen1e704462016-08-21 15:17:17 -0700363 // Tell python not to spam the source tree with .pyc files.
364 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
365
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400366 tmpDir := absPath(ctx, ret.TempDir())
Taylor Santiago0af8ea12024-08-20 14:10:50 -0700367 ret.environ.Set("TMPDIR", ret.sandboxPath(wd, tmpDir))
Dan Willemsen32a669b2018-03-08 19:42:00 -0800368
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700369 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
370 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
371 "llvm-binutils-stable/llvm-symbolizer")
Taylor Santiago0af8ea12024-08-20 14:10:50 -0700372 ret.environ.Set("ASAN_SYMBOLIZER_PATH", ret.sandboxPath(wd, absPath(ctx, symbolizerPath)))
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700373
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800374 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700375 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800376
Yu Liu6e13b402021-07-27 14:29:06 -0700377 srcDir := absPath(ctx, ".")
378 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700379 ctx.Println("You are building in a directory whose absolute path contains a space character:")
380 ctx.Println()
381 ctx.Printf("%q\n", srcDir)
382 ctx.Println()
383 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700384 }
385
Yu Liu6e13b402021-07-27 14:29:06 -0700386 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
387
Dan Willemsendb8457c2017-05-12 16:38:17 -0700388 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700389 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
390 ctx.Println()
391 ctx.Printf("%q\n", outDir)
392 ctx.Println()
393 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700394 }
395
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000396 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700397 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
398 ctx.Println()
399 ctx.Printf("%q\n", distDir)
400 ctx.Println()
401 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700402 }
403
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700404 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000405 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
Sorin Basca0760c892023-11-29 19:13:55 +0000406 java21Home := filepath.Join("prebuilts/jdk/jdk21", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700407 javaHome := func() string {
408 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
409 return override
410 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000411 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
Sorin Basca5dfa2382024-03-11 17:23:06 +0000412 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 +0100413 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000414 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
Sorin Basca5dfa2382024-03-11 17:23:06 +0000415 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 +0000416 }
Sorin Basca5dfa2382024-03-11 17:23:06 +0000417 if toolchain21, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK21_TOOLCHAIN"); ok && toolchain21 != "true" {
418 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK21_TOOLCHAIN is no longer supported. An OpenJDK 21 toolchain is now the global default.")
419 }
420 return java21Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700421 }()
422 absJavaHome := absPath(ctx, javaHome)
423
Dan Willemsened869522018-01-08 14:58:46 -0800424 ret.configureLocale(ctx)
425
Taylor Santiago0af8ea12024-08-20 14:10:50 -0700426 newPath := []string{ret.sandboxPath(wd, filepath.Join(absJavaHome, "bin"))}
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700427 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
Taylor Santiago0af8ea12024-08-20 14:10:50 -0700428 entries := strings.Split(path, string(filepath.ListSeparator))
429 for _, ent := range entries {
430 newPath = append(newPath, ret.sandboxPath(wd, ent))
431 }
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700432 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100433
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700434 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
Taylor Santiago0af8ea12024-08-20 14:10:50 -0700435 ret.environ.Set("JAVA_HOME", ret.sandboxPath(wd, absJavaHome))
436 ret.environ.Set("ANDROID_JAVA_HOME", ret.sandboxPath(wd, javaHome))
437 ret.environ.Set("ANDROID_JAVA8_HOME", ret.sandboxPath(wd, java8Home))
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700438 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
439
Colin Crossfe5ed4d2023-07-28 09:27:23 -0700440 // b/286885495, https://bugzilla.redhat.com/show_bug.cgi?id=2227130: some versions of Fedora include patches
441 // to unzip to enable zipbomb detection that incorrectly handle zip64 and data descriptors and fail on large
442 // zip files produced by soong_zip. Disable zipbomb detection.
443 ret.environ.Set("UNZIP_DISABLE_ZIPBOMB_DETECTION", "TRUE")
444
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800445 outDir := ret.OutDir()
446 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800447 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800448 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800449 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800450 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800451 }
Colin Cross28f527c2019-11-26 16:19:04 -0800452
Taylor Santiago0af8ea12024-08-20 14:10:50 -0700453 ret.environ.Set("BUILD_DATETIME_FILE", ret.sandboxPath(wd, buildDateTimeFile))
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800454
Cole Faust583dfb42023-09-28 13:56:30 -0700455 if _, ok := ret.environ.Get("BUILD_USERNAME"); !ok {
456 username := "unknown"
457 if u, err := user.Current(); err == nil {
458 username = u.Username
459 } else {
460 ctx.Println("Failed to get current user:", err)
461 }
462 ret.environ.Set("BUILD_USERNAME", username)
463 }
Taylor Santiago0af8ea12024-08-20 14:10:50 -0700464 ret.environ.Set("PWD", ret.sandboxPath(wd, wd))
Cole Faust583dfb42023-09-28 13:56:30 -0700465
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400466 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400467 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400468 ret.environ.Set(k, v)
469 }
470 }
471
Patrice Arruda96850362020-08-11 20:41:11 +0000472 c := Config{ret}
473 storeConfigMetrics(ctx, c)
474 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700475}
476
Patrice Arruda13848222019-04-22 17:12:02 -0700477// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
478// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700479func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
480 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700481}
482
LaMont Jones9a912862023-11-06 22:11:08 +0000483// Prepare for getting make variables. For them to be accurate, we need to have
484// obtained PRODUCT_RELEASE_CONFIG_MAPS.
485//
486// Returns:
487//
488// Whether config should be called again.
489//
490// TODO: when converting product config to a declarative language, make sure
491// that PRODUCT_RELEASE_CONFIG_MAPS is properly handled as a separate step in
492// that process.
493func SetProductReleaseConfigMaps(ctx Context, config Config) bool {
494 ctx.BeginTrace(metrics.RunKati, "SetProductReleaseConfigMaps")
495 defer ctx.EndTrace()
496
497 if config.SkipConfig() {
498 // This duplicates the logic from Build to skip product config
499 // if the user has explicitly said to.
500 return false
501 }
502
503 releaseConfigVars := []string{
504 "PRODUCT_RELEASE_CONFIG_MAPS",
505 }
506
507 origValue, _ := config.environ.Get("PRODUCT_RELEASE_CONFIG_MAPS")
508 // Get the PRODUCT_RELEASE_CONFIG_MAPS for this product, to avoid polluting the environment
509 // when we run product config to get the rest of the make vars.
510 releaseMapVars, err := dumpMakeVars(ctx, config, nil, releaseConfigVars, false, "")
511 if err != nil {
512 ctx.Fatalln("Error getting PRODUCT_RELEASE_CONFIG_MAPS:", err)
513 }
514 productReleaseConfigMaps := releaseMapVars["PRODUCT_RELEASE_CONFIG_MAPS"]
515 os.Setenv("PRODUCT_RELEASE_CONFIG_MAPS", productReleaseConfigMaps)
516 return origValue != productReleaseConfigMaps
517}
518
Patrice Arruda96850362020-08-11 20:41:11 +0000519// storeConfigMetrics selects a set of configuration information and store in
520// the metrics system for further analysis.
521func storeConfigMetrics(ctx Context, config Config) {
522 if ctx.Metrics == nil {
523 return
524 }
525
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400526 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000527
528 s := &smpb.SystemResourceInfo{
529 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
530 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
531 }
532 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000533}
534
Jeongik Cha8d63d562023-03-17 03:52:13 +0900535func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900536 switch s {
537 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900538 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900539 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900540 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900541 case EXTERNAL_FILE:
542 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900543 case HINT_FROM_SOONG:
544 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900545 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900546 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900547 }
548}
549
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400550func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700551 c := &smpb.BuildConfig{
Colin Cross8d411ff2023-12-07 10:31:24 -0800552 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
553 UseGoma: proto.Bool(config.UseGoma()),
554 UseRbe: proto.Bool(config.UseRBE()),
555 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400556 }
Yu Liue737a992021-10-04 13:21:41 -0700557 c.Targets = append(c.Targets, config.arguments...)
558
559 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400560}
561
Patrice Arruda13848222019-04-22 17:12:02 -0700562// getConfigArgs processes the command arguments based on the build action and creates a set of new
563// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700564func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700565 // The next block of code verifies that the current directory is the root directory of the source
566 // tree. It then finds the relative path of dir based on the root directory of the source tree
567 // and verify that dir is inside of the source tree.
568 checkTopDir(ctx)
569 topDir, err := os.Getwd()
570 if err != nil {
571 ctx.Fatalf("Error retrieving top directory: %v", err)
572 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700573 dir, err = filepath.EvalSymlinks(dir)
574 if err != nil {
575 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
576 }
Patrice Arruda13848222019-04-22 17:12:02 -0700577 dir, err = filepath.Abs(dir)
578 if err != nil {
579 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
580 }
581 relDir, err := filepath.Rel(topDir, dir)
582 if err != nil {
583 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
584 }
585 // If there are ".." in the path, it's not in the source tree.
586 if strings.Contains(relDir, "..") {
587 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
588 }
589
590 configArgs := args[:]
591
592 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
593 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
594 targetNamePrefix := "MODULES-IN-"
595 if inList("GET-INSTALL-PATH", configArgs) {
596 targetNamePrefix = "GET-INSTALL-PATH-IN-"
597 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
598 }
599
Patrice Arruda13848222019-04-22 17:12:02 -0700600 var targets []string
601
602 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700603 case BUILD_MODULES:
604 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700605 case BUILD_MODULES_IN_A_DIRECTORY:
606 // If dir is the root source tree, all the modules are built of the source tree are built so
607 // no need to find the build file.
608 if topDir == dir {
609 break
610 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700611
Patrice Arruda13848222019-04-22 17:12:02 -0700612 buildFile := findBuildFile(ctx, relDir)
613 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700614 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700615 }
Patrice Arruda13848222019-04-22 17:12:02 -0700616 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
617 case BUILD_MODULES_IN_DIRECTORIES:
618 newConfigArgs, dirs := splitArgs(configArgs)
619 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700620 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700621 }
622
623 // Tidy only override all other specified targets.
624 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
625 if tidyOnly == "true" || tidyOnly == "1" {
626 configArgs = append(configArgs, "tidy_only")
627 } else {
628 configArgs = append(configArgs, targets...)
629 }
630
631 return configArgs
632}
633
634// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
635func convertToTarget(dir string, targetNamePrefix string) string {
636 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
637}
638
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700639// hasBuildFile returns true if dir contains an Android build file.
640func hasBuildFile(ctx Context, dir string) bool {
641 for _, buildFile := range buildFiles {
642 _, err := os.Stat(filepath.Join(dir, buildFile))
643 if err == nil {
644 return true
645 }
646 if !os.IsNotExist(err) {
647 ctx.Fatalf("Error retrieving the build file stats: %v", err)
648 }
649 }
650 return false
651}
652
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700653// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
654// in the current and any sub directory of dir. If a build file is not found, traverse the path
655// up by one directory and repeat again until either a build file is found or reached to the root
656// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
657// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700658func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700659 // If the string is empty or ".", assume it is top directory of the source tree.
660 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700661 return ""
662 }
663
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700664 found := false
665 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
666 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
667 if err != nil {
668 return err
669 }
670 if found {
671 return filepath.SkipDir
672 }
673 if info.IsDir() {
674 return nil
675 }
676 for _, buildFile := range buildFiles {
677 if info.Name() == buildFile {
678 found = true
679 return filepath.SkipDir
680 }
681 }
682 return nil
683 })
684 if err != nil {
685 ctx.Fatalf("Error finding Android build file: %v", err)
686 }
687
688 if found {
689 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700690 }
691 }
692
693 return ""
694}
695
696// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
697func splitArgs(args []string) (newArgs []string, dirs []string) {
698 specialArgs := map[string]bool{
699 "showcommands": true,
700 "snod": true,
701 "dist": true,
702 "checkbuild": true,
703 }
704
705 newArgs = []string{}
706 dirs = []string{}
707
708 for _, arg := range args {
709 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
710 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
711 newArgs = append(newArgs, arg)
712 continue
713 }
714
715 if _, ok := specialArgs[arg]; ok {
716 newArgs = append(newArgs, arg)
717 continue
718 }
719
720 dirs = append(dirs, arg)
721 }
722
723 return newArgs, dirs
724}
725
726// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
727// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
728// source root tree where the build action command was invoked. Each directory is validated if the
729// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700730func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700731 for _, dir := range dirs {
732 // The directory may have specified specific modules to build. ":" is the separator to separate
733 // the directory and the list of modules.
734 s := strings.Split(dir, ":")
735 l := len(s)
736 if l > 2 { // more than one ":" was specified.
737 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
738 }
739
740 dir = filepath.Join(relDir, s[0])
741 if _, err := os.Stat(dir); err != nil {
742 ctx.Fatalf("couldn't find directory %s", dir)
743 }
744
745 // Verify that if there are any targets specified after ":". Each target is separated by ",".
746 var newTargets []string
747 if l == 2 && s[1] != "" {
748 newTargets = strings.Split(s[1], ",")
749 if inList("", newTargets) {
750 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
751 }
752 }
753
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700754 // If there are specified targets to build in dir, an android build file must exist for the one
755 // shot build. For the non-targets case, find the appropriate build file and build all the
756 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700757 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700758 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700759 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
760 }
761 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700762 buildFile := findBuildFile(ctx, dir)
763 if buildFile == "" {
764 ctx.Fatalf("Build file not found for %s directory", dir)
765 }
766 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700767 }
768
Patrice Arruda13848222019-04-22 17:12:02 -0700769 targets = append(targets, newTargets...)
770 }
771
Dan Willemsence41e942019-07-29 23:39:30 -0700772 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700773}
774
Dan Willemsen9b587492017-07-10 22:13:00 -0700775func (c *configImpl) parseArgs(ctx Context, args []string) {
776 for i := 0; i < len(args); i++ {
777 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100778 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700779 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200780 } else if arg == "--empty-ninja-file" {
781 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100782 } else if arg == "--skip-ninja" {
783 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700784 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700785 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
786 // but it does run a Kati ninja file if the .kati_enabled marker file was created
787 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000788 c.skipConfig = true
789 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100790 } else if arg == "--soong-only" {
791 c.skipKati = true
792 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200793 } else if arg == "--config-only" {
794 c.skipKati = true
795 c.skipKatiNinja = true
796 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700797 } else if arg == "--skip-config" {
798 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700799 } else if arg == "--skip-soong-tests" {
800 c.skipSoongTests = true
Colin Cross106d6ef2023-10-24 10:34:56 -0700801 } else if arg == "--no-skip-soong-tests" {
802 c.skipSoongTests = false
MarkDacekd0e7cd32022-12-02 22:22:40 +0000803 } else if arg == "--skip-metrics-upload" {
804 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500805 } else if arg == "--mk-metrics" {
806 c.reportMkMetrics = true
Spandan Das394aa322022-11-03 17:02:10 +0000807 } else if arg == "--search-api-dir" {
808 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900809 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
810 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
811 if source == "ninja_log" {
812 c.ninjaWeightListSource = NINJA_LOG
813 } else if source == "evenly_distributed" {
814 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
815 } else if source == "not_used" {
816 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900817 } else if source == "soong" {
818 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900819 } else if strings.HasPrefix(source, "file,") {
820 c.ninjaWeightListSource = EXTERNAL_FILE
821 filePath := strings.TrimPrefix(source, "file,")
822 err := validateNinjaWeightList(filePath)
823 if err != nil {
824 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
825 }
826 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
827 if err != nil {
828 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
829 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900830 } else {
831 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
832 }
Jihoon Kang2a929ad2023-06-08 19:02:07 +0000833 } else if arg == "--build-from-source-stub" {
834 c.buildFromSourceStub = true
Yu Liufa297642024-06-11 00:13:02 +0000835 } else if arg == "--incremental-build-actions" {
836 c.incrementalBuildActions = true
MarkDacekb96561e2022-12-02 04:34:43 +0000837 } else if strings.HasPrefix(arg, "--build-command=") {
838 buildCmd := strings.TrimPrefix(arg, "--build-command=")
839 // remove quotations
840 buildCmd = strings.TrimPrefix(buildCmd, "\"")
841 buildCmd = strings.TrimSuffix(buildCmd, "\"")
842 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacek6614d9c2022-12-07 21:57:38 +0000843 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
844 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
845 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
846 if err == nil {
847 c.buildStartedTime = val
848 } else {
849 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
850 }
MarkDacekf47e1422023-04-19 16:47:36 +0000851 } else if arg == "--ensure-allowlist-integrity" {
852 c.ensureAllowlistIntegrity = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700853 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700854 parseArgNum := func(def int) int {
855 if len(arg) > 2 {
856 p, err := strconv.ParseUint(arg[2:], 10, 31)
857 if err != nil {
858 ctx.Fatalf("Failed to parse %q: %v", arg, err)
859 }
860 return int(p)
861 } else if i+1 < len(args) {
862 p, err := strconv.ParseUint(args[i+1], 10, 31)
863 if err == nil {
864 i++
865 return int(p)
866 }
867 }
868 return def
869 }
870
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700871 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700872 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700873 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700874 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700875 } else {
876 ctx.Fatalln("Unknown option:", arg)
877 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700878 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700879 if k == "OUT_DIR" {
880 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
881 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700882 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700883 } else if arg == "dist" {
884 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200885 } else if arg == "json-module-graph" {
886 c.jsonModuleGraph = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200887 } else if arg == "queryview" {
888 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200889 } else if arg == "soong_docs" {
890 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700891 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700892 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800893 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700894 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700895 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700896 }
897 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700898}
899
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900900func validateNinjaWeightList(weightListFilePath string) (err error) {
901 data, err := os.ReadFile(weightListFilePath)
902 if err != nil {
903 return
904 }
905 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
906 for _, line := range lines {
907 fields := strings.Split(line, ",")
908 if len(fields) != 2 {
909 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
910 }
911 _, err = strconv.Atoi(fields[1])
912 if err != nil {
913 return
914 }
915 }
916 return
917}
918
Dan Willemsened869522018-01-08 14:58:46 -0800919func (c *configImpl) configureLocale(ctx Context) {
920 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
921 output, err := cmd.Output()
922
923 var locales []string
924 if err == nil {
925 locales = strings.Split(string(output), "\n")
926 } else {
927 // If we're unable to list the locales, let's assume en_US.UTF-8
928 locales = []string{"en_US.UTF-8"}
929 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
930 }
931
932 // gettext uses LANGUAGE, which is passed directly through
933
934 // For LANG and LC_*, only preserve the evaluated version of
935 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800936 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800937 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800938 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800939 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800940 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800941 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800942 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800943 }
944
945 c.environ.UnsetWithPrefix("LC_")
946
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800947 if userLang != "" {
948 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800949 }
950
951 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
952 // for others)
953 if inList("C.UTF-8", locales) {
954 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500955 } else if inList("C.utf8", locales) {
956 // These normalize to the same thing
957 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800958 } else if inList("en_US.UTF-8", locales) {
959 c.environ.Set("LANG", "en_US.UTF-8")
960 } else if inList("en_US.utf8", locales) {
961 // These normalize to the same thing
962 c.environ.Set("LANG", "en_US.UTF-8")
963 } else {
964 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
965 }
966}
967
Dan Willemsen1e704462016-08-21 15:17:17 -0700968func (c *configImpl) Environment() *Environment {
969 return c.environ
970}
971
972func (c *configImpl) Arguments() []string {
973 return c.arguments
974}
975
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200976func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200977 if len(c.Arguments()) > 0 {
978 // Explicit targets requested that are not special targets like b2pbuild
979 // or the JSON module graph
980 return true
981 }
982
Colin Cross8d411ff2023-12-07 10:31:24 -0800983 if !c.JsonModuleGraph() && !c.Queryview() && !c.SoongDocs() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200984 // Command line was empty, the default Ninja target is built
985 return true
986 }
987
Colin Cross8d411ff2023-12-07 10:31:24 -0800988 if c.Dist() {
Liz Kammer88677422021-12-15 15:03:19 -0500989 return true
990 }
991
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200992 // build.ninja doesn't need to be generated
993 return false
994}
995
Dan Willemsen1e704462016-08-21 15:17:17 -0700996func (c *configImpl) OutDir() string {
997 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700998 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700999 }
1000 return "out"
1001}
1002
Dan Willemsen8a073a82017-02-04 17:30:44 -08001003func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -04001004 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001005}
1006
1007func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -07001008 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -08001009}
1010
Dan Willemsen1e704462016-08-21 15:17:17 -07001011func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001012 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001013 return c.arguments
1014 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001015 return c.ninjaArgs
1016}
1017
1018func (c *configImpl) SoongOutDir() string {
1019 return filepath.Join(c.OutDir(), "soong")
1020}
1021
Spandan Das394aa322022-11-03 17:02:10 +00001022func (c *configImpl) ApiSurfacesOutDir() string {
1023 return filepath.Join(c.OutDir(), "api_surfaces")
1024}
1025
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001026func (c *configImpl) PrebuiltOS() string {
1027 switch runtime.GOOS {
1028 case "linux":
1029 return "linux-x86"
1030 case "darwin":
1031 return "darwin-x86"
1032 default:
1033 panic("Unknown GOOS")
1034 }
1035}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001036
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001037func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001038 if c.SkipKatiNinja() {
1039 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1040 } else {
1041 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1042 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001043}
1044
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001045func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001046 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001047}
1048
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001049func (c *configImpl) UsedEnvFile(tag string) string {
Kiyoung Kimeaa55a82023-06-05 16:56:49 +09001050 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
Qing Shen9e05d1c2024-08-13 02:04:53 +00001051 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+v+c.CoverageSuffix()+"."+tag)
Kiyoung Kimeaa55a82023-06-05 16:56:49 +09001052 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001053 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1054}
1055
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001056func (c *configImpl) SoongDocsHtml() string {
1057 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1058}
1059
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001060func (c *configImpl) QueryviewMarkerFile() string {
1061 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1062}
1063
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001064func (c *configImpl) ModuleGraphFile() string {
1065 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1066}
1067
kgui67007242022-01-25 13:50:25 +08001068func (c *configImpl) ModuleActionsFile() string {
1069 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1070}
1071
Jeff Gastonefc1b412017-03-29 17:29:06 -07001072func (c *configImpl) TempDir() string {
1073 return shared.TempDirForOutDir(c.SoongOutDir())
1074}
1075
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001076func (c *configImpl) FileListDir() string {
1077 return filepath.Join(c.OutDir(), ".module_paths")
1078}
1079
Dan Willemsen1e704462016-08-21 15:17:17 -07001080func (c *configImpl) KatiSuffix() string {
1081 if c.katiSuffix != "" {
1082 return c.katiSuffix
1083 }
1084 panic("SetKatiSuffix has not been called")
1085}
1086
Colin Cross37193492017-11-16 17:55:00 -08001087// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1088// user is interested in additional checks at the expense of build time.
1089func (c *configImpl) Checkbuild() bool {
1090 return c.checkbuild
1091}
1092
Dan Willemsen8a073a82017-02-04 17:30:44 -08001093func (c *configImpl) Dist() bool {
1094 return c.dist
1095}
1096
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001097func (c *configImpl) JsonModuleGraph() bool {
1098 return c.jsonModuleGraph
1099}
1100
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001101func (c *configImpl) Queryview() bool {
1102 return c.queryview
1103}
1104
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001105func (c *configImpl) SoongDocs() bool {
1106 return c.soongDocs
1107}
1108
Dan Willemsen1e704462016-08-21 15:17:17 -07001109func (c *configImpl) IsVerbose() bool {
1110 return c.verbose
1111}
1112
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001113func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1114 return c.ninjaWeightListSource
1115}
1116
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001117func (c *configImpl) SkipKati() bool {
1118 return c.skipKati
1119}
1120
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001121func (c *configImpl) SkipKatiNinja() bool {
1122 return c.skipKatiNinja
1123}
1124
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001125func (c *configImpl) SkipSoong() bool {
1126 return c.skipSoong
1127}
1128
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001129func (c *configImpl) SkipNinja() bool {
1130 return c.skipNinja
1131}
1132
Anton Hansson5a7861a2021-06-04 10:09:01 +01001133func (c *configImpl) SetSkipNinja(v bool) {
1134 c.skipNinja = v
1135}
1136
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001137func (c *configImpl) SkipConfig() bool {
1138 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001139}
1140
Jihoon Kang1bff0342023-01-17 20:40:22 +00001141func (c *configImpl) BuildFromTextStub() bool {
Jihoon Kang2a929ad2023-06-08 19:02:07 +00001142 return !c.buildFromSourceStub
Jihoon Kang1bff0342023-01-17 20:40:22 +00001143}
1144
Dan Willemsen1e704462016-08-21 15:17:17 -07001145func (c *configImpl) TargetProduct() string {
1146 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1147 return v
1148 }
1149 panic("TARGET_PRODUCT is not defined")
1150}
1151
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001152func (c *configImpl) TargetProductOrErr() (string, error) {
1153 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1154 return v, nil
1155 }
1156 return "", fmt.Errorf("TARGET_PRODUCT is not defined")
1157}
1158
Qing Shen9e05d1c2024-08-13 02:04:53 +00001159func (c *configImpl) CoverageSuffix() string {
1160 if v := c.environ.IsEnvTrue("EMMA_INSTRUMENT"); v {
1161 return ".coverage"
1162 }
1163 return ""
1164}
1165
Dan Willemsen02781d52017-05-12 19:28:13 -07001166func (c *configImpl) TargetDevice() string {
1167 return c.targetDevice
1168}
1169
1170func (c *configImpl) SetTargetDevice(device string) {
1171 c.targetDevice = device
1172}
1173
1174func (c *configImpl) TargetBuildVariant() string {
1175 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1176 return v
1177 }
1178 panic("TARGET_BUILD_VARIANT is not defined")
1179}
1180
Dan Willemsen1e704462016-08-21 15:17:17 -07001181func (c *configImpl) KatiArgs() []string {
1182 return c.katiArgs
1183}
1184
1185func (c *configImpl) Parallel() int {
1186 return c.parallel
1187}
1188
Sam Delmerico98a73292023-02-21 11:50:29 -05001189func (c *configImpl) GetSourceRootDirs() []string {
1190 return c.sourceRootDirs
1191}
1192
1193func (c *configImpl) SetSourceRootDirs(i []string) {
1194 c.sourceRootDirs = i
1195}
1196
MarkDacek6614d9c2022-12-07 21:57:38 +00001197func (c *configImpl) GetLogsPrefix() string {
1198 return c.logsPrefix
1199}
1200
1201func (c *configImpl) SetLogsPrefix(prefix string) {
1202 c.logsPrefix = prefix
1203}
1204
Colin Cross8b8bec32019-11-15 13:18:43 -08001205func (c *configImpl) HighmemParallel() int {
1206 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1207 return i
1208 }
1209
1210 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1211 parallel := c.Parallel()
1212 if c.UseRemoteBuild() {
1213 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1214 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1215 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1216 // Return 1/16th of the size of the local pool, rounding up.
1217 return (parallel + 15) / 16
1218 } else if c.totalRAM == 0 {
1219 // Couldn't detect the total RAM, don't restrict highmem processes.
1220 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001221 } else if c.totalRAM <= 16*1024*1024*1024 {
1222 // Less than 16GB of ram, restrict to 1 highmem processes
1223 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001224 } else if c.totalRAM <= 32*1024*1024*1024 {
1225 // Less than 32GB of ram, restrict to 2 highmem processes
1226 return 2
1227 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1228 // If less than 8GB total RAM per process, reduce the number of highmem processes
1229 return p
1230 }
1231 // No restriction on highmem processes
1232 return parallel
1233}
1234
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001235func (c *configImpl) TotalRAM() uint64 {
1236 return c.totalRAM
1237}
1238
Kousik Kumarec478642020-09-21 13:39:24 -04001239// ForceUseGoma determines whether we should override Goma deprecation
1240// and use Goma for the current build or not.
1241func (c *configImpl) ForceUseGoma() bool {
1242 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1243 v = strings.TrimSpace(v)
1244 if v != "" && v != "false" {
1245 return true
1246 }
1247 }
1248 return false
1249}
1250
Dan Willemsen1e704462016-08-21 15:17:17 -07001251func (c *configImpl) UseGoma() bool {
1252 if v, ok := c.environ.Get("USE_GOMA"); ok {
1253 v = strings.TrimSpace(v)
1254 if v != "" && v != "false" {
1255 return true
1256 }
1257 }
1258 return false
1259}
1260
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001261func (c *configImpl) StartGoma() bool {
1262 if !c.UseGoma() {
1263 return false
1264 }
1265
1266 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1267 v = strings.TrimSpace(v)
1268 if v != "" && v != "false" {
1269 return false
1270 }
1271 }
1272 return true
1273}
1274
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001275func (c *configImpl) canSupportRBE() bool {
Joe Onorato86f50e72024-06-24 14:28:25 -07001276 // Only supported on linux
1277 if runtime.GOOS != "linux" {
1278 return false
1279 }
1280
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001281 // Do not use RBE with prod credentials in scenarios when stubby doesn't exist, since
1282 // its unlikely that we will be able to obtain necessary creds without stubby.
1283 authType, _ := c.rbeAuth()
1284 if !c.StubbyExists() && strings.Contains(authType, "use_google_prod_creds") {
1285 return false
1286 }
Taylor Santiago3c16e612024-05-30 14:41:31 -07001287 if c.UseABFS() {
1288 return false
1289 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001290 return true
1291}
1292
Taylor Santiago3c16e612024-05-30 14:41:31 -07001293func (c *configImpl) UseABFS() bool {
1294 if v, ok := c.environ.Get("NO_ABFS"); ok {
1295 v = strings.ToLower(strings.TrimSpace(v))
1296 if v == "true" || v == "1" {
1297 return false
1298 }
1299 }
1300
1301 abfsBox := c.PrebuiltBuildTool("abfsbox")
1302 err := exec.Command(abfsBox, "hash", srcDirFileCheck).Run()
1303 return err == nil
1304}
1305
Taylor Santiago0af8ea12024-08-20 14:10:50 -07001306func (c *configImpl) sandboxPath(base, in string) string {
1307 if !c.UseABFS() {
1308 return in
1309 }
1310
1311 rel, err := filepath.Rel(base, in)
1312 if err != nil {
1313 return in
1314 }
1315
1316 return filepath.Join(abfsSrcDir, rel)
1317}
1318
Ramy Medhatbbf25672019-07-17 12:30:04 +00001319func (c *configImpl) UseRBE() bool {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001320 // These alternate modes of running Soong do not use RBE / reclient.
Colin Cross8d411ff2023-12-07 10:31:24 -08001321 if c.Queryview() || c.JsonModuleGraph() {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001322 return false
1323 }
1324
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001325 if !c.canSupportRBE() {
Kousik Kumar67ad4342023-06-06 15:09:27 -04001326 return false
1327 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001328
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001329 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001330 v = strings.TrimSpace(v)
1331 if v != "" && v != "false" {
1332 return true
1333 }
1334 }
1335 return false
1336}
1337
1338func (c *configImpl) StartRBE() bool {
1339 if !c.UseRBE() {
1340 return false
1341 }
1342
1343 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1344 v = strings.TrimSpace(v)
1345 if v != "" && v != "false" {
1346 return false
1347 }
1348 }
1349 return true
1350}
1351
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001352func (c *configImpl) rbeProxyLogsDir() string {
1353 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001354 if v, ok := c.environ.Get(f); ok {
1355 return v
1356 }
1357 }
Ramy Medhatbc061762023-10-10 18:36:59 +00001358 return c.rbeTmpDir()
1359}
1360
1361func (c *configImpl) rbeDownloadTmpDir() string {
Cole Faust06ea5312023-10-18 17:38:40 -07001362 for _, f := range []string{"RBE_download_tmp_dir", "FLAG_download_tmp_dir"} {
Ramy Medhatbc061762023-10-10 18:36:59 +00001363 if v, ok := c.environ.Get(f); ok {
1364 return v
1365 }
1366 }
1367 return c.rbeTmpDir()
1368}
1369
1370func (c *configImpl) rbeTmpDir() string {
Yaowen Meid4da2662024-07-24 08:25:12 +00001371 return filepath.Join(c.SoongOutDir(), "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001372}
1373
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001374func (c *configImpl) rbeCacheDir() string {
1375 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1376 if v, ok := c.environ.Get(f); ok {
1377 return v
1378 }
1379 }
1380 return shared.JoinPath(c.SoongOutDir(), "rbe")
1381}
1382
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001383func (c *configImpl) shouldCleanupRBELogsDir() bool {
1384 // Perform a log directory cleanup only when the log directory
1385 // is auto created by the build rather than user-specified.
1386 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1387 if _, ok := c.environ.Get(f); ok {
1388 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001389 }
1390 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001391 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001392}
1393
1394func (c *configImpl) rbeExecRoot() string {
1395 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1396 if v, ok := c.environ.Get(f); ok {
1397 return v
1398 }
1399 }
1400 wd, err := os.Getwd()
1401 if err != nil {
1402 return ""
1403 }
1404 return wd
1405}
1406
1407func (c *configImpl) rbeDir() string {
1408 if v, ok := c.environ.Get("RBE_DIR"); ok {
1409 return v
1410 }
1411 return "prebuilts/remoteexecution-client/live/"
1412}
1413
1414func (c *configImpl) rbeReproxy() string {
1415 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1416 if v, ok := c.environ.Get(f); ok {
1417 return v
1418 }
1419 }
1420 return filepath.Join(c.rbeDir(), "reproxy")
1421}
1422
1423func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001424 credFlags := []string{
1425 "use_application_default_credentials",
1426 "use_gce_credentials",
1427 "credential_file",
1428 "use_google_prod_creds",
1429 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001430 for _, cf := range credFlags {
1431 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1432 if v, ok := c.environ.Get(f); ok {
1433 v = strings.TrimSpace(v)
1434 if v != "" && v != "false" && v != "0" {
1435 return "RBE_" + cf, v
1436 }
1437 }
1438 }
1439 }
1440 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001441}
1442
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001443func (c *configImpl) rbeSockAddr(dir string) (string, error) {
Andus Yuc917eb82024-03-06 21:54:15 +00001444 // Absolute path socket addresses have a prefix of //. This should
1445 // be included in the length limit.
1446 maxNameLen := len(syscall.RawSockaddrUnix{}.Path) - 2
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001447 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1448
1449 name := filepath.Join(dir, base)
1450 if len(name) < maxNameLen {
1451 return name, nil
1452 }
1453
1454 name = filepath.Join("/tmp", base)
1455 if len(name) < maxNameLen {
1456 return name, nil
1457 }
1458
1459 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1460}
1461
Kousik Kumar7bc78192022-04-27 14:52:56 -04001462// IsGooglerEnvironment returns true if the current build is running
1463// on a Google developer machine and false otherwise.
1464func (c *configImpl) IsGooglerEnvironment() bool {
1465 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1466 if v, ok := c.environ.Get(cf); ok {
1467 return v == "googler"
1468 }
1469 return false
1470}
1471
1472// GoogleProdCredsExist determine whether credentials exist on the
1473// Googler machine to use remote execution.
1474func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001475 if googleProdCredsExistCache {
1476 return googleProdCredsExistCache
1477 }
andusyu0b3dc032023-06-21 17:29:32 -04001478 if _, err := exec.Command("/usr/bin/gcertstatus", "-nocheck_ssh").Output(); err != nil {
Kousik Kumar7bc78192022-04-27 14:52:56 -04001479 return false
1480 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001481 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001482 return true
1483}
1484
1485// UseRemoteBuild indicates whether to use a remote build acceleration system
1486// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001487func (c *configImpl) UseRemoteBuild() bool {
1488 return c.UseGoma() || c.UseRBE()
1489}
1490
Kousik Kumar7bc78192022-04-27 14:52:56 -04001491// StubbyExists checks whether the stubby binary exists on the machine running
1492// the build.
1493func (c *configImpl) StubbyExists() bool {
1494 if _, err := exec.LookPath("stubby"); err != nil {
1495 return false
1496 }
1497 return true
1498}
1499
Dan Willemsen1e704462016-08-21 15:17:17 -07001500// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001501// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001502// still limited by Parallel()
1503func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001504 if !c.UseRemoteBuild() {
1505 return 0
1506 }
1507 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1508 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001509 }
1510 return 500
1511}
1512
1513func (c *configImpl) SetKatiArgs(args []string) {
1514 c.katiArgs = args
1515}
1516
1517func (c *configImpl) SetNinjaArgs(args []string) {
1518 c.ninjaArgs = args
1519}
1520
1521func (c *configImpl) SetKatiSuffix(suffix string) {
1522 c.katiSuffix = suffix
1523}
1524
Dan Willemsene0879fc2017-08-04 15:06:27 -07001525func (c *configImpl) LastKatiSuffixFile() string {
1526 return filepath.Join(c.OutDir(), "last_kati_suffix")
1527}
1528
1529func (c *configImpl) HasKatiSuffix() bool {
1530 return c.katiSuffix != ""
1531}
1532
Dan Willemsen1e704462016-08-21 15:17:17 -07001533func (c *configImpl) KatiEnvFile() string {
1534 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1535}
1536
Dan Willemsen29971232018-09-26 14:58:30 -07001537func (c *configImpl) KatiBuildNinjaFile() string {
1538 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001539}
1540
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001541func (c *configImpl) KatiPackageNinjaFile() string {
1542 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1543}
1544
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001545func (c *configImpl) SoongVarsFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001546 targetProduct, err := c.TargetProductOrErr()
1547 if err != nil {
1548 return filepath.Join(c.SoongOutDir(), "soong.variables")
1549 } else {
Qing Shen9e05d1c2024-08-13 02:04:53 +00001550 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+c.CoverageSuffix()+".variables")
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001551 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001552}
1553
Inseob Kim58c802f2024-06-11 10:59:00 +09001554func (c *configImpl) SoongExtraVarsFile() string {
1555 targetProduct, err := c.TargetProductOrErr()
1556 if err != nil {
1557 return filepath.Join(c.SoongOutDir(), "soong.extra.variables")
1558 } else {
Qing Shen9e05d1c2024-08-13 02:04:53 +00001559 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+c.CoverageSuffix()+".extra.variables")
Inseob Kim58c802f2024-06-11 10:59:00 +09001560 }
1561}
1562
Dan Willemsen1e704462016-08-21 15:17:17 -07001563func (c *configImpl) SoongNinjaFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001564 targetProduct, err := c.TargetProductOrErr()
1565 if err != nil {
1566 return filepath.Join(c.SoongOutDir(), "build.ninja")
1567 } else {
Qing Shen9e05d1c2024-08-13 02:04:53 +00001568 return filepath.Join(c.SoongOutDir(), "build."+targetProduct+c.CoverageSuffix()+".ninja")
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001569 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001570}
1571
1572func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001573 if c.katiSuffix == "" {
1574 return filepath.Join(c.OutDir(), "combined.ninja")
1575 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001576 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1577}
1578
1579func (c *configImpl) SoongAndroidMk() string {
Qing Shen9e05d1c2024-08-13 02:04:53 +00001580 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+c.CoverageSuffix()+".mk")
Dan Willemsen1e704462016-08-21 15:17:17 -07001581}
1582
1583func (c *configImpl) SoongMakeVarsMk() string {
Qing Shen9e05d1c2024-08-13 02:04:53 +00001584 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+c.CoverageSuffix()+".mk")
Dan Willemsen1e704462016-08-21 15:17:17 -07001585}
1586
Colin Crossaa9a2732023-10-27 10:54:27 -07001587func (c *configImpl) SoongBuildMetrics() string {
Colin Crossb67b0612023-10-31 10:02:45 -07001588 return filepath.Join(c.LogsDir(), "soong_build_metrics.pb")
Colin Crossaa9a2732023-10-27 10:54:27 -07001589}
1590
Dan Willemsenf052f782017-05-18 15:29:04 -07001591func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001592 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001593}
1594
Dan Willemsen02781d52017-05-12 19:28:13 -07001595func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001596 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1597}
1598
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001599func (c *configImpl) KatiPackageMkDir() string {
1600 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1601}
1602
Dan Willemsenf052f782017-05-18 15:29:04 -07001603func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001604 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001605}
1606
1607func (c *configImpl) HostOut() string {
1608 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1609}
1610
1611// This probably needs to be multi-valued, so not exporting it for now
1612func (c *configImpl) hostCrossOut() string {
1613 if runtime.GOOS == "linux" {
1614 return filepath.Join(c.hostOutRoot(), "windows-x86")
1615 } else {
1616 return ""
1617 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001618}
1619
Dan Willemsen1e704462016-08-21 15:17:17 -07001620func (c *configImpl) HostPrebuiltTag() string {
1621 if runtime.GOOS == "linux" {
1622 return "linux-x86"
1623 } else if runtime.GOOS == "darwin" {
1624 return "darwin-x86"
1625 } else {
1626 panic("Unsupported OS")
1627 }
1628}
Dan Willemsenf173d592017-04-27 14:28:00 -07001629
Taylor Santiago3c16e612024-05-30 14:41:31 -07001630func (c *configImpl) KatiBin() string {
1631 binName := "ckati"
1632 if c.UseABFS() {
1633 binName = "ckati-wrap"
1634 }
1635
1636 return c.PrebuiltBuildTool(binName)
1637}
1638
1639func (c *configImpl) NinjaBin() string {
1640 binName := "ninja"
1641 if c.UseABFS() {
1642 binName = "ninjago"
1643 }
1644 return c.PrebuiltBuildTool(binName)
1645}
1646
Dan Willemsen8122bd52017-10-12 20:20:41 -07001647func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001648 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1649 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001650 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1651 if _, err := os.Stat(asan); err == nil {
1652 return asan
1653 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001654 }
1655 }
1656 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1657}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001658
1659func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1660 c.brokenDupRules = val
1661}
1662
1663func (c *configImpl) BuildBrokenDupRules() bool {
1664 return c.brokenDupRules
1665}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001666
Dan Willemsen25e6f092019-04-09 10:22:43 -07001667func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1668 c.brokenUsesNetwork = val
1669}
1670
1671func (c *configImpl) BuildBrokenUsesNetwork() bool {
1672 return c.brokenUsesNetwork
1673}
1674
Dan Willemsene3336352020-01-02 19:10:38 -08001675func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1676 c.brokenNinjaEnvVars = val
1677}
1678
1679func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1680 return c.brokenNinjaEnvVars
1681}
1682
Spandan Das28a6f192024-07-01 21:00:25 +00001683func (c *configImpl) SetBuildBrokenMissingOutputs(val bool) {
1684 c.brokenMissingOutputs = val
1685}
1686
1687func (c *configImpl) BuildBrokenMissingOutputs() bool {
1688 return c.brokenMissingOutputs
1689}
1690
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001691func (c *configImpl) SetTargetDeviceDir(dir string) {
1692 c.targetDeviceDir = dir
1693}
1694
1695func (c *configImpl) TargetDeviceDir() string {
1696 return c.targetDeviceDir
1697}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001698
Patrice Arruda219eef32020-06-01 17:29:30 +00001699func (c *configImpl) BuildDateTime() string {
1700 return c.buildDateTime
1701}
1702
1703func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001704 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001705}
Patrice Arruda83842d72020-12-08 19:42:08 +00001706
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001707// LogsDir returns the absolute path to the logs directory where build log and
1708// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001709// directory. If the argument dist is specified, the logs directory
1710// is <dist_dir>/logs.
1711func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001712 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001713 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001714 // 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 -05001715 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001716 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001717 absDir, err := filepath.Abs(dir)
1718 if err != nil {
1719 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1720 os.Exit(1)
1721 }
1722 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001723}
1724
Chris Parsons53f68ae2022-03-03 12:01:40 -05001725// MkFileMetrics returns the file path for make-related metrics.
1726func (c *configImpl) MkMetrics() string {
1727 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1728}
1729
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001730func (c *configImpl) SetEmptyNinjaFile(v bool) {
1731 c.emptyNinjaFile = v
1732}
1733
1734func (c *configImpl) EmptyNinjaFile() bool {
1735 return c.emptyNinjaFile
1736}
Yu Liu6e13b402021-07-27 14:29:06 -07001737
MarkDacekd0e7cd32022-12-02 22:22:40 +00001738func (c *configImpl) SkipMetricsUpload() bool {
Taylor Santiago0af8ea12024-08-20 14:10:50 -07001739 // b/362625275 - Metrics upload sometimes prevents abfs unmount
1740 if c.UseABFS() {
1741 return true
1742 }
1743
MarkDacekd0e7cd32022-12-02 22:22:40 +00001744 return c.skipMetricsUpload
1745}
1746
MarkDacekf47e1422023-04-19 16:47:36 +00001747func (c *configImpl) EnsureAllowlistIntegrity() bool {
1748 return c.ensureAllowlistIntegrity
1749}
1750
MarkDacek6614d9c2022-12-07 21:57:38 +00001751// Returns a Time object if one was passed via a command-line flag.
1752// Otherwise returns the passed default.
1753func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1754 if c.buildStartedTime == 0 {
1755 return defaultTime
1756 }
1757 return time.UnixMilli(c.buildStartedTime)
1758}
1759
Yu Liu6e13b402021-07-27 14:29:06 -07001760func GetMetricsUploader(topDir string, env *Environment) string {
1761 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1762 metricsUploader := filepath.Join(topDir, p)
1763 if _, err := os.Stat(metricsUploader); err == nil {
1764 return metricsUploader
1765 }
1766 }
1767
1768 return ""
1769}