blob: b8fcb6b5d90bcae536fdadeed8eccbb04b9975d0 [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 }
217
Colin Cross106d6ef2023-10-24 10:34:56 -0700218 // Skip soong tests by default on Linux
219 if runtime.GOOS == "linux" {
220 ret.skipSoongTests = true
221 }
222
Patrice Arruda90109172020-07-28 18:07:27 +0000223 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700224 ret.parallel = runtime.NumCPU() + 2
225 ret.keepGoing = 1
226
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800227 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700228 ret.parseArgs(ctx, args)
Jeongik Chae114e602023-03-19 00:12:39 +0900229
230 if ret.ninjaWeightListSource == HINT_FROM_SOONG {
Jeongik Chaa87506f2023-06-01 23:16:41 +0900231 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "always")
232 } else if ret.ninjaWeightListSource == DEFAULT {
233 defaultNinjaWeightListSource := NINJA_LOG
234 if _, err := os.Stat(filepath.Join(ret.OutDir(), ninjaLogFileName)); errors.Is(err, os.ErrNotExist) {
235 ctx.Verboseln("$OUT/.ninja_log doesn't exist, use HINT_FROM_SOONG instead")
236 defaultNinjaWeightListSource = HINT_FROM_SOONG
237 } else {
238 ctx.Verboseln("$OUT/.ninja_log exist, use NINJA_LOG")
239 }
240 ret.ninjaWeightListSource = defaultNinjaWeightListSource
241 // soong_build generates ninja hint depending on ninja log existence.
242 // Set it "depend" to avoid soong re-run due to env variable change.
243 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "depend")
Jeongik Chae114e602023-03-19 00:12:39 +0900244 }
Jeongik Chaa87506f2023-06-01 23:16:41 +0900245
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800246 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700247 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
248 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
249 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800250 outDir := "out"
251 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
252 if wd, err := os.Getwd(); err != nil {
253 ctx.Fatalln("Failed to get working directory:", err)
254 } else {
255 outDir = filepath.Join(baseDir, filepath.Base(wd))
256 }
257 }
258 ret.environ.Set("OUT_DIR", outDir)
259 }
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",
Dan Willemsen1e704462016-08-21 15:17:17 -0700353 )
354
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400355 if ret.UseGoma() || ret.ForceUseGoma() {
356 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
357 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400358 }
359
Dan Willemsen1e704462016-08-21 15:17:17 -0700360 // Tell python not to spam the source tree with .pyc files.
361 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
362
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400363 tmpDir := absPath(ctx, ret.TempDir())
364 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800365
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700366 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
367 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
368 "llvm-binutils-stable/llvm-symbolizer")
369 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
370
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800371 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700372 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800373
Yu Liu6e13b402021-07-27 14:29:06 -0700374 srcDir := absPath(ctx, ".")
375 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700376 ctx.Println("You are building in a directory whose absolute path contains a space character:")
377 ctx.Println()
378 ctx.Printf("%q\n", srcDir)
379 ctx.Println()
380 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700381 }
382
Yu Liu6e13b402021-07-27 14:29:06 -0700383 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
384
Dan Willemsendb8457c2017-05-12 16:38:17 -0700385 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700386 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
387 ctx.Println()
388 ctx.Printf("%q\n", outDir)
389 ctx.Println()
390 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700391 }
392
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000393 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700394 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
395 ctx.Println()
396 ctx.Printf("%q\n", distDir)
397 ctx.Println()
398 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700399 }
400
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700401 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000402 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
Sorin Basca0760c892023-11-29 19:13:55 +0000403 java21Home := filepath.Join("prebuilts/jdk/jdk21", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700404 javaHome := func() string {
405 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
406 return override
407 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000408 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
Sorin Basca5dfa2382024-03-11 17:23:06 +0000409 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 +0100410 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000411 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
Sorin Basca5dfa2382024-03-11 17:23:06 +0000412 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 +0000413 }
Sorin Basca5dfa2382024-03-11 17:23:06 +0000414 if toolchain21, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK21_TOOLCHAIN"); ok && toolchain21 != "true" {
415 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK21_TOOLCHAIN is no longer supported. An OpenJDK 21 toolchain is now the global default.")
416 }
417 return java21Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700418 }()
419 absJavaHome := absPath(ctx, javaHome)
420
Dan Willemsened869522018-01-08 14:58:46 -0800421 ret.configureLocale(ctx)
422
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700423 newPath := []string{filepath.Join(absJavaHome, "bin")}
424 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
425 newPath = append(newPath, path)
426 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100427
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700428 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
429 ret.environ.Set("JAVA_HOME", absJavaHome)
430 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000431 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700432 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
433
Colin Crossfe5ed4d2023-07-28 09:27:23 -0700434 // b/286885495, https://bugzilla.redhat.com/show_bug.cgi?id=2227130: some versions of Fedora include patches
435 // to unzip to enable zipbomb detection that incorrectly handle zip64 and data descriptors and fail on large
436 // zip files produced by soong_zip. Disable zipbomb detection.
437 ret.environ.Set("UNZIP_DISABLE_ZIPBOMB_DETECTION", "TRUE")
438
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800439 outDir := ret.OutDir()
440 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800441 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800442 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800443 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800444 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800445 }
Colin Cross28f527c2019-11-26 16:19:04 -0800446
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800447 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
448
Cole Faust583dfb42023-09-28 13:56:30 -0700449 if _, ok := ret.environ.Get("BUILD_USERNAME"); !ok {
450 username := "unknown"
451 if u, err := user.Current(); err == nil {
452 username = u.Username
453 } else {
454 ctx.Println("Failed to get current user:", err)
455 }
456 ret.environ.Set("BUILD_USERNAME", username)
457 }
458
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400459 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400460 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400461 ret.environ.Set(k, v)
462 }
463 }
464
Patrice Arruda96850362020-08-11 20:41:11 +0000465 c := Config{ret}
466 storeConfigMetrics(ctx, c)
467 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700468}
469
Patrice Arruda13848222019-04-22 17:12:02 -0700470// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
471// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700472func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
473 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700474}
475
LaMont Jones9a912862023-11-06 22:11:08 +0000476// Prepare for getting make variables. For them to be accurate, we need to have
477// obtained PRODUCT_RELEASE_CONFIG_MAPS.
478//
479// Returns:
480//
481// Whether config should be called again.
482//
483// TODO: when converting product config to a declarative language, make sure
484// that PRODUCT_RELEASE_CONFIG_MAPS is properly handled as a separate step in
485// that process.
486func SetProductReleaseConfigMaps(ctx Context, config Config) bool {
487 ctx.BeginTrace(metrics.RunKati, "SetProductReleaseConfigMaps")
488 defer ctx.EndTrace()
489
490 if config.SkipConfig() {
491 // This duplicates the logic from Build to skip product config
492 // if the user has explicitly said to.
493 return false
494 }
495
496 releaseConfigVars := []string{
497 "PRODUCT_RELEASE_CONFIG_MAPS",
498 }
499
500 origValue, _ := config.environ.Get("PRODUCT_RELEASE_CONFIG_MAPS")
501 // Get the PRODUCT_RELEASE_CONFIG_MAPS for this product, to avoid polluting the environment
502 // when we run product config to get the rest of the make vars.
503 releaseMapVars, err := dumpMakeVars(ctx, config, nil, releaseConfigVars, false, "")
504 if err != nil {
505 ctx.Fatalln("Error getting PRODUCT_RELEASE_CONFIG_MAPS:", err)
506 }
507 productReleaseConfigMaps := releaseMapVars["PRODUCT_RELEASE_CONFIG_MAPS"]
508 os.Setenv("PRODUCT_RELEASE_CONFIG_MAPS", productReleaseConfigMaps)
509 return origValue != productReleaseConfigMaps
510}
511
Patrice Arruda96850362020-08-11 20:41:11 +0000512// storeConfigMetrics selects a set of configuration information and store in
513// the metrics system for further analysis.
514func storeConfigMetrics(ctx Context, config Config) {
515 if ctx.Metrics == nil {
516 return
517 }
518
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400519 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000520
521 s := &smpb.SystemResourceInfo{
522 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
523 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
524 }
525 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000526}
527
Jeongik Cha8d63d562023-03-17 03:52:13 +0900528func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900529 switch s {
530 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900531 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900532 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900533 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900534 case EXTERNAL_FILE:
535 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900536 case HINT_FROM_SOONG:
537 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900538 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900539 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900540 }
541}
542
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400543func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700544 c := &smpb.BuildConfig{
Colin Cross8d411ff2023-12-07 10:31:24 -0800545 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
546 UseGoma: proto.Bool(config.UseGoma()),
547 UseRbe: proto.Bool(config.UseRBE()),
548 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400549 }
Yu Liue737a992021-10-04 13:21:41 -0700550 c.Targets = append(c.Targets, config.arguments...)
551
552 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400553}
554
Patrice Arruda13848222019-04-22 17:12:02 -0700555// getConfigArgs processes the command arguments based on the build action and creates a set of new
556// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700557func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700558 // The next block of code verifies that the current directory is the root directory of the source
559 // tree. It then finds the relative path of dir based on the root directory of the source tree
560 // and verify that dir is inside of the source tree.
561 checkTopDir(ctx)
562 topDir, err := os.Getwd()
563 if err != nil {
564 ctx.Fatalf("Error retrieving top directory: %v", err)
565 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700566 dir, err = filepath.EvalSymlinks(dir)
567 if err != nil {
568 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
569 }
Patrice Arruda13848222019-04-22 17:12:02 -0700570 dir, err = filepath.Abs(dir)
571 if err != nil {
572 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
573 }
574 relDir, err := filepath.Rel(topDir, dir)
575 if err != nil {
576 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
577 }
578 // If there are ".." in the path, it's not in the source tree.
579 if strings.Contains(relDir, "..") {
580 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
581 }
582
583 configArgs := args[:]
584
585 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
586 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
587 targetNamePrefix := "MODULES-IN-"
588 if inList("GET-INSTALL-PATH", configArgs) {
589 targetNamePrefix = "GET-INSTALL-PATH-IN-"
590 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
591 }
592
Patrice Arruda13848222019-04-22 17:12:02 -0700593 var targets []string
594
595 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700596 case BUILD_MODULES:
597 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700598 case BUILD_MODULES_IN_A_DIRECTORY:
599 // If dir is the root source tree, all the modules are built of the source tree are built so
600 // no need to find the build file.
601 if topDir == dir {
602 break
603 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700604
Patrice Arruda13848222019-04-22 17:12:02 -0700605 buildFile := findBuildFile(ctx, relDir)
606 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700607 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700608 }
Patrice Arruda13848222019-04-22 17:12:02 -0700609 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
610 case BUILD_MODULES_IN_DIRECTORIES:
611 newConfigArgs, dirs := splitArgs(configArgs)
612 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700613 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700614 }
615
616 // Tidy only override all other specified targets.
617 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
618 if tidyOnly == "true" || tidyOnly == "1" {
619 configArgs = append(configArgs, "tidy_only")
620 } else {
621 configArgs = append(configArgs, targets...)
622 }
623
624 return configArgs
625}
626
627// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
628func convertToTarget(dir string, targetNamePrefix string) string {
629 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
630}
631
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700632// hasBuildFile returns true if dir contains an Android build file.
633func hasBuildFile(ctx Context, dir string) bool {
634 for _, buildFile := range buildFiles {
635 _, err := os.Stat(filepath.Join(dir, buildFile))
636 if err == nil {
637 return true
638 }
639 if !os.IsNotExist(err) {
640 ctx.Fatalf("Error retrieving the build file stats: %v", err)
641 }
642 }
643 return false
644}
645
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700646// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
647// in the current and any sub directory of dir. If a build file is not found, traverse the path
648// up by one directory and repeat again until either a build file is found or reached to the root
649// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
650// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700651func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700652 // If the string is empty or ".", assume it is top directory of the source tree.
653 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700654 return ""
655 }
656
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700657 found := false
658 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
659 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
660 if err != nil {
661 return err
662 }
663 if found {
664 return filepath.SkipDir
665 }
666 if info.IsDir() {
667 return nil
668 }
669 for _, buildFile := range buildFiles {
670 if info.Name() == buildFile {
671 found = true
672 return filepath.SkipDir
673 }
674 }
675 return nil
676 })
677 if err != nil {
678 ctx.Fatalf("Error finding Android build file: %v", err)
679 }
680
681 if found {
682 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700683 }
684 }
685
686 return ""
687}
688
689// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
690func splitArgs(args []string) (newArgs []string, dirs []string) {
691 specialArgs := map[string]bool{
692 "showcommands": true,
693 "snod": true,
694 "dist": true,
695 "checkbuild": true,
696 }
697
698 newArgs = []string{}
699 dirs = []string{}
700
701 for _, arg := range args {
702 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
703 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
704 newArgs = append(newArgs, arg)
705 continue
706 }
707
708 if _, ok := specialArgs[arg]; ok {
709 newArgs = append(newArgs, arg)
710 continue
711 }
712
713 dirs = append(dirs, arg)
714 }
715
716 return newArgs, dirs
717}
718
719// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
720// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
721// source root tree where the build action command was invoked. Each directory is validated if the
722// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700723func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700724 for _, dir := range dirs {
725 // The directory may have specified specific modules to build. ":" is the separator to separate
726 // the directory and the list of modules.
727 s := strings.Split(dir, ":")
728 l := len(s)
729 if l > 2 { // more than one ":" was specified.
730 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
731 }
732
733 dir = filepath.Join(relDir, s[0])
734 if _, err := os.Stat(dir); err != nil {
735 ctx.Fatalf("couldn't find directory %s", dir)
736 }
737
738 // Verify that if there are any targets specified after ":". Each target is separated by ",".
739 var newTargets []string
740 if l == 2 && s[1] != "" {
741 newTargets = strings.Split(s[1], ",")
742 if inList("", newTargets) {
743 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
744 }
745 }
746
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700747 // If there are specified targets to build in dir, an android build file must exist for the one
748 // shot build. For the non-targets case, find the appropriate build file and build all the
749 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700750 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700751 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700752 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
753 }
754 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700755 buildFile := findBuildFile(ctx, dir)
756 if buildFile == "" {
757 ctx.Fatalf("Build file not found for %s directory", dir)
758 }
759 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700760 }
761
Patrice Arruda13848222019-04-22 17:12:02 -0700762 targets = append(targets, newTargets...)
763 }
764
Dan Willemsence41e942019-07-29 23:39:30 -0700765 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700766}
767
Dan Willemsen9b587492017-07-10 22:13:00 -0700768func (c *configImpl) parseArgs(ctx Context, args []string) {
769 for i := 0; i < len(args); i++ {
770 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100771 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700772 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200773 } else if arg == "--empty-ninja-file" {
774 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100775 } else if arg == "--skip-ninja" {
776 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700777 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700778 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
779 // but it does run a Kati ninja file if the .kati_enabled marker file was created
780 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000781 c.skipConfig = true
782 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100783 } else if arg == "--soong-only" {
784 c.skipKati = true
785 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200786 } else if arg == "--config-only" {
787 c.skipKati = true
788 c.skipKatiNinja = true
789 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700790 } else if arg == "--skip-config" {
791 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700792 } else if arg == "--skip-soong-tests" {
793 c.skipSoongTests = true
Colin Cross106d6ef2023-10-24 10:34:56 -0700794 } else if arg == "--no-skip-soong-tests" {
795 c.skipSoongTests = false
MarkDacekd0e7cd32022-12-02 22:22:40 +0000796 } else if arg == "--skip-metrics-upload" {
797 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500798 } else if arg == "--mk-metrics" {
799 c.reportMkMetrics = true
Spandan Das394aa322022-11-03 17:02:10 +0000800 } else if arg == "--search-api-dir" {
801 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900802 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
803 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
804 if source == "ninja_log" {
805 c.ninjaWeightListSource = NINJA_LOG
806 } else if source == "evenly_distributed" {
807 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
808 } else if source == "not_used" {
809 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900810 } else if source == "soong" {
811 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900812 } else if strings.HasPrefix(source, "file,") {
813 c.ninjaWeightListSource = EXTERNAL_FILE
814 filePath := strings.TrimPrefix(source, "file,")
815 err := validateNinjaWeightList(filePath)
816 if err != nil {
817 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
818 }
819 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
820 if err != nil {
821 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
822 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900823 } else {
824 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
825 }
Jihoon Kang2a929ad2023-06-08 19:02:07 +0000826 } else if arg == "--build-from-source-stub" {
827 c.buildFromSourceStub = true
Yu Liufa297642024-06-11 00:13:02 +0000828 } else if arg == "--incremental-build-actions" {
829 c.incrementalBuildActions = true
MarkDacekb96561e2022-12-02 04:34:43 +0000830 } else if strings.HasPrefix(arg, "--build-command=") {
831 buildCmd := strings.TrimPrefix(arg, "--build-command=")
832 // remove quotations
833 buildCmd = strings.TrimPrefix(buildCmd, "\"")
834 buildCmd = strings.TrimSuffix(buildCmd, "\"")
835 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacek6614d9c2022-12-07 21:57:38 +0000836 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
837 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
838 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
839 if err == nil {
840 c.buildStartedTime = val
841 } else {
842 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
843 }
MarkDacekf47e1422023-04-19 16:47:36 +0000844 } else if arg == "--ensure-allowlist-integrity" {
845 c.ensureAllowlistIntegrity = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700846 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700847 parseArgNum := func(def int) int {
848 if len(arg) > 2 {
849 p, err := strconv.ParseUint(arg[2:], 10, 31)
850 if err != nil {
851 ctx.Fatalf("Failed to parse %q: %v", arg, err)
852 }
853 return int(p)
854 } else if i+1 < len(args) {
855 p, err := strconv.ParseUint(args[i+1], 10, 31)
856 if err == nil {
857 i++
858 return int(p)
859 }
860 }
861 return def
862 }
863
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700864 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700865 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700866 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700867 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700868 } else {
869 ctx.Fatalln("Unknown option:", arg)
870 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700871 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700872 if k == "OUT_DIR" {
873 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
874 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700875 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700876 } else if arg == "dist" {
877 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200878 } else if arg == "json-module-graph" {
879 c.jsonModuleGraph = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200880 } else if arg == "queryview" {
881 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200882 } else if arg == "soong_docs" {
883 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700884 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700885 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800886 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700887 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700888 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700889 }
890 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700891}
892
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900893func validateNinjaWeightList(weightListFilePath string) (err error) {
894 data, err := os.ReadFile(weightListFilePath)
895 if err != nil {
896 return
897 }
898 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
899 for _, line := range lines {
900 fields := strings.Split(line, ",")
901 if len(fields) != 2 {
902 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
903 }
904 _, err = strconv.Atoi(fields[1])
905 if err != nil {
906 return
907 }
908 }
909 return
910}
911
Dan Willemsened869522018-01-08 14:58:46 -0800912func (c *configImpl) configureLocale(ctx Context) {
913 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
914 output, err := cmd.Output()
915
916 var locales []string
917 if err == nil {
918 locales = strings.Split(string(output), "\n")
919 } else {
920 // If we're unable to list the locales, let's assume en_US.UTF-8
921 locales = []string{"en_US.UTF-8"}
922 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
923 }
924
925 // gettext uses LANGUAGE, which is passed directly through
926
927 // For LANG and LC_*, only preserve the evaluated version of
928 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800929 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800930 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800931 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800932 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800933 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800934 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800935 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800936 }
937
938 c.environ.UnsetWithPrefix("LC_")
939
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800940 if userLang != "" {
941 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800942 }
943
944 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
945 // for others)
946 if inList("C.UTF-8", locales) {
947 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500948 } else if inList("C.utf8", locales) {
949 // These normalize to the same thing
950 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800951 } else if inList("en_US.UTF-8", locales) {
952 c.environ.Set("LANG", "en_US.UTF-8")
953 } else if inList("en_US.utf8", locales) {
954 // These normalize to the same thing
955 c.environ.Set("LANG", "en_US.UTF-8")
956 } else {
957 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
958 }
959}
960
Dan Willemsen1e704462016-08-21 15:17:17 -0700961func (c *configImpl) Environment() *Environment {
962 return c.environ
963}
964
965func (c *configImpl) Arguments() []string {
966 return c.arguments
967}
968
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200969func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200970 if len(c.Arguments()) > 0 {
971 // Explicit targets requested that are not special targets like b2pbuild
972 // or the JSON module graph
973 return true
974 }
975
Colin Cross8d411ff2023-12-07 10:31:24 -0800976 if !c.JsonModuleGraph() && !c.Queryview() && !c.SoongDocs() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200977 // Command line was empty, the default Ninja target is built
978 return true
979 }
980
Colin Cross8d411ff2023-12-07 10:31:24 -0800981 if c.Dist() {
Liz Kammer88677422021-12-15 15:03:19 -0500982 return true
983 }
984
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200985 // build.ninja doesn't need to be generated
986 return false
987}
988
Dan Willemsen1e704462016-08-21 15:17:17 -0700989func (c *configImpl) OutDir() string {
990 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700991 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700992 }
993 return "out"
994}
995
Dan Willemsen8a073a82017-02-04 17:30:44 -0800996func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400997 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000998}
999
1000func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -07001001 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -08001002}
1003
Dan Willemsen1e704462016-08-21 15:17:17 -07001004func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001005 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001006 return c.arguments
1007 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001008 return c.ninjaArgs
1009}
1010
1011func (c *configImpl) SoongOutDir() string {
1012 return filepath.Join(c.OutDir(), "soong")
1013}
1014
Spandan Das394aa322022-11-03 17:02:10 +00001015func (c *configImpl) ApiSurfacesOutDir() string {
1016 return filepath.Join(c.OutDir(), "api_surfaces")
1017}
1018
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001019func (c *configImpl) PrebuiltOS() string {
1020 switch runtime.GOOS {
1021 case "linux":
1022 return "linux-x86"
1023 case "darwin":
1024 return "darwin-x86"
1025 default:
1026 panic("Unknown GOOS")
1027 }
1028}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001029
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001030func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001031 if c.SkipKatiNinja() {
1032 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1033 } else {
1034 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1035 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001036}
1037
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001038func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001039 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001040}
1041
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001042func (c *configImpl) UsedEnvFile(tag string) string {
Kiyoung Kimeaa55a82023-06-05 16:56:49 +09001043 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1044 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+v+"."+tag)
1045 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001046 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1047}
1048
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001049func (c *configImpl) SoongDocsHtml() string {
1050 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1051}
1052
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001053func (c *configImpl) QueryviewMarkerFile() string {
1054 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1055}
1056
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001057func (c *configImpl) ModuleGraphFile() string {
1058 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1059}
1060
kgui67007242022-01-25 13:50:25 +08001061func (c *configImpl) ModuleActionsFile() string {
1062 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1063}
1064
Jeff Gastonefc1b412017-03-29 17:29:06 -07001065func (c *configImpl) TempDir() string {
1066 return shared.TempDirForOutDir(c.SoongOutDir())
1067}
1068
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001069func (c *configImpl) FileListDir() string {
1070 return filepath.Join(c.OutDir(), ".module_paths")
1071}
1072
Dan Willemsen1e704462016-08-21 15:17:17 -07001073func (c *configImpl) KatiSuffix() string {
1074 if c.katiSuffix != "" {
1075 return c.katiSuffix
1076 }
1077 panic("SetKatiSuffix has not been called")
1078}
1079
Colin Cross37193492017-11-16 17:55:00 -08001080// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1081// user is interested in additional checks at the expense of build time.
1082func (c *configImpl) Checkbuild() bool {
1083 return c.checkbuild
1084}
1085
Dan Willemsen8a073a82017-02-04 17:30:44 -08001086func (c *configImpl) Dist() bool {
1087 return c.dist
1088}
1089
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001090func (c *configImpl) JsonModuleGraph() bool {
1091 return c.jsonModuleGraph
1092}
1093
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001094func (c *configImpl) Queryview() bool {
1095 return c.queryview
1096}
1097
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001098func (c *configImpl) SoongDocs() bool {
1099 return c.soongDocs
1100}
1101
Dan Willemsen1e704462016-08-21 15:17:17 -07001102func (c *configImpl) IsVerbose() bool {
1103 return c.verbose
1104}
1105
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001106func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1107 return c.ninjaWeightListSource
1108}
1109
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001110func (c *configImpl) SkipKati() bool {
1111 return c.skipKati
1112}
1113
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001114func (c *configImpl) SkipKatiNinja() bool {
1115 return c.skipKatiNinja
1116}
1117
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001118func (c *configImpl) SkipSoong() bool {
1119 return c.skipSoong
1120}
1121
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001122func (c *configImpl) SkipNinja() bool {
1123 return c.skipNinja
1124}
1125
Anton Hansson5a7861a2021-06-04 10:09:01 +01001126func (c *configImpl) SetSkipNinja(v bool) {
1127 c.skipNinja = v
1128}
1129
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001130func (c *configImpl) SkipConfig() bool {
1131 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001132}
1133
Jihoon Kang1bff0342023-01-17 20:40:22 +00001134func (c *configImpl) BuildFromTextStub() bool {
Jihoon Kang2a929ad2023-06-08 19:02:07 +00001135 return !c.buildFromSourceStub
Jihoon Kang1bff0342023-01-17 20:40:22 +00001136}
1137
Dan Willemsen1e704462016-08-21 15:17:17 -07001138func (c *configImpl) TargetProduct() string {
1139 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1140 return v
1141 }
1142 panic("TARGET_PRODUCT is not defined")
1143}
1144
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001145func (c *configImpl) TargetProductOrErr() (string, error) {
1146 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1147 return v, nil
1148 }
1149 return "", fmt.Errorf("TARGET_PRODUCT is not defined")
1150}
1151
Dan Willemsen02781d52017-05-12 19:28:13 -07001152func (c *configImpl) TargetDevice() string {
1153 return c.targetDevice
1154}
1155
1156func (c *configImpl) SetTargetDevice(device string) {
1157 c.targetDevice = device
1158}
1159
1160func (c *configImpl) TargetBuildVariant() string {
1161 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1162 return v
1163 }
1164 panic("TARGET_BUILD_VARIANT is not defined")
1165}
1166
Dan Willemsen1e704462016-08-21 15:17:17 -07001167func (c *configImpl) KatiArgs() []string {
1168 return c.katiArgs
1169}
1170
1171func (c *configImpl) Parallel() int {
1172 return c.parallel
1173}
1174
Sam Delmerico98a73292023-02-21 11:50:29 -05001175func (c *configImpl) GetSourceRootDirs() []string {
1176 return c.sourceRootDirs
1177}
1178
1179func (c *configImpl) SetSourceRootDirs(i []string) {
1180 c.sourceRootDirs = i
1181}
1182
MarkDacek6614d9c2022-12-07 21:57:38 +00001183func (c *configImpl) GetLogsPrefix() string {
1184 return c.logsPrefix
1185}
1186
1187func (c *configImpl) SetLogsPrefix(prefix string) {
1188 c.logsPrefix = prefix
1189}
1190
Colin Cross8b8bec32019-11-15 13:18:43 -08001191func (c *configImpl) HighmemParallel() int {
1192 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1193 return i
1194 }
1195
1196 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1197 parallel := c.Parallel()
1198 if c.UseRemoteBuild() {
1199 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1200 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1201 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1202 // Return 1/16th of the size of the local pool, rounding up.
1203 return (parallel + 15) / 16
1204 } else if c.totalRAM == 0 {
1205 // Couldn't detect the total RAM, don't restrict highmem processes.
1206 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001207 } else if c.totalRAM <= 16*1024*1024*1024 {
1208 // Less than 16GB of ram, restrict to 1 highmem processes
1209 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001210 } else if c.totalRAM <= 32*1024*1024*1024 {
1211 // Less than 32GB of ram, restrict to 2 highmem processes
1212 return 2
1213 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1214 // If less than 8GB total RAM per process, reduce the number of highmem processes
1215 return p
1216 }
1217 // No restriction on highmem processes
1218 return parallel
1219}
1220
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001221func (c *configImpl) TotalRAM() uint64 {
1222 return c.totalRAM
1223}
1224
Kousik Kumarec478642020-09-21 13:39:24 -04001225// ForceUseGoma determines whether we should override Goma deprecation
1226// and use Goma for the current build or not.
1227func (c *configImpl) ForceUseGoma() bool {
1228 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1229 v = strings.TrimSpace(v)
1230 if v != "" && v != "false" {
1231 return true
1232 }
1233 }
1234 return false
1235}
1236
Dan Willemsen1e704462016-08-21 15:17:17 -07001237func (c *configImpl) UseGoma() bool {
1238 if v, ok := c.environ.Get("USE_GOMA"); ok {
1239 v = strings.TrimSpace(v)
1240 if v != "" && v != "false" {
1241 return true
1242 }
1243 }
1244 return false
1245}
1246
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001247func (c *configImpl) StartGoma() bool {
1248 if !c.UseGoma() {
1249 return false
1250 }
1251
1252 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1253 v = strings.TrimSpace(v)
1254 if v != "" && v != "false" {
1255 return false
1256 }
1257 }
1258 return true
1259}
1260
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001261func (c *configImpl) canSupportRBE() bool {
Joe Onorato86f50e72024-06-24 14:28:25 -07001262 // Only supported on linux
1263 if runtime.GOOS != "linux" {
1264 return false
1265 }
1266
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001267 // Do not use RBE with prod credentials in scenarios when stubby doesn't exist, since
1268 // its unlikely that we will be able to obtain necessary creds without stubby.
1269 authType, _ := c.rbeAuth()
1270 if !c.StubbyExists() && strings.Contains(authType, "use_google_prod_creds") {
1271 return false
1272 }
Taylor Santiago3c16e612024-05-30 14:41:31 -07001273 if c.UseABFS() {
1274 return false
1275 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001276 return true
1277}
1278
Taylor Santiago3c16e612024-05-30 14:41:31 -07001279func (c *configImpl) UseABFS() bool {
1280 if v, ok := c.environ.Get("NO_ABFS"); ok {
1281 v = strings.ToLower(strings.TrimSpace(v))
1282 if v == "true" || v == "1" {
1283 return false
1284 }
1285 }
1286
1287 abfsBox := c.PrebuiltBuildTool("abfsbox")
1288 err := exec.Command(abfsBox, "hash", srcDirFileCheck).Run()
1289 return err == nil
1290}
1291
Ramy Medhatbbf25672019-07-17 12:30:04 +00001292func (c *configImpl) UseRBE() bool {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001293 // These alternate modes of running Soong do not use RBE / reclient.
Colin Cross8d411ff2023-12-07 10:31:24 -08001294 if c.Queryview() || c.JsonModuleGraph() {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001295 return false
1296 }
1297
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001298 if !c.canSupportRBE() {
Kousik Kumar67ad4342023-06-06 15:09:27 -04001299 return false
1300 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001301
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001302 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001303 v = strings.TrimSpace(v)
1304 if v != "" && v != "false" {
1305 return true
1306 }
1307 }
1308 return false
1309}
1310
1311func (c *configImpl) StartRBE() bool {
1312 if !c.UseRBE() {
1313 return false
1314 }
1315
1316 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1317 v = strings.TrimSpace(v)
1318 if v != "" && v != "false" {
1319 return false
1320 }
1321 }
1322 return true
1323}
1324
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001325func (c *configImpl) rbeProxyLogsDir() string {
1326 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001327 if v, ok := c.environ.Get(f); ok {
1328 return v
1329 }
1330 }
Ramy Medhatbc061762023-10-10 18:36:59 +00001331 return c.rbeTmpDir()
1332}
1333
1334func (c *configImpl) rbeDownloadTmpDir() string {
Cole Faust06ea5312023-10-18 17:38:40 -07001335 for _, f := range []string{"RBE_download_tmp_dir", "FLAG_download_tmp_dir"} {
Ramy Medhatbc061762023-10-10 18:36:59 +00001336 if v, ok := c.environ.Get(f); ok {
1337 return v
1338 }
1339 }
1340 return c.rbeTmpDir()
1341}
1342
1343func (c *configImpl) rbeTmpDir() string {
Yaowen Meid4da2662024-07-24 08:25:12 +00001344 return filepath.Join(c.SoongOutDir(), "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001345}
1346
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001347func (c *configImpl) rbeCacheDir() string {
1348 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1349 if v, ok := c.environ.Get(f); ok {
1350 return v
1351 }
1352 }
1353 return shared.JoinPath(c.SoongOutDir(), "rbe")
1354}
1355
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001356func (c *configImpl) shouldCleanupRBELogsDir() bool {
1357 // Perform a log directory cleanup only when the log directory
1358 // is auto created by the build rather than user-specified.
1359 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1360 if _, ok := c.environ.Get(f); ok {
1361 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001362 }
1363 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001364 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001365}
1366
1367func (c *configImpl) rbeExecRoot() string {
1368 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1369 if v, ok := c.environ.Get(f); ok {
1370 return v
1371 }
1372 }
1373 wd, err := os.Getwd()
1374 if err != nil {
1375 return ""
1376 }
1377 return wd
1378}
1379
1380func (c *configImpl) rbeDir() string {
1381 if v, ok := c.environ.Get("RBE_DIR"); ok {
1382 return v
1383 }
1384 return "prebuilts/remoteexecution-client/live/"
1385}
1386
1387func (c *configImpl) rbeReproxy() string {
1388 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1389 if v, ok := c.environ.Get(f); ok {
1390 return v
1391 }
1392 }
1393 return filepath.Join(c.rbeDir(), "reproxy")
1394}
1395
1396func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001397 credFlags := []string{
1398 "use_application_default_credentials",
1399 "use_gce_credentials",
1400 "credential_file",
1401 "use_google_prod_creds",
1402 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001403 for _, cf := range credFlags {
1404 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1405 if v, ok := c.environ.Get(f); ok {
1406 v = strings.TrimSpace(v)
1407 if v != "" && v != "false" && v != "0" {
1408 return "RBE_" + cf, v
1409 }
1410 }
1411 }
1412 }
1413 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001414}
1415
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001416func (c *configImpl) rbeSockAddr(dir string) (string, error) {
Andus Yuc917eb82024-03-06 21:54:15 +00001417 // Absolute path socket addresses have a prefix of //. This should
1418 // be included in the length limit.
1419 maxNameLen := len(syscall.RawSockaddrUnix{}.Path) - 2
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001420 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1421
1422 name := filepath.Join(dir, base)
1423 if len(name) < maxNameLen {
1424 return name, nil
1425 }
1426
1427 name = filepath.Join("/tmp", base)
1428 if len(name) < maxNameLen {
1429 return name, nil
1430 }
1431
1432 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1433}
1434
Kousik Kumar7bc78192022-04-27 14:52:56 -04001435// IsGooglerEnvironment returns true if the current build is running
1436// on a Google developer machine and false otherwise.
1437func (c *configImpl) IsGooglerEnvironment() bool {
1438 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1439 if v, ok := c.environ.Get(cf); ok {
1440 return v == "googler"
1441 }
1442 return false
1443}
1444
1445// GoogleProdCredsExist determine whether credentials exist on the
1446// Googler machine to use remote execution.
1447func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001448 if googleProdCredsExistCache {
1449 return googleProdCredsExistCache
1450 }
andusyu0b3dc032023-06-21 17:29:32 -04001451 if _, err := exec.Command("/usr/bin/gcertstatus", "-nocheck_ssh").Output(); err != nil {
Kousik Kumar7bc78192022-04-27 14:52:56 -04001452 return false
1453 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001454 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001455 return true
1456}
1457
1458// UseRemoteBuild indicates whether to use a remote build acceleration system
1459// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001460func (c *configImpl) UseRemoteBuild() bool {
1461 return c.UseGoma() || c.UseRBE()
1462}
1463
Kousik Kumar7bc78192022-04-27 14:52:56 -04001464// StubbyExists checks whether the stubby binary exists on the machine running
1465// the build.
1466func (c *configImpl) StubbyExists() bool {
1467 if _, err := exec.LookPath("stubby"); err != nil {
1468 return false
1469 }
1470 return true
1471}
1472
Dan Willemsen1e704462016-08-21 15:17:17 -07001473// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001474// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001475// still limited by Parallel()
1476func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001477 if !c.UseRemoteBuild() {
1478 return 0
1479 }
1480 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1481 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001482 }
1483 return 500
1484}
1485
1486func (c *configImpl) SetKatiArgs(args []string) {
1487 c.katiArgs = args
1488}
1489
1490func (c *configImpl) SetNinjaArgs(args []string) {
1491 c.ninjaArgs = args
1492}
1493
1494func (c *configImpl) SetKatiSuffix(suffix string) {
1495 c.katiSuffix = suffix
1496}
1497
Dan Willemsene0879fc2017-08-04 15:06:27 -07001498func (c *configImpl) LastKatiSuffixFile() string {
1499 return filepath.Join(c.OutDir(), "last_kati_suffix")
1500}
1501
1502func (c *configImpl) HasKatiSuffix() bool {
1503 return c.katiSuffix != ""
1504}
1505
Dan Willemsen1e704462016-08-21 15:17:17 -07001506func (c *configImpl) KatiEnvFile() string {
1507 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1508}
1509
Dan Willemsen29971232018-09-26 14:58:30 -07001510func (c *configImpl) KatiBuildNinjaFile() string {
1511 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001512}
1513
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001514func (c *configImpl) KatiPackageNinjaFile() string {
1515 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1516}
1517
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001518func (c *configImpl) SoongVarsFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001519 targetProduct, err := c.TargetProductOrErr()
1520 if err != nil {
1521 return filepath.Join(c.SoongOutDir(), "soong.variables")
1522 } else {
1523 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+".variables")
1524 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001525}
1526
Inseob Kim58c802f2024-06-11 10:59:00 +09001527func (c *configImpl) SoongExtraVarsFile() string {
1528 targetProduct, err := c.TargetProductOrErr()
1529 if err != nil {
1530 return filepath.Join(c.SoongOutDir(), "soong.extra.variables")
1531 } else {
1532 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+".extra.variables")
1533 }
1534}
1535
Dan Willemsen1e704462016-08-21 15:17:17 -07001536func (c *configImpl) SoongNinjaFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001537 targetProduct, err := c.TargetProductOrErr()
1538 if err != nil {
1539 return filepath.Join(c.SoongOutDir(), "build.ninja")
1540 } else {
1541 return filepath.Join(c.SoongOutDir(), "build."+targetProduct+".ninja")
1542 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001543}
1544
1545func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001546 if c.katiSuffix == "" {
1547 return filepath.Join(c.OutDir(), "combined.ninja")
1548 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001549 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1550}
1551
1552func (c *configImpl) SoongAndroidMk() string {
1553 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1554}
1555
1556func (c *configImpl) SoongMakeVarsMk() string {
1557 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1558}
1559
Colin Crossaa9a2732023-10-27 10:54:27 -07001560func (c *configImpl) SoongBuildMetrics() string {
Colin Crossb67b0612023-10-31 10:02:45 -07001561 return filepath.Join(c.LogsDir(), "soong_build_metrics.pb")
Colin Crossaa9a2732023-10-27 10:54:27 -07001562}
1563
Dan Willemsenf052f782017-05-18 15:29:04 -07001564func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001565 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001566}
1567
Dan Willemsen02781d52017-05-12 19:28:13 -07001568func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001569 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1570}
1571
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001572func (c *configImpl) KatiPackageMkDir() string {
1573 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1574}
1575
Dan Willemsenf052f782017-05-18 15:29:04 -07001576func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001577 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001578}
1579
1580func (c *configImpl) HostOut() string {
1581 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1582}
1583
1584// This probably needs to be multi-valued, so not exporting it for now
1585func (c *configImpl) hostCrossOut() string {
1586 if runtime.GOOS == "linux" {
1587 return filepath.Join(c.hostOutRoot(), "windows-x86")
1588 } else {
1589 return ""
1590 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001591}
1592
Dan Willemsen1e704462016-08-21 15:17:17 -07001593func (c *configImpl) HostPrebuiltTag() string {
1594 if runtime.GOOS == "linux" {
1595 return "linux-x86"
1596 } else if runtime.GOOS == "darwin" {
1597 return "darwin-x86"
1598 } else {
1599 panic("Unsupported OS")
1600 }
1601}
Dan Willemsenf173d592017-04-27 14:28:00 -07001602
Taylor Santiago3c16e612024-05-30 14:41:31 -07001603func (c *configImpl) KatiBin() string {
1604 binName := "ckati"
1605 if c.UseABFS() {
1606 binName = "ckati-wrap"
1607 }
1608
1609 return c.PrebuiltBuildTool(binName)
1610}
1611
1612func (c *configImpl) NinjaBin() string {
1613 binName := "ninja"
1614 if c.UseABFS() {
1615 binName = "ninjago"
1616 }
1617 return c.PrebuiltBuildTool(binName)
1618}
1619
Dan Willemsen8122bd52017-10-12 20:20:41 -07001620func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001621 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1622 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001623 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1624 if _, err := os.Stat(asan); err == nil {
1625 return asan
1626 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001627 }
1628 }
1629 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1630}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001631
1632func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1633 c.brokenDupRules = val
1634}
1635
1636func (c *configImpl) BuildBrokenDupRules() bool {
1637 return c.brokenDupRules
1638}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001639
Dan Willemsen25e6f092019-04-09 10:22:43 -07001640func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1641 c.brokenUsesNetwork = val
1642}
1643
1644func (c *configImpl) BuildBrokenUsesNetwork() bool {
1645 return c.brokenUsesNetwork
1646}
1647
Dan Willemsene3336352020-01-02 19:10:38 -08001648func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1649 c.brokenNinjaEnvVars = val
1650}
1651
1652func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1653 return c.brokenNinjaEnvVars
1654}
1655
Spandan Das28a6f192024-07-01 21:00:25 +00001656func (c *configImpl) SetBuildBrokenMissingOutputs(val bool) {
1657 c.brokenMissingOutputs = val
1658}
1659
1660func (c *configImpl) BuildBrokenMissingOutputs() bool {
1661 return c.brokenMissingOutputs
1662}
1663
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001664func (c *configImpl) SetTargetDeviceDir(dir string) {
1665 c.targetDeviceDir = dir
1666}
1667
1668func (c *configImpl) TargetDeviceDir() string {
1669 return c.targetDeviceDir
1670}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001671
Patrice Arruda219eef32020-06-01 17:29:30 +00001672func (c *configImpl) BuildDateTime() string {
1673 return c.buildDateTime
1674}
1675
1676func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001677 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001678}
Patrice Arruda83842d72020-12-08 19:42:08 +00001679
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001680// LogsDir returns the absolute path to the logs directory where build log and
1681// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001682// directory. If the argument dist is specified, the logs directory
1683// is <dist_dir>/logs.
1684func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001685 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001686 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001687 // 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 -05001688 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001689 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001690 absDir, err := filepath.Abs(dir)
1691 if err != nil {
1692 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1693 os.Exit(1)
1694 }
1695 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001696}
1697
Chris Parsons53f68ae2022-03-03 12:01:40 -05001698// MkFileMetrics returns the file path for make-related metrics.
1699func (c *configImpl) MkMetrics() string {
1700 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1701}
1702
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001703func (c *configImpl) SetEmptyNinjaFile(v bool) {
1704 c.emptyNinjaFile = v
1705}
1706
1707func (c *configImpl) EmptyNinjaFile() bool {
1708 return c.emptyNinjaFile
1709}
Yu Liu6e13b402021-07-27 14:29:06 -07001710
MarkDacekd0e7cd32022-12-02 22:22:40 +00001711func (c *configImpl) SkipMetricsUpload() bool {
1712 return c.skipMetricsUpload
1713}
1714
MarkDacekf47e1422023-04-19 16:47:36 +00001715func (c *configImpl) EnsureAllowlistIntegrity() bool {
1716 return c.ensureAllowlistIntegrity
1717}
1718
MarkDacek6614d9c2022-12-07 21:57:38 +00001719// Returns a Time object if one was passed via a command-line flag.
1720// Otherwise returns the passed default.
1721func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1722 if c.buildStartedTime == 0 {
1723 return defaultTime
1724 }
1725 return time.UnixMilli(c.buildStartedTime)
1726}
1727
Yu Liu6e13b402021-07-27 14:29:06 -07001728func GetMetricsUploader(topDir string, env *Environment) string {
1729 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1730 metricsUploader := filepath.Join(topDir, p)
1731 if _, err := os.Stat(metricsUploader); err == nil {
1732 return metricsUploader
1733 }
1734 }
1735
1736 return ""
1737}