blob: 1d5269c7c9c746fecc952b6e7d1b89348b510bb9 [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",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700316 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700317 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700318
319 // Drop make flags
320 "MAKEFLAGS",
321 "MAKELEVEL",
322 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700323
324 // Set in envsetup.sh, reset in makefiles
325 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700326
327 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
328 "ANDROID_BUILD_TOP",
329 "ANDROID_HOST_OUT",
330 "ANDROID_PRODUCT_OUT",
331 "ANDROID_HOST_OUT_TESTCASES",
332 "ANDROID_TARGET_OUT_TESTCASES",
333 "ANDROID_TOOLCHAIN",
334 "ANDROID_TOOLCHAIN_2ND_ARCH",
335 "ANDROID_DEV_SCRIPTS",
336 "ANDROID_EMULATOR_PREBUILTS",
337 "ANDROID_PRE_BUILD_PATHS",
Joe Onoratoe5ed3472024-02-02 14:52:05 -0800338
339 // We read it here already, don't let others share in the fun
340 "GENERATE_SOONG_DEBUG",
Dan Willemsen1e704462016-08-21 15:17:17 -0700341 )
342
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400343 if ret.UseGoma() || ret.ForceUseGoma() {
344 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
345 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400346 }
347
Dan Willemsen1e704462016-08-21 15:17:17 -0700348 // Tell python not to spam the source tree with .pyc files.
349 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
350
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400351 tmpDir := absPath(ctx, ret.TempDir())
352 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800353
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700354 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
355 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
356 "llvm-binutils-stable/llvm-symbolizer")
357 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
358
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800359 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700360 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800361
Yu Liu6e13b402021-07-27 14:29:06 -0700362 srcDir := absPath(ctx, ".")
363 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700364 ctx.Println("You are building in a directory whose absolute path contains a space character:")
365 ctx.Println()
366 ctx.Printf("%q\n", srcDir)
367 ctx.Println()
368 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700369 }
370
Yu Liu6e13b402021-07-27 14:29:06 -0700371 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
372
Dan Willemsendb8457c2017-05-12 16:38:17 -0700373 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700374 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
375 ctx.Println()
376 ctx.Printf("%q\n", outDir)
377 ctx.Println()
378 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700379 }
380
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000381 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700382 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
383 ctx.Println()
384 ctx.Printf("%q\n", distDir)
385 ctx.Println()
386 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700387 }
388
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700389 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000390 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
Sorin Basca0760c892023-11-29 19:13:55 +0000391 java21Home := filepath.Join("prebuilts/jdk/jdk21", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700392 javaHome := func() string {
393 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
394 return override
395 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000396 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
Sorin Basca5dfa2382024-03-11 17:23:06 +0000397 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 +0100398 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000399 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
Sorin Basca5dfa2382024-03-11 17:23:06 +0000400 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 +0000401 }
Sorin Basca5dfa2382024-03-11 17:23:06 +0000402 if toolchain21, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK21_TOOLCHAIN"); ok && toolchain21 != "true" {
403 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK21_TOOLCHAIN is no longer supported. An OpenJDK 21 toolchain is now the global default.")
404 }
405 return java21Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700406 }()
407 absJavaHome := absPath(ctx, javaHome)
408
Dan Willemsened869522018-01-08 14:58:46 -0800409 ret.configureLocale(ctx)
410
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700411 newPath := []string{filepath.Join(absJavaHome, "bin")}
412 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
413 newPath = append(newPath, path)
414 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100415
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700416 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
417 ret.environ.Set("JAVA_HOME", absJavaHome)
418 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000419 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700420 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
421
Colin Crossfe5ed4d2023-07-28 09:27:23 -0700422 // b/286885495, https://bugzilla.redhat.com/show_bug.cgi?id=2227130: some versions of Fedora include patches
423 // to unzip to enable zipbomb detection that incorrectly handle zip64 and data descriptors and fail on large
424 // zip files produced by soong_zip. Disable zipbomb detection.
425 ret.environ.Set("UNZIP_DISABLE_ZIPBOMB_DETECTION", "TRUE")
426
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800427 outDir := ret.OutDir()
428 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800429 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800430 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800431 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800432 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800433 }
Colin Cross28f527c2019-11-26 16:19:04 -0800434
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800435 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
436
Cole Faust583dfb42023-09-28 13:56:30 -0700437 if _, ok := ret.environ.Get("BUILD_USERNAME"); !ok {
438 username := "unknown"
439 if u, err := user.Current(); err == nil {
440 username = u.Username
441 } else {
442 ctx.Println("Failed to get current user:", err)
443 }
444 ret.environ.Set("BUILD_USERNAME", username)
445 }
446
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400447 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400448 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400449 ret.environ.Set(k, v)
450 }
451 }
452
Patrice Arruda96850362020-08-11 20:41:11 +0000453 c := Config{ret}
454 storeConfigMetrics(ctx, c)
455 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700456}
457
Patrice Arruda13848222019-04-22 17:12:02 -0700458// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
459// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700460func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
461 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700462}
463
LaMont Jones9a912862023-11-06 22:11:08 +0000464// Prepare for getting make variables. For them to be accurate, we need to have
465// obtained PRODUCT_RELEASE_CONFIG_MAPS.
466//
467// Returns:
468//
469// Whether config should be called again.
470//
471// TODO: when converting product config to a declarative language, make sure
472// that PRODUCT_RELEASE_CONFIG_MAPS is properly handled as a separate step in
473// that process.
474func SetProductReleaseConfigMaps(ctx Context, config Config) bool {
475 ctx.BeginTrace(metrics.RunKati, "SetProductReleaseConfigMaps")
476 defer ctx.EndTrace()
477
478 if config.SkipConfig() {
479 // This duplicates the logic from Build to skip product config
480 // if the user has explicitly said to.
481 return false
482 }
483
484 releaseConfigVars := []string{
485 "PRODUCT_RELEASE_CONFIG_MAPS",
486 }
487
488 origValue, _ := config.environ.Get("PRODUCT_RELEASE_CONFIG_MAPS")
489 // Get the PRODUCT_RELEASE_CONFIG_MAPS for this product, to avoid polluting the environment
490 // when we run product config to get the rest of the make vars.
491 releaseMapVars, err := dumpMakeVars(ctx, config, nil, releaseConfigVars, false, "")
492 if err != nil {
493 ctx.Fatalln("Error getting PRODUCT_RELEASE_CONFIG_MAPS:", err)
494 }
495 productReleaseConfigMaps := releaseMapVars["PRODUCT_RELEASE_CONFIG_MAPS"]
496 os.Setenv("PRODUCT_RELEASE_CONFIG_MAPS", productReleaseConfigMaps)
497 return origValue != productReleaseConfigMaps
498}
499
Patrice Arruda96850362020-08-11 20:41:11 +0000500// storeConfigMetrics selects a set of configuration information and store in
501// the metrics system for further analysis.
502func storeConfigMetrics(ctx Context, config Config) {
503 if ctx.Metrics == nil {
504 return
505 }
506
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400507 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000508
509 s := &smpb.SystemResourceInfo{
510 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
511 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
512 }
513 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000514}
515
Jeongik Cha8d63d562023-03-17 03:52:13 +0900516func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900517 switch s {
518 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900519 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900520 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900521 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900522 case EXTERNAL_FILE:
523 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900524 case HINT_FROM_SOONG:
525 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900526 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900527 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900528 }
529}
530
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400531func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700532 c := &smpb.BuildConfig{
Colin Cross8d411ff2023-12-07 10:31:24 -0800533 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
534 UseGoma: proto.Bool(config.UseGoma()),
535 UseRbe: proto.Bool(config.UseRBE()),
536 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400537 }
Yu Liue737a992021-10-04 13:21:41 -0700538 c.Targets = append(c.Targets, config.arguments...)
539
540 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400541}
542
Patrice Arruda13848222019-04-22 17:12:02 -0700543// getConfigArgs processes the command arguments based on the build action and creates a set of new
544// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700545func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700546 // The next block of code verifies that the current directory is the root directory of the source
547 // tree. It then finds the relative path of dir based on the root directory of the source tree
548 // and verify that dir is inside of the source tree.
549 checkTopDir(ctx)
550 topDir, err := os.Getwd()
551 if err != nil {
552 ctx.Fatalf("Error retrieving top directory: %v", err)
553 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700554 dir, err = filepath.EvalSymlinks(dir)
555 if err != nil {
556 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
557 }
Patrice Arruda13848222019-04-22 17:12:02 -0700558 dir, err = filepath.Abs(dir)
559 if err != nil {
560 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
561 }
562 relDir, err := filepath.Rel(topDir, dir)
563 if err != nil {
564 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
565 }
566 // If there are ".." in the path, it's not in the source tree.
567 if strings.Contains(relDir, "..") {
568 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
569 }
570
571 configArgs := args[:]
572
573 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
574 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
575 targetNamePrefix := "MODULES-IN-"
576 if inList("GET-INSTALL-PATH", configArgs) {
577 targetNamePrefix = "GET-INSTALL-PATH-IN-"
578 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
579 }
580
Patrice Arruda13848222019-04-22 17:12:02 -0700581 var targets []string
582
583 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700584 case BUILD_MODULES:
585 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700586 case BUILD_MODULES_IN_A_DIRECTORY:
587 // If dir is the root source tree, all the modules are built of the source tree are built so
588 // no need to find the build file.
589 if topDir == dir {
590 break
591 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700592
Patrice Arruda13848222019-04-22 17:12:02 -0700593 buildFile := findBuildFile(ctx, relDir)
594 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700595 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700596 }
Patrice Arruda13848222019-04-22 17:12:02 -0700597 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
598 case BUILD_MODULES_IN_DIRECTORIES:
599 newConfigArgs, dirs := splitArgs(configArgs)
600 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700601 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700602 }
603
604 // Tidy only override all other specified targets.
605 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
606 if tidyOnly == "true" || tidyOnly == "1" {
607 configArgs = append(configArgs, "tidy_only")
608 } else {
609 configArgs = append(configArgs, targets...)
610 }
611
612 return configArgs
613}
614
615// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
616func convertToTarget(dir string, targetNamePrefix string) string {
617 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
618}
619
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700620// hasBuildFile returns true if dir contains an Android build file.
621func hasBuildFile(ctx Context, dir string) bool {
622 for _, buildFile := range buildFiles {
623 _, err := os.Stat(filepath.Join(dir, buildFile))
624 if err == nil {
625 return true
626 }
627 if !os.IsNotExist(err) {
628 ctx.Fatalf("Error retrieving the build file stats: %v", err)
629 }
630 }
631 return false
632}
633
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700634// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
635// in the current and any sub directory of dir. If a build file is not found, traverse the path
636// up by one directory and repeat again until either a build file is found or reached to the root
637// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
638// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700639func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700640 // If the string is empty or ".", assume it is top directory of the source tree.
641 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700642 return ""
643 }
644
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700645 found := false
646 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
647 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
648 if err != nil {
649 return err
650 }
651 if found {
652 return filepath.SkipDir
653 }
654 if info.IsDir() {
655 return nil
656 }
657 for _, buildFile := range buildFiles {
658 if info.Name() == buildFile {
659 found = true
660 return filepath.SkipDir
661 }
662 }
663 return nil
664 })
665 if err != nil {
666 ctx.Fatalf("Error finding Android build file: %v", err)
667 }
668
669 if found {
670 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700671 }
672 }
673
674 return ""
675}
676
677// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
678func splitArgs(args []string) (newArgs []string, dirs []string) {
679 specialArgs := map[string]bool{
680 "showcommands": true,
681 "snod": true,
682 "dist": true,
683 "checkbuild": true,
684 }
685
686 newArgs = []string{}
687 dirs = []string{}
688
689 for _, arg := range args {
690 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
691 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
692 newArgs = append(newArgs, arg)
693 continue
694 }
695
696 if _, ok := specialArgs[arg]; ok {
697 newArgs = append(newArgs, arg)
698 continue
699 }
700
701 dirs = append(dirs, arg)
702 }
703
704 return newArgs, dirs
705}
706
707// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
708// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
709// source root tree where the build action command was invoked. Each directory is validated if the
710// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700711func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700712 for _, dir := range dirs {
713 // The directory may have specified specific modules to build. ":" is the separator to separate
714 // the directory and the list of modules.
715 s := strings.Split(dir, ":")
716 l := len(s)
717 if l > 2 { // more than one ":" was specified.
718 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
719 }
720
721 dir = filepath.Join(relDir, s[0])
722 if _, err := os.Stat(dir); err != nil {
723 ctx.Fatalf("couldn't find directory %s", dir)
724 }
725
726 // Verify that if there are any targets specified after ":". Each target is separated by ",".
727 var newTargets []string
728 if l == 2 && s[1] != "" {
729 newTargets = strings.Split(s[1], ",")
730 if inList("", newTargets) {
731 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
732 }
733 }
734
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700735 // If there are specified targets to build in dir, an android build file must exist for the one
736 // shot build. For the non-targets case, find the appropriate build file and build all the
737 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700738 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700739 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700740 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
741 }
742 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700743 buildFile := findBuildFile(ctx, dir)
744 if buildFile == "" {
745 ctx.Fatalf("Build file not found for %s directory", dir)
746 }
747 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700748 }
749
Patrice Arruda13848222019-04-22 17:12:02 -0700750 targets = append(targets, newTargets...)
751 }
752
Dan Willemsence41e942019-07-29 23:39:30 -0700753 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700754}
755
Dan Willemsen9b587492017-07-10 22:13:00 -0700756func (c *configImpl) parseArgs(ctx Context, args []string) {
757 for i := 0; i < len(args); i++ {
758 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100759 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700760 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200761 } else if arg == "--empty-ninja-file" {
762 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100763 } else if arg == "--skip-ninja" {
764 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700765 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700766 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
767 // but it does run a Kati ninja file if the .kati_enabled marker file was created
768 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000769 c.skipConfig = true
770 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100771 } else if arg == "--soong-only" {
772 c.skipKati = true
773 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200774 } else if arg == "--config-only" {
775 c.skipKati = true
776 c.skipKatiNinja = true
777 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700778 } else if arg == "--skip-config" {
779 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700780 } else if arg == "--skip-soong-tests" {
781 c.skipSoongTests = true
Colin Cross106d6ef2023-10-24 10:34:56 -0700782 } else if arg == "--no-skip-soong-tests" {
783 c.skipSoongTests = false
MarkDacekd0e7cd32022-12-02 22:22:40 +0000784 } else if arg == "--skip-metrics-upload" {
785 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500786 } else if arg == "--mk-metrics" {
787 c.reportMkMetrics = true
Spandan Das394aa322022-11-03 17:02:10 +0000788 } else if arg == "--search-api-dir" {
789 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900790 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
791 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
792 if source == "ninja_log" {
793 c.ninjaWeightListSource = NINJA_LOG
794 } else if source == "evenly_distributed" {
795 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
796 } else if source == "not_used" {
797 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900798 } else if source == "soong" {
799 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900800 } else if strings.HasPrefix(source, "file,") {
801 c.ninjaWeightListSource = EXTERNAL_FILE
802 filePath := strings.TrimPrefix(source, "file,")
803 err := validateNinjaWeightList(filePath)
804 if err != nil {
805 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
806 }
807 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
808 if err != nil {
809 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
810 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900811 } else {
812 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
813 }
Jihoon Kang2a929ad2023-06-08 19:02:07 +0000814 } else if arg == "--build-from-source-stub" {
815 c.buildFromSourceStub = true
Yu Liufa297642024-06-11 00:13:02 +0000816 } else if arg == "--incremental-build-actions" {
817 c.incrementalBuildActions = true
MarkDacekb96561e2022-12-02 04:34:43 +0000818 } else if strings.HasPrefix(arg, "--build-command=") {
819 buildCmd := strings.TrimPrefix(arg, "--build-command=")
820 // remove quotations
821 buildCmd = strings.TrimPrefix(buildCmd, "\"")
822 buildCmd = strings.TrimSuffix(buildCmd, "\"")
823 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacek6614d9c2022-12-07 21:57:38 +0000824 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
825 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
826 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
827 if err == nil {
828 c.buildStartedTime = val
829 } else {
830 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
831 }
MarkDacekf47e1422023-04-19 16:47:36 +0000832 } else if arg == "--ensure-allowlist-integrity" {
833 c.ensureAllowlistIntegrity = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700834 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700835 parseArgNum := func(def int) int {
836 if len(arg) > 2 {
837 p, err := strconv.ParseUint(arg[2:], 10, 31)
838 if err != nil {
839 ctx.Fatalf("Failed to parse %q: %v", arg, err)
840 }
841 return int(p)
842 } else if i+1 < len(args) {
843 p, err := strconv.ParseUint(args[i+1], 10, 31)
844 if err == nil {
845 i++
846 return int(p)
847 }
848 }
849 return def
850 }
851
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700852 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700853 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700854 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700855 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700856 } else {
857 ctx.Fatalln("Unknown option:", arg)
858 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700859 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700860 if k == "OUT_DIR" {
861 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
862 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700863 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700864 } else if arg == "dist" {
865 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200866 } else if arg == "json-module-graph" {
867 c.jsonModuleGraph = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200868 } else if arg == "queryview" {
869 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200870 } else if arg == "soong_docs" {
871 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700872 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700873 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800874 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700875 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700876 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700877 }
878 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700879}
880
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900881func validateNinjaWeightList(weightListFilePath string) (err error) {
882 data, err := os.ReadFile(weightListFilePath)
883 if err != nil {
884 return
885 }
886 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
887 for _, line := range lines {
888 fields := strings.Split(line, ",")
889 if len(fields) != 2 {
890 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
891 }
892 _, err = strconv.Atoi(fields[1])
893 if err != nil {
894 return
895 }
896 }
897 return
898}
899
Dan Willemsened869522018-01-08 14:58:46 -0800900func (c *configImpl) configureLocale(ctx Context) {
901 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
902 output, err := cmd.Output()
903
904 var locales []string
905 if err == nil {
906 locales = strings.Split(string(output), "\n")
907 } else {
908 // If we're unable to list the locales, let's assume en_US.UTF-8
909 locales = []string{"en_US.UTF-8"}
910 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
911 }
912
913 // gettext uses LANGUAGE, which is passed directly through
914
915 // For LANG and LC_*, only preserve the evaluated version of
916 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800917 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800918 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800919 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800920 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800921 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800922 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800923 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800924 }
925
926 c.environ.UnsetWithPrefix("LC_")
927
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800928 if userLang != "" {
929 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800930 }
931
932 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
933 // for others)
934 if inList("C.UTF-8", locales) {
935 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500936 } else if inList("C.utf8", locales) {
937 // These normalize to the same thing
938 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800939 } else if inList("en_US.UTF-8", locales) {
940 c.environ.Set("LANG", "en_US.UTF-8")
941 } else if inList("en_US.utf8", locales) {
942 // These normalize to the same thing
943 c.environ.Set("LANG", "en_US.UTF-8")
944 } else {
945 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
946 }
947}
948
Dan Willemsen1e704462016-08-21 15:17:17 -0700949func (c *configImpl) Environment() *Environment {
950 return c.environ
951}
952
953func (c *configImpl) Arguments() []string {
954 return c.arguments
955}
956
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200957func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200958 if len(c.Arguments()) > 0 {
959 // Explicit targets requested that are not special targets like b2pbuild
960 // or the JSON module graph
961 return true
962 }
963
Colin Cross8d411ff2023-12-07 10:31:24 -0800964 if !c.JsonModuleGraph() && !c.Queryview() && !c.SoongDocs() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200965 // Command line was empty, the default Ninja target is built
966 return true
967 }
968
Colin Cross8d411ff2023-12-07 10:31:24 -0800969 if c.Dist() {
Liz Kammer88677422021-12-15 15:03:19 -0500970 return true
971 }
972
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200973 // build.ninja doesn't need to be generated
974 return false
975}
976
Dan Willemsen1e704462016-08-21 15:17:17 -0700977func (c *configImpl) OutDir() string {
978 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700979 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700980 }
981 return "out"
982}
983
Dan Willemsen8a073a82017-02-04 17:30:44 -0800984func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400985 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000986}
987
988func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700989 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800990}
991
Dan Willemsen1e704462016-08-21 15:17:17 -0700992func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000993 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700994 return c.arguments
995 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700996 return c.ninjaArgs
997}
998
999func (c *configImpl) SoongOutDir() string {
1000 return filepath.Join(c.OutDir(), "soong")
1001}
1002
Spandan Das394aa322022-11-03 17:02:10 +00001003func (c *configImpl) ApiSurfacesOutDir() string {
1004 return filepath.Join(c.OutDir(), "api_surfaces")
1005}
1006
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001007func (c *configImpl) PrebuiltOS() string {
1008 switch runtime.GOOS {
1009 case "linux":
1010 return "linux-x86"
1011 case "darwin":
1012 return "darwin-x86"
1013 default:
1014 panic("Unknown GOOS")
1015 }
1016}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001017
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001018func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001019 if c.SkipKatiNinja() {
1020 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1021 } else {
1022 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1023 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001024}
1025
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001026func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001027 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001028}
1029
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001030func (c *configImpl) UsedEnvFile(tag string) string {
Kiyoung Kimeaa55a82023-06-05 16:56:49 +09001031 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1032 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+v+"."+tag)
1033 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001034 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1035}
1036
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001037func (c *configImpl) SoongDocsHtml() string {
1038 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1039}
1040
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001041func (c *configImpl) QueryviewMarkerFile() string {
1042 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1043}
1044
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001045func (c *configImpl) ModuleGraphFile() string {
1046 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1047}
1048
kgui67007242022-01-25 13:50:25 +08001049func (c *configImpl) ModuleActionsFile() string {
1050 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1051}
1052
Jeff Gastonefc1b412017-03-29 17:29:06 -07001053func (c *configImpl) TempDir() string {
1054 return shared.TempDirForOutDir(c.SoongOutDir())
1055}
1056
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001057func (c *configImpl) FileListDir() string {
1058 return filepath.Join(c.OutDir(), ".module_paths")
1059}
1060
Dan Willemsen1e704462016-08-21 15:17:17 -07001061func (c *configImpl) KatiSuffix() string {
1062 if c.katiSuffix != "" {
1063 return c.katiSuffix
1064 }
1065 panic("SetKatiSuffix has not been called")
1066}
1067
Colin Cross37193492017-11-16 17:55:00 -08001068// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1069// user is interested in additional checks at the expense of build time.
1070func (c *configImpl) Checkbuild() bool {
1071 return c.checkbuild
1072}
1073
Dan Willemsen8a073a82017-02-04 17:30:44 -08001074func (c *configImpl) Dist() bool {
1075 return c.dist
1076}
1077
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001078func (c *configImpl) JsonModuleGraph() bool {
1079 return c.jsonModuleGraph
1080}
1081
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001082func (c *configImpl) Queryview() bool {
1083 return c.queryview
1084}
1085
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001086func (c *configImpl) SoongDocs() bool {
1087 return c.soongDocs
1088}
1089
Dan Willemsen1e704462016-08-21 15:17:17 -07001090func (c *configImpl) IsVerbose() bool {
1091 return c.verbose
1092}
1093
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001094func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1095 return c.ninjaWeightListSource
1096}
1097
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001098func (c *configImpl) SkipKati() bool {
1099 return c.skipKati
1100}
1101
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001102func (c *configImpl) SkipKatiNinja() bool {
1103 return c.skipKatiNinja
1104}
1105
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001106func (c *configImpl) SkipSoong() bool {
1107 return c.skipSoong
1108}
1109
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001110func (c *configImpl) SkipNinja() bool {
1111 return c.skipNinja
1112}
1113
Anton Hansson5a7861a2021-06-04 10:09:01 +01001114func (c *configImpl) SetSkipNinja(v bool) {
1115 c.skipNinja = v
1116}
1117
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001118func (c *configImpl) SkipConfig() bool {
1119 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001120}
1121
Jihoon Kang1bff0342023-01-17 20:40:22 +00001122func (c *configImpl) BuildFromTextStub() bool {
Jihoon Kang2a929ad2023-06-08 19:02:07 +00001123 return !c.buildFromSourceStub
Jihoon Kang1bff0342023-01-17 20:40:22 +00001124}
1125
Dan Willemsen1e704462016-08-21 15:17:17 -07001126func (c *configImpl) TargetProduct() string {
1127 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1128 return v
1129 }
1130 panic("TARGET_PRODUCT is not defined")
1131}
1132
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001133func (c *configImpl) TargetProductOrErr() (string, error) {
1134 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1135 return v, nil
1136 }
1137 return "", fmt.Errorf("TARGET_PRODUCT is not defined")
1138}
1139
Dan Willemsen02781d52017-05-12 19:28:13 -07001140func (c *configImpl) TargetDevice() string {
1141 return c.targetDevice
1142}
1143
1144func (c *configImpl) SetTargetDevice(device string) {
1145 c.targetDevice = device
1146}
1147
1148func (c *configImpl) TargetBuildVariant() string {
1149 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1150 return v
1151 }
1152 panic("TARGET_BUILD_VARIANT is not defined")
1153}
1154
Dan Willemsen1e704462016-08-21 15:17:17 -07001155func (c *configImpl) KatiArgs() []string {
1156 return c.katiArgs
1157}
1158
1159func (c *configImpl) Parallel() int {
1160 return c.parallel
1161}
1162
Sam Delmerico98a73292023-02-21 11:50:29 -05001163func (c *configImpl) GetSourceRootDirs() []string {
1164 return c.sourceRootDirs
1165}
1166
1167func (c *configImpl) SetSourceRootDirs(i []string) {
1168 c.sourceRootDirs = i
1169}
1170
MarkDacek6614d9c2022-12-07 21:57:38 +00001171func (c *configImpl) GetLogsPrefix() string {
1172 return c.logsPrefix
1173}
1174
1175func (c *configImpl) SetLogsPrefix(prefix string) {
1176 c.logsPrefix = prefix
1177}
1178
Colin Cross8b8bec32019-11-15 13:18:43 -08001179func (c *configImpl) HighmemParallel() int {
1180 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1181 return i
1182 }
1183
1184 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1185 parallel := c.Parallel()
1186 if c.UseRemoteBuild() {
1187 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1188 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1189 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1190 // Return 1/16th of the size of the local pool, rounding up.
1191 return (parallel + 15) / 16
1192 } else if c.totalRAM == 0 {
1193 // Couldn't detect the total RAM, don't restrict highmem processes.
1194 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001195 } else if c.totalRAM <= 16*1024*1024*1024 {
1196 // Less than 16GB of ram, restrict to 1 highmem processes
1197 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001198 } else if c.totalRAM <= 32*1024*1024*1024 {
1199 // Less than 32GB of ram, restrict to 2 highmem processes
1200 return 2
1201 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1202 // If less than 8GB total RAM per process, reduce the number of highmem processes
1203 return p
1204 }
1205 // No restriction on highmem processes
1206 return parallel
1207}
1208
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001209func (c *configImpl) TotalRAM() uint64 {
1210 return c.totalRAM
1211}
1212
Kousik Kumarec478642020-09-21 13:39:24 -04001213// ForceUseGoma determines whether we should override Goma deprecation
1214// and use Goma for the current build or not.
1215func (c *configImpl) ForceUseGoma() bool {
1216 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1217 v = strings.TrimSpace(v)
1218 if v != "" && v != "false" {
1219 return true
1220 }
1221 }
1222 return false
1223}
1224
Dan Willemsen1e704462016-08-21 15:17:17 -07001225func (c *configImpl) UseGoma() bool {
1226 if v, ok := c.environ.Get("USE_GOMA"); ok {
1227 v = strings.TrimSpace(v)
1228 if v != "" && v != "false" {
1229 return true
1230 }
1231 }
1232 return false
1233}
1234
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001235func (c *configImpl) StartGoma() bool {
1236 if !c.UseGoma() {
1237 return false
1238 }
1239
1240 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1241 v = strings.TrimSpace(v)
1242 if v != "" && v != "false" {
1243 return false
1244 }
1245 }
1246 return true
1247}
1248
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001249func (c *configImpl) canSupportRBE() bool {
Joe Onorato86f50e72024-06-24 14:28:25 -07001250 // Only supported on linux
1251 if runtime.GOOS != "linux" {
1252 return false
1253 }
1254
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001255 // Do not use RBE with prod credentials in scenarios when stubby doesn't exist, since
1256 // its unlikely that we will be able to obtain necessary creds without stubby.
1257 authType, _ := c.rbeAuth()
1258 if !c.StubbyExists() && strings.Contains(authType, "use_google_prod_creds") {
1259 return false
1260 }
1261 return true
1262}
1263
Ramy Medhatbbf25672019-07-17 12:30:04 +00001264func (c *configImpl) UseRBE() bool {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001265 // These alternate modes of running Soong do not use RBE / reclient.
Colin Cross8d411ff2023-12-07 10:31:24 -08001266 if c.Queryview() || c.JsonModuleGraph() {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001267 return false
1268 }
1269
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001270 if !c.canSupportRBE() {
Kousik Kumar67ad4342023-06-06 15:09:27 -04001271 return false
1272 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001273
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001274 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001275 v = strings.TrimSpace(v)
1276 if v != "" && v != "false" {
1277 return true
1278 }
1279 }
1280 return false
1281}
1282
1283func (c *configImpl) StartRBE() bool {
1284 if !c.UseRBE() {
1285 return false
1286 }
1287
1288 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1289 v = strings.TrimSpace(v)
1290 if v != "" && v != "false" {
1291 return false
1292 }
1293 }
1294 return true
1295}
1296
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001297func (c *configImpl) rbeProxyLogsDir() string {
1298 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001299 if v, ok := c.environ.Get(f); ok {
1300 return v
1301 }
1302 }
Ramy Medhatbc061762023-10-10 18:36:59 +00001303 return c.rbeTmpDir()
1304}
1305
1306func (c *configImpl) rbeDownloadTmpDir() string {
Cole Faust06ea5312023-10-18 17:38:40 -07001307 for _, f := range []string{"RBE_download_tmp_dir", "FLAG_download_tmp_dir"} {
Ramy Medhatbc061762023-10-10 18:36:59 +00001308 if v, ok := c.environ.Get(f); ok {
1309 return v
1310 }
1311 }
1312 return c.rbeTmpDir()
1313}
1314
1315func (c *configImpl) rbeTmpDir() string {
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001316 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1317 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001318}
1319
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001320func (c *configImpl) rbeCacheDir() string {
1321 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1322 if v, ok := c.environ.Get(f); ok {
1323 return v
1324 }
1325 }
1326 return shared.JoinPath(c.SoongOutDir(), "rbe")
1327}
1328
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001329func (c *configImpl) shouldCleanupRBELogsDir() bool {
1330 // Perform a log directory cleanup only when the log directory
1331 // is auto created by the build rather than user-specified.
1332 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1333 if _, ok := c.environ.Get(f); ok {
1334 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001335 }
1336 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001337 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001338}
1339
1340func (c *configImpl) rbeExecRoot() string {
1341 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1342 if v, ok := c.environ.Get(f); ok {
1343 return v
1344 }
1345 }
1346 wd, err := os.Getwd()
1347 if err != nil {
1348 return ""
1349 }
1350 return wd
1351}
1352
1353func (c *configImpl) rbeDir() string {
1354 if v, ok := c.environ.Get("RBE_DIR"); ok {
1355 return v
1356 }
1357 return "prebuilts/remoteexecution-client/live/"
1358}
1359
1360func (c *configImpl) rbeReproxy() string {
1361 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1362 if v, ok := c.environ.Get(f); ok {
1363 return v
1364 }
1365 }
1366 return filepath.Join(c.rbeDir(), "reproxy")
1367}
1368
1369func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001370 credFlags := []string{
1371 "use_application_default_credentials",
1372 "use_gce_credentials",
1373 "credential_file",
1374 "use_google_prod_creds",
1375 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001376 for _, cf := range credFlags {
1377 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1378 if v, ok := c.environ.Get(f); ok {
1379 v = strings.TrimSpace(v)
1380 if v != "" && v != "false" && v != "0" {
1381 return "RBE_" + cf, v
1382 }
1383 }
1384 }
1385 }
1386 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001387}
1388
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001389func (c *configImpl) rbeSockAddr(dir string) (string, error) {
Andus Yuc917eb82024-03-06 21:54:15 +00001390 // Absolute path socket addresses have a prefix of //. This should
1391 // be included in the length limit.
1392 maxNameLen := len(syscall.RawSockaddrUnix{}.Path) - 2
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001393 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1394
1395 name := filepath.Join(dir, base)
1396 if len(name) < maxNameLen {
1397 return name, nil
1398 }
1399
1400 name = filepath.Join("/tmp", base)
1401 if len(name) < maxNameLen {
1402 return name, nil
1403 }
1404
1405 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1406}
1407
Kousik Kumar7bc78192022-04-27 14:52:56 -04001408// IsGooglerEnvironment returns true if the current build is running
1409// on a Google developer machine and false otherwise.
1410func (c *configImpl) IsGooglerEnvironment() bool {
1411 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1412 if v, ok := c.environ.Get(cf); ok {
1413 return v == "googler"
1414 }
1415 return false
1416}
1417
1418// GoogleProdCredsExist determine whether credentials exist on the
1419// Googler machine to use remote execution.
1420func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001421 if googleProdCredsExistCache {
1422 return googleProdCredsExistCache
1423 }
andusyu0b3dc032023-06-21 17:29:32 -04001424 if _, err := exec.Command("/usr/bin/gcertstatus", "-nocheck_ssh").Output(); err != nil {
Kousik Kumar7bc78192022-04-27 14:52:56 -04001425 return false
1426 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001427 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001428 return true
1429}
1430
1431// UseRemoteBuild indicates whether to use a remote build acceleration system
1432// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001433func (c *configImpl) UseRemoteBuild() bool {
1434 return c.UseGoma() || c.UseRBE()
1435}
1436
Kousik Kumar7bc78192022-04-27 14:52:56 -04001437// StubbyExists checks whether the stubby binary exists on the machine running
1438// the build.
1439func (c *configImpl) StubbyExists() bool {
1440 if _, err := exec.LookPath("stubby"); err != nil {
1441 return false
1442 }
1443 return true
1444}
1445
Dan Willemsen1e704462016-08-21 15:17:17 -07001446// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001447// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001448// still limited by Parallel()
1449func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001450 if !c.UseRemoteBuild() {
1451 return 0
1452 }
1453 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1454 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001455 }
1456 return 500
1457}
1458
1459func (c *configImpl) SetKatiArgs(args []string) {
1460 c.katiArgs = args
1461}
1462
1463func (c *configImpl) SetNinjaArgs(args []string) {
1464 c.ninjaArgs = args
1465}
1466
1467func (c *configImpl) SetKatiSuffix(suffix string) {
1468 c.katiSuffix = suffix
1469}
1470
Dan Willemsene0879fc2017-08-04 15:06:27 -07001471func (c *configImpl) LastKatiSuffixFile() string {
1472 return filepath.Join(c.OutDir(), "last_kati_suffix")
1473}
1474
1475func (c *configImpl) HasKatiSuffix() bool {
1476 return c.katiSuffix != ""
1477}
1478
Dan Willemsen1e704462016-08-21 15:17:17 -07001479func (c *configImpl) KatiEnvFile() string {
1480 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1481}
1482
Dan Willemsen29971232018-09-26 14:58:30 -07001483func (c *configImpl) KatiBuildNinjaFile() string {
1484 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001485}
1486
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001487func (c *configImpl) KatiPackageNinjaFile() string {
1488 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1489}
1490
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001491func (c *configImpl) SoongVarsFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001492 targetProduct, err := c.TargetProductOrErr()
1493 if err != nil {
1494 return filepath.Join(c.SoongOutDir(), "soong.variables")
1495 } else {
1496 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+".variables")
1497 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001498}
1499
Inseob Kim58c802f2024-06-11 10:59:00 +09001500func (c *configImpl) SoongExtraVarsFile() string {
1501 targetProduct, err := c.TargetProductOrErr()
1502 if err != nil {
1503 return filepath.Join(c.SoongOutDir(), "soong.extra.variables")
1504 } else {
1505 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+".extra.variables")
1506 }
1507}
1508
Dan Willemsen1e704462016-08-21 15:17:17 -07001509func (c *configImpl) SoongNinjaFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001510 targetProduct, err := c.TargetProductOrErr()
1511 if err != nil {
1512 return filepath.Join(c.SoongOutDir(), "build.ninja")
1513 } else {
1514 return filepath.Join(c.SoongOutDir(), "build."+targetProduct+".ninja")
1515 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001516}
1517
1518func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001519 if c.katiSuffix == "" {
1520 return filepath.Join(c.OutDir(), "combined.ninja")
1521 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001522 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1523}
1524
1525func (c *configImpl) SoongAndroidMk() string {
1526 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1527}
1528
1529func (c *configImpl) SoongMakeVarsMk() string {
1530 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1531}
1532
Colin Crossaa9a2732023-10-27 10:54:27 -07001533func (c *configImpl) SoongBuildMetrics() string {
Colin Crossb67b0612023-10-31 10:02:45 -07001534 return filepath.Join(c.LogsDir(), "soong_build_metrics.pb")
Colin Crossaa9a2732023-10-27 10:54:27 -07001535}
1536
Dan Willemsenf052f782017-05-18 15:29:04 -07001537func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001538 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001539}
1540
Dan Willemsen02781d52017-05-12 19:28:13 -07001541func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001542 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1543}
1544
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001545func (c *configImpl) KatiPackageMkDir() string {
1546 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1547}
1548
Dan Willemsenf052f782017-05-18 15:29:04 -07001549func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001550 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001551}
1552
1553func (c *configImpl) HostOut() string {
1554 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1555}
1556
1557// This probably needs to be multi-valued, so not exporting it for now
1558func (c *configImpl) hostCrossOut() string {
1559 if runtime.GOOS == "linux" {
1560 return filepath.Join(c.hostOutRoot(), "windows-x86")
1561 } else {
1562 return ""
1563 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001564}
1565
Dan Willemsen1e704462016-08-21 15:17:17 -07001566func (c *configImpl) HostPrebuiltTag() string {
1567 if runtime.GOOS == "linux" {
1568 return "linux-x86"
1569 } else if runtime.GOOS == "darwin" {
1570 return "darwin-x86"
1571 } else {
1572 panic("Unsupported OS")
1573 }
1574}
Dan Willemsenf173d592017-04-27 14:28:00 -07001575
Dan Willemsen8122bd52017-10-12 20:20:41 -07001576func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001577 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1578 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001579 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1580 if _, err := os.Stat(asan); err == nil {
1581 return asan
1582 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001583 }
1584 }
1585 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1586}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001587
1588func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1589 c.brokenDupRules = val
1590}
1591
1592func (c *configImpl) BuildBrokenDupRules() bool {
1593 return c.brokenDupRules
1594}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001595
Dan Willemsen25e6f092019-04-09 10:22:43 -07001596func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1597 c.brokenUsesNetwork = val
1598}
1599
1600func (c *configImpl) BuildBrokenUsesNetwork() bool {
1601 return c.brokenUsesNetwork
1602}
1603
Dan Willemsene3336352020-01-02 19:10:38 -08001604func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1605 c.brokenNinjaEnvVars = val
1606}
1607
1608func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1609 return c.brokenNinjaEnvVars
1610}
1611
Spandan Das28a6f192024-07-01 21:00:25 +00001612func (c *configImpl) SetBuildBrokenMissingOutputs(val bool) {
1613 c.brokenMissingOutputs = val
1614}
1615
1616func (c *configImpl) BuildBrokenMissingOutputs() bool {
1617 return c.brokenMissingOutputs
1618}
1619
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001620func (c *configImpl) SetTargetDeviceDir(dir string) {
1621 c.targetDeviceDir = dir
1622}
1623
1624func (c *configImpl) TargetDeviceDir() string {
1625 return c.targetDeviceDir
1626}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001627
Patrice Arruda219eef32020-06-01 17:29:30 +00001628func (c *configImpl) BuildDateTime() string {
1629 return c.buildDateTime
1630}
1631
1632func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001633 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001634}
Patrice Arruda83842d72020-12-08 19:42:08 +00001635
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001636// LogsDir returns the absolute path to the logs directory where build log and
1637// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001638// directory. If the argument dist is specified, the logs directory
1639// is <dist_dir>/logs.
1640func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001641 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001642 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001643 // 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 -05001644 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001645 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001646 absDir, err := filepath.Abs(dir)
1647 if err != nil {
1648 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1649 os.Exit(1)
1650 }
1651 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001652}
1653
Chris Parsons53f68ae2022-03-03 12:01:40 -05001654// MkFileMetrics returns the file path for make-related metrics.
1655func (c *configImpl) MkMetrics() string {
1656 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1657}
1658
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001659func (c *configImpl) SetEmptyNinjaFile(v bool) {
1660 c.emptyNinjaFile = v
1661}
1662
1663func (c *configImpl) EmptyNinjaFile() bool {
1664 return c.emptyNinjaFile
1665}
Yu Liu6e13b402021-07-27 14:29:06 -07001666
MarkDacekd0e7cd32022-12-02 22:22:40 +00001667func (c *configImpl) SkipMetricsUpload() bool {
1668 return c.skipMetricsUpload
1669}
1670
MarkDacekf47e1422023-04-19 16:47:36 +00001671func (c *configImpl) EnsureAllowlistIntegrity() bool {
1672 return c.ensureAllowlistIntegrity
1673}
1674
MarkDacek6614d9c2022-12-07 21:57:38 +00001675// Returns a Time object if one was passed via a command-line flag.
1676// Otherwise returns the passed default.
1677func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1678 if c.buildStartedTime == 0 {
1679 return defaultTime
1680 }
1681 return time.UnixMilli(c.buildStartedTime)
1682}
1683
Yu Liu6e13b402021-07-27 14:29:06 -07001684func GetMetricsUploader(topDir string, env *Environment) string {
1685 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1686 metricsUploader := filepath.Join(topDir, p)
1687 if _, err := os.Stat(metricsUploader); err == nil {
1688 return metricsUploader
1689 }
1690 }
1691
1692 return ""
1693}