blob: 5c2debbc88192b03b2ae77ae1e7bfb6199f745b7 [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
LaMont Jones54b01cd2024-10-23 13:59:40 -070033 "android/soong/finder/fs"
Jeff Gastonefc1b412017-03-29 17:29:06 -070034 "android/soong/shared"
LaMont Jones9a912862023-11-06 22:11:08 +000035 "android/soong/ui/metrics"
Kousik Kumarec478642020-09-21 13:39:24 -040036
Dan Willemsen4591b642021-05-24 14:24:12 -070037 "google.golang.org/protobuf/proto"
Patrice Arruda96850362020-08-11 20:41:11 +000038
39 smpb "android/soong/ui/metrics/metrics_proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070040)
41
Kousik Kumar3ff037e2022-01-25 22:11:01 -050042const (
Chris Parsons53f68ae2022-03-03 12:01:40 -050043 envConfigDir = "vendor/google/tools/soong_config"
44 jsonSuffix = "json"
Taylor Santiago8b0bed72024-09-03 13:30:22 -070045 abfsSrcDir = "/src"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050046)
47
Kousik Kumar4c180ad2022-05-27 07:48:37 -040048var (
Kevin Dagostino096ab2f2023-03-03 19:47:17 +000049 rbeRandPrefix int
50 googleProdCredsExistCache bool
Kousik Kumar4c180ad2022-05-27 07:48:37 -040051)
52
53func init() {
54 rand.Seed(time.Now().UnixNano())
55 rbeRandPrefix = rand.Intn(1000)
56}
57
LaMont Jonesece626c2024-09-03 11:19:31 -070058// Which builder are we using?
59type ninjaCommandType = int
60
61const (
62 _ = iota
63 NINJA_NINJA
64 NINJA_N2
65 NINJA_SISO
66)
67
Dan Willemsen1e704462016-08-21 15:17:17 -070068type Config struct{ *configImpl }
69
70type configImpl struct {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020071 // Some targets that are implemented in soong_build
Colin Cross28f527c2019-11-26 16:19:04 -080072 arguments []string
73 goma bool
74 environ *Environment
75 distDir string
76 buildDateTime string
MarkDacek6614d9c2022-12-07 21:57:38 +000077 logsPrefix string
Dan Willemsen1e704462016-08-21 15:17:17 -070078
79 // From the arguments
MarkDacekf47e1422023-04-19 16:47:36 +000080 parallel int
81 keepGoing int
82 verbose bool
83 checkbuild bool
84 dist bool
85 jsonModuleGraph bool
MarkDacekf47e1422023-04-19 16:47:36 +000086 reportMkMetrics bool // Collect and report mk2bp migration progress metrics.
87 soongDocs bool
MarkDacekf47e1422023-04-19 16:47:36 +000088 skipConfig bool
89 skipKati bool
90 skipKatiNinja bool
91 skipSoong bool
92 skipNinja bool
93 skipSoongTests bool
94 searchApiDir bool // Scan the Android.bp files generated in out/api_surfaces
95 skipMetricsUpload bool
96 buildStartedTime int64 // For metrics-upload-only - manually specify a build-started time
Jihoon Kang2a929ad2023-06-08 19:02:07 +000097 buildFromSourceStub bool
Yu Liufa297642024-06-11 00:13:02 +000098 incrementalBuildActions bool
Colin Cross8d411ff2023-12-07 10:31:24 -080099 ensureAllowlistIntegrity bool // For CI builds - make sure modules are mixed-built
Dan Willemsen1e704462016-08-21 15:17:17 -0700100
101 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -0700102 katiArgs []string
103 ninjaArgs []string
104 katiSuffix string
105 targetDevice string
106 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +0000107 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -0700108
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800109 // Autodetected
LaMont Jones54b01cd2024-10-23 13:59:40 -0700110 totalRAM uint64
111 systemCpuInfo *metrics.CpuInfo
112 systemMemInfo *metrics.MemInfo
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800113
Spandan Das28a6f192024-07-01 21:00:25 +0000114 brokenDupRules bool
115 brokenUsesNetwork bool
116 brokenNinjaEnvVars []string
117 brokenMissingOutputs bool
Dan Willemsen18490112018-05-25 16:30:04 -0700118
119 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000120
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700121 // Set by multiproduct_kati
122 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700123
124 metricsUploader string
MarkDacekd06db5d2022-11-29 00:47:59 +0000125
Sam Delmerico98a73292023-02-21 11:50:29 -0500126 includeTags []string
127 sourceRootDirs []string
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900128
129 // Data source to write ninja weight list
130 ninjaWeightListSource NinjaWeightListSource
Joe Onoratoe5ed3472024-02-02 14:52:05 -0800131
132 // This file is a detailed dump of all soong-defined modules for debugging purposes.
133 // There's quite a bit of overlap with module-info.json and soong module graph. We
134 // could consider merging them.
135 moduleDebugFile string
Cole Faustbee030d2024-01-03 13:45:48 -0800136
LaMont Jonesece626c2024-09-03 11:19:31 -0700137 // Which builder are we using
138 ninjaCommand ninjaCommandType
Dan Willemsen1e704462016-08-21 15:17:17 -0700139}
140
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900141type NinjaWeightListSource uint
142
143const (
144 // ninja doesn't use weight list.
145 NOT_USED NinjaWeightListSource = iota
146 // ninja uses weight list based on previous builds by ninja log
147 NINJA_LOG
148 // ninja thinks every task has the same weight.
149 EVENLY_DISTRIBUTED
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900150 // ninja uses an external custom weight list
151 EXTERNAL_FILE
Jeongik Chae114e602023-03-19 00:12:39 +0900152 // ninja uses a prioritized module list from Soong
153 HINT_FROM_SOONG
Jeongik Chaa87506f2023-06-01 23:16:41 +0900154 // If ninja log exists, use NINJA_LOG, if not, use HINT_FROM_SOONG instead.
155 // We can assume it is an incremental build if ninja log exists.
156 DEFAULT
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900157)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800158const srcDirFileCheck = "build/soong/root.bp"
159
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700160var buildFiles = []string{"Android.mk", "Android.bp"}
161
Patrice Arruda13848222019-04-22 17:12:02 -0700162type BuildAction uint
163
164const (
165 // Builds all of the modules and their dependencies of a specified directory, relative to the root
166 // directory of the source tree.
167 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
168
169 // Builds all of the modules and their dependencies of a list of specified directories. All specified
170 // directories are relative to the root directory of the source tree.
171 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700172
173 // Build a list of specified modules. If none was specified, simply build the whole source tree.
174 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700175)
176
177// checkTopDir validates that the current directory is at the root directory of the source tree.
178func checkTopDir(ctx Context) {
179 if _, err := os.Stat(srcDirFileCheck); err != nil {
180 if os.IsNotExist(err) {
181 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
182 }
183 ctx.Fatalln("Error verifying tree state:", err)
184 }
185}
186
MarkDacek7901e582023-01-09 19:48:01 +0000187func loadEnvConfig(ctx Context, config *configImpl, bc string) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500188 if bc == "" {
189 return nil
190 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500191
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500192 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500193 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500194 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500195 envConfigDir,
196 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500197 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500198 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
199 envVarsJSON, err := ioutil.ReadFile(cfgFile)
200 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500201 continue
202 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500203 ctx.Verbosef("Loading config file %v\n", cfgFile)
204 var envVars map[string]map[string]string
205 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
206 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
207 continue
208 }
209 for k, v := range envVars["env"] {
210 if os.Getenv(k) != "" {
211 continue
212 }
213 config.environ.Set(k, v)
214 }
215 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
216 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500217 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500218
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500219 return nil
220}
221
Dan Willemsen1e704462016-08-21 15:17:17 -0700222func NewConfig(ctx Context, args ...string) Config {
223 ret := &configImpl{
Jeongik Chaf2ecf762023-05-19 14:03:45 +0900224 environ: OsEnvironment(),
225 sandboxConfig: &SandboxConfig{},
Jeongik Chaa87506f2023-06-01 23:16:41 +0900226 ninjaWeightListSource: DEFAULT,
Dan Willemsen1e704462016-08-21 15:17:17 -0700227 }
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700228 wd, err := os.Getwd()
229 if err != nil {
230 ctx.Fatalln("Failed to get working directory:", err)
231 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700232
Colin Cross106d6ef2023-10-24 10:34:56 -0700233 // Skip soong tests by default on Linux
234 if runtime.GOOS == "linux" {
235 ret.skipSoongTests = true
236 }
237
Patrice Arruda90109172020-07-28 18:07:27 +0000238 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700239 ret.parallel = runtime.NumCPU() + 2
240 ret.keepGoing = 1
241
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800242 ret.totalRAM = detectTotalRAM(ctx)
LaMont Jones54b01cd2024-10-23 13:59:40 -0700243 ret.systemCpuInfo, err = metrics.NewCpuInfo(fs.OsFs)
244 if err != nil {
245 ctx.Fatalln("Failed to get cpuinfo:", err)
246 }
247 ret.systemMemInfo, err = metrics.NewMemInfo(fs.OsFs)
248 if err != nil {
249 ctx.Fatalln("Failed to get meminfo:", err)
250 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700251 ret.parseArgs(ctx, args)
Jeongik Chae114e602023-03-19 00:12:39 +0900252
253 if ret.ninjaWeightListSource == HINT_FROM_SOONG {
Jeongik Chaa87506f2023-06-01 23:16:41 +0900254 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "always")
255 } else if ret.ninjaWeightListSource == DEFAULT {
256 defaultNinjaWeightListSource := NINJA_LOG
257 if _, err := os.Stat(filepath.Join(ret.OutDir(), ninjaLogFileName)); errors.Is(err, os.ErrNotExist) {
258 ctx.Verboseln("$OUT/.ninja_log doesn't exist, use HINT_FROM_SOONG instead")
259 defaultNinjaWeightListSource = HINT_FROM_SOONG
260 } else {
261 ctx.Verboseln("$OUT/.ninja_log exist, use NINJA_LOG")
262 }
263 ret.ninjaWeightListSource = defaultNinjaWeightListSource
264 // soong_build generates ninja hint depending on ninja log existence.
265 // Set it "depend" to avoid soong re-run due to env variable change.
266 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "depend")
Jeongik Chae114e602023-03-19 00:12:39 +0900267 }
Jeongik Chaa87506f2023-06-01 23:16:41 +0900268
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800269 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700270 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700271 ret.environ.Set("OUT_DIR", ret.sandboxPath(wd, filepath.Clean(outDir)))
Dan Willemsen02f3add2017-05-12 13:50:19 -0700272 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800273 outDir := "out"
274 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700275 outDir = filepath.Join(baseDir, filepath.Base(wd))
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800276 }
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700277 ret.environ.Set("OUT_DIR", ret.sandboxPath(wd, outDir))
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800278 }
279
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500280 // loadEnvConfig needs to know what the OUT_DIR is, so it should
281 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000282 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
283
284 if bc != "" {
Kousik Kumarc8818332023-01-16 16:33:05 +0000285 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000286 ctx.Fatalln("Failed to parse env config files: %v", err)
287 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +0000288 if !ret.canSupportRBE() {
289 // Explicitly set USE_RBE env variable to false when we cannot run
290 // an RBE build to avoid ninja local execution pool issues.
291 ret.environ.Set("USE_RBE", "false")
292 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500293 }
294
Dan Willemsen2d31a442018-10-20 21:33:41 -0700295 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
296 ret.distDir = filepath.Clean(distDir)
297 } else {
298 ret.distDir = filepath.Join(ret.OutDir(), "dist")
299 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700300
Spandan Das05063612021-06-25 01:39:04 +0000301 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
302 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
303 }
304
Joe Onoratoe5ed3472024-02-02 14:52:05 -0800305 if os.Getenv("GENERATE_SOONG_DEBUG") == "true" {
306 ret.moduleDebugFile, _ = filepath.Abs(shared.JoinPath(ret.SoongOutDir(), "soong-debug-info.json"))
307 }
308
LaMont Jones99f18962024-10-17 11:50:44 -0700309 // If SOONG_USE_PARTIAL_COMPILE is set, make it one of "true" or the empty string.
310 // This simplifies the generated Ninja rules, so that they only need to check for the empty string.
LaMont Jonesb547c7e2024-12-19 09:52:01 -0800311 if value, ok := ret.environ.Get("SOONG_USE_PARTIAL_COMPILE"); ok {
LaMont Jones99f18962024-10-17 11:50:44 -0700312 if value == "true" || value == "1" || value == "y" || value == "yes" {
313 value = "true"
314 } else {
315 value = ""
316 }
LaMont Jonesb547c7e2024-12-19 09:52:01 -0800317 ret.environ.Set("SOONG_USE_PARTIAL_COMPILE", value)
LaMont Jones99f18962024-10-17 11:50:44 -0700318 }
319
LaMont Jonesece626c2024-09-03 11:19:31 -0700320 ret.ninjaCommand = NINJA_NINJA
321 switch os.Getenv("SOONG_NINJA") {
322 case "n2":
323 ret.ninjaCommand = NINJA_N2
324 case "siso":
325 ret.ninjaCommand = NINJA_SISO
326 default:
327 if os.Getenv("SOONG_USE_N2") == "true" {
328 ret.ninjaCommand = NINJA_N2
329 }
Cole Faustbee030d2024-01-03 13:45:48 -0800330 }
331
Dan Willemsen1e704462016-08-21 15:17:17 -0700332 ret.environ.Unset(
333 // We're already using it
334 "USE_SOONG_UI",
335
336 // We should never use GOROOT/GOPATH from the shell environment
337 "GOROOT",
338 "GOPATH",
339
340 // These should only come from Soong, not the environment.
341 "CLANG",
342 "CLANG_CXX",
343 "CCC_CC",
344 "CCC_CXX",
345
346 // Used by the goma compiler wrapper, but should only be set by
347 // gomacc
348 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800349
350 // We handle this above
351 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700352
Dan Willemsen2d31a442018-10-20 21:33:41 -0700353 // This is handled above too, and set for individual commands later
354 "DIST_DIR",
355
Dan Willemsen68a09852017-04-18 13:56:57 -0700356 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000357 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700358 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700359 "DISPLAY",
360 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000361 "JAVAC",
Nathan Egge978c9342024-07-03 21:13:03 +0000362 "LEX",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700363 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700364 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700365
366 // Drop make flags
367 "MAKEFLAGS",
368 "MAKELEVEL",
369 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700370
371 // Set in envsetup.sh, reset in makefiles
372 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700373
374 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
375 "ANDROID_BUILD_TOP",
376 "ANDROID_HOST_OUT",
377 "ANDROID_PRODUCT_OUT",
378 "ANDROID_HOST_OUT_TESTCASES",
379 "ANDROID_TARGET_OUT_TESTCASES",
380 "ANDROID_TOOLCHAIN",
381 "ANDROID_TOOLCHAIN_2ND_ARCH",
382 "ANDROID_DEV_SCRIPTS",
383 "ANDROID_EMULATOR_PREBUILTS",
384 "ANDROID_PRE_BUILD_PATHS",
Joe Onoratoe5ed3472024-02-02 14:52:05 -0800385
386 // We read it here already, don't let others share in the fun
387 "GENERATE_SOONG_DEBUG",
Cole Faustbee030d2024-01-03 13:45:48 -0800388
LaMont Jonesece626c2024-09-03 11:19:31 -0700389 // Use config.ninjaCommand instead.
390 "SOONG_NINJA",
Cole Faustbee030d2024-01-03 13:45:48 -0800391 "SOONG_USE_N2",
Dan Willemsen1e704462016-08-21 15:17:17 -0700392 )
393
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400394 if ret.UseGoma() || ret.ForceUseGoma() {
395 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
396 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400397 }
398
Dan Willemsen1e704462016-08-21 15:17:17 -0700399 // Tell python not to spam the source tree with .pyc files.
400 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
401
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400402 tmpDir := absPath(ctx, ret.TempDir())
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700403 ret.environ.Set("TMPDIR", ret.sandboxPath(wd, tmpDir))
Dan Willemsen32a669b2018-03-08 19:42:00 -0800404
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700405 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
406 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
407 "llvm-binutils-stable/llvm-symbolizer")
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700408 ret.environ.Set("ASAN_SYMBOLIZER_PATH", ret.sandboxPath(wd, absPath(ctx, symbolizerPath)))
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700409
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800410 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700411 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800412
Yu Liu6e13b402021-07-27 14:29:06 -0700413 srcDir := absPath(ctx, ".")
414 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700415 ctx.Println("You are building in a directory whose absolute path contains a space character:")
416 ctx.Println()
417 ctx.Printf("%q\n", srcDir)
418 ctx.Println()
419 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700420 }
421
Yu Liu6e13b402021-07-27 14:29:06 -0700422 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
423
Dan Willemsendb8457c2017-05-12 16:38:17 -0700424 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700425 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
426 ctx.Println()
427 ctx.Printf("%q\n", outDir)
428 ctx.Println()
429 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700430 }
431
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000432 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700433 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
434 ctx.Println()
435 ctx.Printf("%q\n", distDir)
436 ctx.Println()
437 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700438 }
439
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700440 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000441 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
Sorin Basca0760c892023-11-29 19:13:55 +0000442 java21Home := filepath.Join("prebuilts/jdk/jdk21", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700443 javaHome := func() string {
444 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
445 return override
446 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000447 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
Sorin Basca5dfa2382024-03-11 17:23:06 +0000448 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 +0100449 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000450 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
Sorin Basca5dfa2382024-03-11 17:23:06 +0000451 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 +0000452 }
Sorin Basca5dfa2382024-03-11 17:23:06 +0000453 if toolchain21, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK21_TOOLCHAIN"); ok && toolchain21 != "true" {
454 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK21_TOOLCHAIN is no longer supported. An OpenJDK 21 toolchain is now the global default.")
455 }
456 return java21Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700457 }()
458 absJavaHome := absPath(ctx, javaHome)
459
Dan Willemsened869522018-01-08 14:58:46 -0800460 ret.configureLocale(ctx)
461
PODISHETTY KUMAR (xWF)9543d192024-09-02 03:54:36 +0000462 newPath := []string{filepath.Join(absJavaHome, "bin")}
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700463 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
PODISHETTY KUMAR (xWF)9543d192024-09-02 03:54:36 +0000464 newPath = append(newPath, path)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700465 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100466
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700467 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700468 ret.environ.Set("JAVA_HOME", ret.sandboxPath(wd, absJavaHome))
469 ret.environ.Set("ANDROID_JAVA_HOME", ret.sandboxPath(wd, javaHome))
470 ret.environ.Set("ANDROID_JAVA8_HOME", ret.sandboxPath(wd, java8Home))
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700471 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
472
Colin Crossfe5ed4d2023-07-28 09:27:23 -0700473 // b/286885495, https://bugzilla.redhat.com/show_bug.cgi?id=2227130: some versions of Fedora include patches
474 // to unzip to enable zipbomb detection that incorrectly handle zip64 and data descriptors and fail on large
475 // zip files produced by soong_zip. Disable zipbomb detection.
476 ret.environ.Set("UNZIP_DISABLE_ZIPBOMB_DETECTION", "TRUE")
477
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800478 outDir := ret.OutDir()
479 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800480 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800481 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800482 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800483 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800484 }
Colin Cross28f527c2019-11-26 16:19:04 -0800485
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700486 ret.environ.Set("BUILD_DATETIME_FILE", ret.sandboxPath(wd, buildDateTimeFile))
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800487
Cole Faust583dfb42023-09-28 13:56:30 -0700488 if _, ok := ret.environ.Get("BUILD_USERNAME"); !ok {
489 username := "unknown"
490 if u, err := user.Current(); err == nil {
491 username = u.Username
492 } else {
493 ctx.Println("Failed to get current user:", err)
494 }
495 ret.environ.Set("BUILD_USERNAME", username)
496 }
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700497 ret.environ.Set("PWD", ret.sandboxPath(wd, wd))
Cole Faust583dfb42023-09-28 13:56:30 -0700498
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400499 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400500 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400501 ret.environ.Set(k, v)
502 }
503 }
504
Patrice Arruda96850362020-08-11 20:41:11 +0000505 c := Config{ret}
506 storeConfigMetrics(ctx, c)
507 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700508}
509
Patrice Arruda13848222019-04-22 17:12:02 -0700510// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
511// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700512func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
513 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700514}
515
LaMont Jones9a912862023-11-06 22:11:08 +0000516// Prepare for getting make variables. For them to be accurate, we need to have
517// obtained PRODUCT_RELEASE_CONFIG_MAPS.
518//
519// Returns:
520//
521// Whether config should be called again.
522//
523// TODO: when converting product config to a declarative language, make sure
524// that PRODUCT_RELEASE_CONFIG_MAPS is properly handled as a separate step in
525// that process.
526func SetProductReleaseConfigMaps(ctx Context, config Config) bool {
527 ctx.BeginTrace(metrics.RunKati, "SetProductReleaseConfigMaps")
528 defer ctx.EndTrace()
529
530 if config.SkipConfig() {
531 // This duplicates the logic from Build to skip product config
532 // if the user has explicitly said to.
533 return false
534 }
535
536 releaseConfigVars := []string{
537 "PRODUCT_RELEASE_CONFIG_MAPS",
538 }
539
540 origValue, _ := config.environ.Get("PRODUCT_RELEASE_CONFIG_MAPS")
541 // Get the PRODUCT_RELEASE_CONFIG_MAPS for this product, to avoid polluting the environment
542 // when we run product config to get the rest of the make vars.
543 releaseMapVars, err := dumpMakeVars(ctx, config, nil, releaseConfigVars, false, "")
544 if err != nil {
545 ctx.Fatalln("Error getting PRODUCT_RELEASE_CONFIG_MAPS:", err)
546 }
547 productReleaseConfigMaps := releaseMapVars["PRODUCT_RELEASE_CONFIG_MAPS"]
548 os.Setenv("PRODUCT_RELEASE_CONFIG_MAPS", productReleaseConfigMaps)
549 return origValue != productReleaseConfigMaps
550}
551
Patrice Arruda96850362020-08-11 20:41:11 +0000552// storeConfigMetrics selects a set of configuration information and store in
553// the metrics system for further analysis.
554func storeConfigMetrics(ctx Context, config Config) {
555 if ctx.Metrics == nil {
556 return
557 }
558
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400559 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000560
LaMont Jones54b01cd2024-10-23 13:59:40 -0700561 cpuInfo := &smpb.SystemCpuInfo{
562 VendorId: proto.String(config.systemCpuInfo.VendorId),
563 ModelName: proto.String(config.systemCpuInfo.ModelName),
564 CpuCores: proto.Int32(config.systemCpuInfo.CpuCores),
565 Flags: proto.String(config.systemCpuInfo.Flags),
566 }
567 memInfo := &smpb.SystemMemInfo{
568 MemTotal: proto.Uint64(config.systemMemInfo.MemTotal),
569 MemFree: proto.Uint64(config.systemMemInfo.MemFree),
570 MemAvailable: proto.Uint64(config.systemMemInfo.MemAvailable),
571 }
572
Patrice Arruda3edfd482020-10-13 23:58:41 +0000573 s := &smpb.SystemResourceInfo{
574 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
575 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
LaMont Jones54b01cd2024-10-23 13:59:40 -0700576 CpuInfo: cpuInfo,
577 MemInfo: memInfo,
Patrice Arruda3edfd482020-10-13 23:58:41 +0000578 }
579 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000580}
581
Jeongik Cha8d63d562023-03-17 03:52:13 +0900582func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900583 switch s {
584 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900585 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900586 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900587 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900588 case EXTERNAL_FILE:
589 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900590 case HINT_FROM_SOONG:
591 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900592 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900593 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900594 }
595}
596
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400597func buildConfig(config Config) *smpb.BuildConfig {
LaMont Jonesb547c7e2024-12-19 09:52:01 -0800598 var soongEnvVars *smpb.SoongEnvVars
599 ensure := func() *smpb.SoongEnvVars {
600 // Create soongEnvVars if it doesn't already exist.
601 if soongEnvVars == nil {
602 soongEnvVars = &smpb.SoongEnvVars{}
603 }
604 return soongEnvVars
605 }
606 if value, ok := config.environ.Get("SOONG_PARTIAL_COMPILE"); ok {
607 ensure().PartialCompile = proto.String(value)
608 }
609 if value, ok := config.environ.Get("SOONG_USE_PARTIAL_COMPILE"); ok {
610 ensure().UsePartialCompile = proto.String(value)
611 }
Yu Liue737a992021-10-04 13:21:41 -0700612 c := &smpb.BuildConfig{
Colin Cross8d411ff2023-12-07 10:31:24 -0800613 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
614 UseGoma: proto.Bool(config.UseGoma()),
615 UseRbe: proto.Bool(config.UseRBE()),
616 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
LaMont Jonesb547c7e2024-12-19 09:52:01 -0800617 SoongEnvVars: soongEnvVars,
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400618 }
Yu Liue737a992021-10-04 13:21:41 -0700619 c.Targets = append(c.Targets, config.arguments...)
620
621 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400622}
623
Patrice Arruda13848222019-04-22 17:12:02 -0700624// getConfigArgs processes the command arguments based on the build action and creates a set of new
625// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700626func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700627 // The next block of code verifies that the current directory is the root directory of the source
628 // tree. It then finds the relative path of dir based on the root directory of the source tree
629 // and verify that dir is inside of the source tree.
630 checkTopDir(ctx)
631 topDir, err := os.Getwd()
632 if err != nil {
633 ctx.Fatalf("Error retrieving top directory: %v", err)
634 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700635 dir, err = filepath.EvalSymlinks(dir)
636 if err != nil {
637 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
638 }
Patrice Arruda13848222019-04-22 17:12:02 -0700639 dir, err = filepath.Abs(dir)
640 if err != nil {
641 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
642 }
643 relDir, err := filepath.Rel(topDir, dir)
644 if err != nil {
645 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
646 }
647 // If there are ".." in the path, it's not in the source tree.
648 if strings.Contains(relDir, "..") {
649 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
650 }
651
652 configArgs := args[:]
653
654 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
655 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
656 targetNamePrefix := "MODULES-IN-"
657 if inList("GET-INSTALL-PATH", configArgs) {
658 targetNamePrefix = "GET-INSTALL-PATH-IN-"
659 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
660 }
661
Patrice Arruda13848222019-04-22 17:12:02 -0700662 var targets []string
663
664 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700665 case BUILD_MODULES:
666 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700667 case BUILD_MODULES_IN_A_DIRECTORY:
668 // If dir is the root source tree, all the modules are built of the source tree are built so
669 // no need to find the build file.
670 if topDir == dir {
671 break
672 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700673
Patrice Arruda13848222019-04-22 17:12:02 -0700674 buildFile := findBuildFile(ctx, relDir)
675 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700676 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700677 }
Patrice Arruda13848222019-04-22 17:12:02 -0700678 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
679 case BUILD_MODULES_IN_DIRECTORIES:
680 newConfigArgs, dirs := splitArgs(configArgs)
681 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700682 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700683 }
684
685 // Tidy only override all other specified targets.
686 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
687 if tidyOnly == "true" || tidyOnly == "1" {
688 configArgs = append(configArgs, "tidy_only")
689 } else {
690 configArgs = append(configArgs, targets...)
691 }
692
693 return configArgs
694}
695
696// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
697func convertToTarget(dir string, targetNamePrefix string) string {
698 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
699}
700
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700701// hasBuildFile returns true if dir contains an Android build file.
702func hasBuildFile(ctx Context, dir string) bool {
703 for _, buildFile := range buildFiles {
704 _, err := os.Stat(filepath.Join(dir, buildFile))
705 if err == nil {
706 return true
707 }
708 if !os.IsNotExist(err) {
709 ctx.Fatalf("Error retrieving the build file stats: %v", err)
710 }
711 }
712 return false
713}
714
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700715// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
716// in the current and any sub directory of dir. If a build file is not found, traverse the path
717// up by one directory and repeat again until either a build file is found or reached to the root
718// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
719// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700720func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700721 // If the string is empty or ".", assume it is top directory of the source tree.
722 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700723 return ""
724 }
725
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700726 found := false
727 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
728 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
729 if err != nil {
730 return err
731 }
732 if found {
733 return filepath.SkipDir
734 }
735 if info.IsDir() {
736 return nil
737 }
738 for _, buildFile := range buildFiles {
739 if info.Name() == buildFile {
740 found = true
741 return filepath.SkipDir
742 }
743 }
744 return nil
745 })
746 if err != nil {
747 ctx.Fatalf("Error finding Android build file: %v", err)
748 }
749
750 if found {
751 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700752 }
753 }
754
755 return ""
756}
757
758// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
759func splitArgs(args []string) (newArgs []string, dirs []string) {
760 specialArgs := map[string]bool{
761 "showcommands": true,
762 "snod": true,
763 "dist": true,
764 "checkbuild": true,
765 }
766
767 newArgs = []string{}
768 dirs = []string{}
769
770 for _, arg := range args {
771 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
772 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
773 newArgs = append(newArgs, arg)
774 continue
775 }
776
777 if _, ok := specialArgs[arg]; ok {
778 newArgs = append(newArgs, arg)
779 continue
780 }
781
782 dirs = append(dirs, arg)
783 }
784
785 return newArgs, dirs
786}
787
788// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
789// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
790// source root tree where the build action command was invoked. Each directory is validated if the
791// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700792func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700793 for _, dir := range dirs {
794 // The directory may have specified specific modules to build. ":" is the separator to separate
795 // the directory and the list of modules.
796 s := strings.Split(dir, ":")
797 l := len(s)
798 if l > 2 { // more than one ":" was specified.
799 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
800 }
801
802 dir = filepath.Join(relDir, s[0])
803 if _, err := os.Stat(dir); err != nil {
804 ctx.Fatalf("couldn't find directory %s", dir)
805 }
806
807 // Verify that if there are any targets specified after ":". Each target is separated by ",".
808 var newTargets []string
809 if l == 2 && s[1] != "" {
810 newTargets = strings.Split(s[1], ",")
811 if inList("", newTargets) {
812 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
813 }
814 }
815
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700816 // If there are specified targets to build in dir, an android build file must exist for the one
817 // shot build. For the non-targets case, find the appropriate build file and build all the
818 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700819 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700820 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700821 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
822 }
823 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700824 buildFile := findBuildFile(ctx, dir)
825 if buildFile == "" {
826 ctx.Fatalf("Build file not found for %s directory", dir)
827 }
828 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700829 }
830
Patrice Arruda13848222019-04-22 17:12:02 -0700831 targets = append(targets, newTargets...)
832 }
833
Dan Willemsence41e942019-07-29 23:39:30 -0700834 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700835}
836
Dan Willemsen9b587492017-07-10 22:13:00 -0700837func (c *configImpl) parseArgs(ctx Context, args []string) {
838 for i := 0; i < len(args); i++ {
839 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100840 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700841 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200842 } else if arg == "--empty-ninja-file" {
843 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100844 } else if arg == "--skip-ninja" {
845 c.skipNinja = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100846 } else if arg == "--soong-only" {
847 c.skipKati = true
848 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200849 } else if arg == "--config-only" {
850 c.skipKati = true
851 c.skipKatiNinja = true
852 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700853 } else if arg == "--skip-config" {
854 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700855 } else if arg == "--skip-soong-tests" {
856 c.skipSoongTests = true
Colin Cross106d6ef2023-10-24 10:34:56 -0700857 } else if arg == "--no-skip-soong-tests" {
858 c.skipSoongTests = false
MarkDacekd0e7cd32022-12-02 22:22:40 +0000859 } else if arg == "--skip-metrics-upload" {
860 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500861 } else if arg == "--mk-metrics" {
862 c.reportMkMetrics = true
Spandan Das394aa322022-11-03 17:02:10 +0000863 } else if arg == "--search-api-dir" {
864 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900865 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
866 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
867 if source == "ninja_log" {
868 c.ninjaWeightListSource = NINJA_LOG
869 } else if source == "evenly_distributed" {
870 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
871 } else if source == "not_used" {
872 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900873 } else if source == "soong" {
874 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900875 } else if strings.HasPrefix(source, "file,") {
876 c.ninjaWeightListSource = EXTERNAL_FILE
877 filePath := strings.TrimPrefix(source, "file,")
878 err := validateNinjaWeightList(filePath)
879 if err != nil {
880 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
881 }
882 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
883 if err != nil {
884 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
885 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900886 } else {
887 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
888 }
Jihoon Kang2a929ad2023-06-08 19:02:07 +0000889 } else if arg == "--build-from-source-stub" {
890 c.buildFromSourceStub = true
Yu Liufa297642024-06-11 00:13:02 +0000891 } else if arg == "--incremental-build-actions" {
892 c.incrementalBuildActions = true
MarkDacekb96561e2022-12-02 04:34:43 +0000893 } else if strings.HasPrefix(arg, "--build-command=") {
894 buildCmd := strings.TrimPrefix(arg, "--build-command=")
895 // remove quotations
896 buildCmd = strings.TrimPrefix(buildCmd, "\"")
897 buildCmd = strings.TrimSuffix(buildCmd, "\"")
898 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacek6614d9c2022-12-07 21:57:38 +0000899 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
900 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
901 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
902 if err == nil {
903 c.buildStartedTime = val
904 } else {
905 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
906 }
MarkDacekf47e1422023-04-19 16:47:36 +0000907 } else if arg == "--ensure-allowlist-integrity" {
908 c.ensureAllowlistIntegrity = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700909 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700910 parseArgNum := func(def int) int {
911 if len(arg) > 2 {
912 p, err := strconv.ParseUint(arg[2:], 10, 31)
913 if err != nil {
914 ctx.Fatalf("Failed to parse %q: %v", arg, err)
915 }
916 return int(p)
917 } else if i+1 < len(args) {
918 p, err := strconv.ParseUint(args[i+1], 10, 31)
919 if err == nil {
920 i++
921 return int(p)
922 }
923 }
924 return def
925 }
926
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700927 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700928 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700929 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700930 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700931 } else {
932 ctx.Fatalln("Unknown option:", arg)
933 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700934 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700935 if k == "OUT_DIR" {
936 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
937 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700938 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700939 } else if arg == "dist" {
940 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200941 } else if arg == "json-module-graph" {
942 c.jsonModuleGraph = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200943 } else if arg == "soong_docs" {
944 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700945 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700946 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800947 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700948 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700949 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700950 }
951 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700952}
953
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900954func validateNinjaWeightList(weightListFilePath string) (err error) {
955 data, err := os.ReadFile(weightListFilePath)
956 if err != nil {
957 return
958 }
959 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
960 for _, line := range lines {
961 fields := strings.Split(line, ",")
962 if len(fields) != 2 {
963 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
964 }
965 _, err = strconv.Atoi(fields[1])
966 if err != nil {
967 return
968 }
969 }
970 return
971}
972
Dan Willemsened869522018-01-08 14:58:46 -0800973func (c *configImpl) configureLocale(ctx Context) {
974 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
975 output, err := cmd.Output()
976
977 var locales []string
978 if err == nil {
979 locales = strings.Split(string(output), "\n")
980 } else {
981 // If we're unable to list the locales, let's assume en_US.UTF-8
982 locales = []string{"en_US.UTF-8"}
983 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
984 }
985
986 // gettext uses LANGUAGE, which is passed directly through
987
988 // For LANG and LC_*, only preserve the evaluated version of
989 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800990 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800991 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800992 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800993 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800994 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800995 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800996 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800997 }
998
999 c.environ.UnsetWithPrefix("LC_")
1000
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001001 if userLang != "" {
1002 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -08001003 }
1004
1005 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
1006 // for others)
1007 if inList("C.UTF-8", locales) {
1008 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -05001009 } else if inList("C.utf8", locales) {
1010 // These normalize to the same thing
1011 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -08001012 } else if inList("en_US.UTF-8", locales) {
1013 c.environ.Set("LANG", "en_US.UTF-8")
1014 } else if inList("en_US.utf8", locales) {
1015 // These normalize to the same thing
1016 c.environ.Set("LANG", "en_US.UTF-8")
1017 } else {
1018 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
1019 }
1020}
1021
Dan Willemsen1e704462016-08-21 15:17:17 -07001022func (c *configImpl) Environment() *Environment {
1023 return c.environ
1024}
1025
1026func (c *configImpl) Arguments() []string {
1027 return c.arguments
1028}
1029
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001030func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001031 if len(c.Arguments()) > 0 {
1032 // Explicit targets requested that are not special targets like b2pbuild
1033 // or the JSON module graph
1034 return true
1035 }
1036
Joe Onorato35f300d2024-10-21 15:02:44 -07001037 if !c.JsonModuleGraph() && !c.SoongDocs() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001038 // Command line was empty, the default Ninja target is built
1039 return true
1040 }
1041
Colin Cross8d411ff2023-12-07 10:31:24 -08001042 if c.Dist() {
Liz Kammer88677422021-12-15 15:03:19 -05001043 return true
1044 }
1045
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001046 // build.ninja doesn't need to be generated
1047 return false
1048}
1049
Dan Willemsen1e704462016-08-21 15:17:17 -07001050func (c *configImpl) OutDir() string {
1051 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -07001052 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -07001053 }
1054 return "out"
1055}
1056
Dan Willemsen8a073a82017-02-04 17:30:44 -08001057func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -04001058 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001059}
1060
1061func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -07001062 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -08001063}
1064
Dan Willemsen1e704462016-08-21 15:17:17 -07001065func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001066 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001067 return c.arguments
1068 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001069 return c.ninjaArgs
1070}
1071
1072func (c *configImpl) SoongOutDir() string {
1073 return filepath.Join(c.OutDir(), "soong")
1074}
1075
Spandan Das394aa322022-11-03 17:02:10 +00001076func (c *configImpl) ApiSurfacesOutDir() string {
1077 return filepath.Join(c.OutDir(), "api_surfaces")
1078}
1079
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001080func (c *configImpl) PrebuiltOS() string {
1081 switch runtime.GOOS {
1082 case "linux":
1083 return "linux-x86"
1084 case "darwin":
1085 return "darwin-x86"
1086 default:
1087 panic("Unknown GOOS")
1088 }
1089}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001090
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001091func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001092 if c.SkipKatiNinja() {
1093 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1094 } else {
1095 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1096 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001097}
1098
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001099func (c *configImpl) UsedEnvFile(tag string) string {
Kiyoung Kimeaa55a82023-06-05 16:56:49 +09001100 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
Qing Shen713c5422024-08-23 04:09:18 +00001101 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+v+c.CoverageSuffix()+"."+tag)
Kiyoung Kimeaa55a82023-06-05 16:56:49 +09001102 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001103 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1104}
1105
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001106func (c *configImpl) SoongDocsHtml() string {
1107 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1108}
1109
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001110func (c *configImpl) ModuleGraphFile() string {
1111 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1112}
1113
kgui67007242022-01-25 13:50:25 +08001114func (c *configImpl) ModuleActionsFile() string {
1115 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1116}
1117
Jeff Gastonefc1b412017-03-29 17:29:06 -07001118func (c *configImpl) TempDir() string {
1119 return shared.TempDirForOutDir(c.SoongOutDir())
1120}
1121
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001122func (c *configImpl) FileListDir() string {
1123 return filepath.Join(c.OutDir(), ".module_paths")
1124}
1125
Dan Willemsen1e704462016-08-21 15:17:17 -07001126func (c *configImpl) KatiSuffix() string {
1127 if c.katiSuffix != "" {
1128 return c.katiSuffix
1129 }
1130 panic("SetKatiSuffix has not been called")
1131}
1132
Colin Cross37193492017-11-16 17:55:00 -08001133// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1134// user is interested in additional checks at the expense of build time.
1135func (c *configImpl) Checkbuild() bool {
1136 return c.checkbuild
1137}
1138
Dan Willemsen8a073a82017-02-04 17:30:44 -08001139func (c *configImpl) Dist() bool {
1140 return c.dist
1141}
1142
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001143func (c *configImpl) JsonModuleGraph() bool {
1144 return c.jsonModuleGraph
1145}
1146
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001147func (c *configImpl) SoongDocs() bool {
1148 return c.soongDocs
1149}
1150
Dan Willemsen1e704462016-08-21 15:17:17 -07001151func (c *configImpl) IsVerbose() bool {
1152 return c.verbose
1153}
1154
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001155func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1156 return c.ninjaWeightListSource
1157}
1158
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001159func (c *configImpl) SkipKati() bool {
1160 return c.skipKati
1161}
1162
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001163func (c *configImpl) SkipKatiNinja() bool {
1164 return c.skipKatiNinja
1165}
1166
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001167func (c *configImpl) SkipSoong() bool {
1168 return c.skipSoong
1169}
1170
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001171func (c *configImpl) SkipNinja() bool {
1172 return c.skipNinja
1173}
1174
Anton Hansson5a7861a2021-06-04 10:09:01 +01001175func (c *configImpl) SetSkipNinja(v bool) {
1176 c.skipNinja = v
1177}
1178
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001179func (c *configImpl) SkipConfig() bool {
1180 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001181}
1182
Jihoon Kang1bff0342023-01-17 20:40:22 +00001183func (c *configImpl) BuildFromTextStub() bool {
Jihoon Kang2a929ad2023-06-08 19:02:07 +00001184 return !c.buildFromSourceStub
Jihoon Kang1bff0342023-01-17 20:40:22 +00001185}
1186
Dan Willemsen1e704462016-08-21 15:17:17 -07001187func (c *configImpl) TargetProduct() string {
1188 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1189 return v
1190 }
1191 panic("TARGET_PRODUCT is not defined")
1192}
1193
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001194func (c *configImpl) TargetProductOrErr() (string, error) {
1195 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1196 return v, nil
1197 }
1198 return "", fmt.Errorf("TARGET_PRODUCT is not defined")
1199}
1200
Qing Shen713c5422024-08-23 04:09:18 +00001201func (c *configImpl) CoverageSuffix() string {
1202 if v := c.environ.IsEnvTrue("EMMA_INSTRUMENT"); v {
1203 return ".coverage"
1204 }
1205 return ""
1206}
1207
Dan Willemsen02781d52017-05-12 19:28:13 -07001208func (c *configImpl) TargetDevice() string {
1209 return c.targetDevice
1210}
1211
1212func (c *configImpl) SetTargetDevice(device string) {
1213 c.targetDevice = device
1214}
1215
1216func (c *configImpl) TargetBuildVariant() string {
1217 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1218 return v
1219 }
1220 panic("TARGET_BUILD_VARIANT is not defined")
1221}
1222
Dan Willemsen1e704462016-08-21 15:17:17 -07001223func (c *configImpl) KatiArgs() []string {
1224 return c.katiArgs
1225}
1226
1227func (c *configImpl) Parallel() int {
1228 return c.parallel
1229}
1230
Sam Delmerico98a73292023-02-21 11:50:29 -05001231func (c *configImpl) GetSourceRootDirs() []string {
1232 return c.sourceRootDirs
1233}
1234
1235func (c *configImpl) SetSourceRootDirs(i []string) {
1236 c.sourceRootDirs = i
1237}
1238
MarkDacek6614d9c2022-12-07 21:57:38 +00001239func (c *configImpl) GetLogsPrefix() string {
1240 return c.logsPrefix
1241}
1242
1243func (c *configImpl) SetLogsPrefix(prefix string) {
1244 c.logsPrefix = prefix
1245}
1246
Colin Cross8b8bec32019-11-15 13:18:43 -08001247func (c *configImpl) HighmemParallel() int {
1248 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1249 return i
1250 }
1251
1252 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1253 parallel := c.Parallel()
1254 if c.UseRemoteBuild() {
1255 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1256 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1257 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1258 // Return 1/16th of the size of the local pool, rounding up.
1259 return (parallel + 15) / 16
1260 } else if c.totalRAM == 0 {
1261 // Couldn't detect the total RAM, don't restrict highmem processes.
1262 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001263 } else if c.totalRAM <= 16*1024*1024*1024 {
1264 // Less than 16GB of ram, restrict to 1 highmem processes
1265 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001266 } else if c.totalRAM <= 32*1024*1024*1024 {
1267 // Less than 32GB of ram, restrict to 2 highmem processes
1268 return 2
1269 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1270 // If less than 8GB total RAM per process, reduce the number of highmem processes
1271 return p
1272 }
1273 // No restriction on highmem processes
1274 return parallel
1275}
1276
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001277func (c *configImpl) TotalRAM() uint64 {
1278 return c.totalRAM
1279}
1280
Kousik Kumarec478642020-09-21 13:39:24 -04001281// ForceUseGoma determines whether we should override Goma deprecation
1282// and use Goma for the current build or not.
1283func (c *configImpl) ForceUseGoma() bool {
1284 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1285 v = strings.TrimSpace(v)
1286 if v != "" && v != "false" {
1287 return true
1288 }
1289 }
1290 return false
1291}
1292
Dan Willemsen1e704462016-08-21 15:17:17 -07001293func (c *configImpl) UseGoma() bool {
1294 if v, ok := c.environ.Get("USE_GOMA"); ok {
1295 v = strings.TrimSpace(v)
1296 if v != "" && v != "false" {
1297 return true
1298 }
1299 }
1300 return false
1301}
1302
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001303func (c *configImpl) StartGoma() bool {
1304 if !c.UseGoma() {
1305 return false
1306 }
1307
1308 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1309 v = strings.TrimSpace(v)
1310 if v != "" && v != "false" {
1311 return false
1312 }
1313 }
1314 return true
1315}
1316
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001317func (c *configImpl) canSupportRBE() bool {
Joe Onorato86f50e72024-06-24 14:28:25 -07001318 // Only supported on linux
1319 if runtime.GOOS != "linux" {
1320 return false
1321 }
1322
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001323 // Do not use RBE with prod credentials in scenarios when stubby doesn't exist, since
1324 // its unlikely that we will be able to obtain necessary creds without stubby.
1325 authType, _ := c.rbeAuth()
1326 if !c.StubbyExists() && strings.Contains(authType, "use_google_prod_creds") {
1327 return false
1328 }
Taylor Santiago3c16e612024-05-30 14:41:31 -07001329 if c.UseABFS() {
1330 return false
1331 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001332 return true
1333}
1334
Taylor Santiago3c16e612024-05-30 14:41:31 -07001335func (c *configImpl) UseABFS() bool {
1336 if v, ok := c.environ.Get("NO_ABFS"); ok {
1337 v = strings.ToLower(strings.TrimSpace(v))
1338 if v == "true" || v == "1" {
1339 return false
1340 }
1341 }
1342
1343 abfsBox := c.PrebuiltBuildTool("abfsbox")
1344 err := exec.Command(abfsBox, "hash", srcDirFileCheck).Run()
1345 return err == nil
1346}
1347
Taylor Santiago8b0bed72024-09-03 13:30:22 -07001348func (c *configImpl) sandboxPath(base, in string) string {
1349 if !c.UseABFS() {
1350 return in
1351 }
1352
1353 rel, err := filepath.Rel(base, in)
1354 if err != nil {
1355 return in
1356 }
1357
1358 return filepath.Join(abfsSrcDir, rel)
1359}
1360
Ramy Medhatbbf25672019-07-17 12:30:04 +00001361func (c *configImpl) UseRBE() bool {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001362 // These alternate modes of running Soong do not use RBE / reclient.
Joe Onorato35f300d2024-10-21 15:02:44 -07001363 if c.JsonModuleGraph() {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001364 return false
1365 }
1366
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001367 if !c.canSupportRBE() {
Kousik Kumar67ad4342023-06-06 15:09:27 -04001368 return false
1369 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001370
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001371 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001372 v = strings.TrimSpace(v)
1373 if v != "" && v != "false" {
1374 return true
1375 }
1376 }
1377 return false
1378}
1379
1380func (c *configImpl) StartRBE() bool {
1381 if !c.UseRBE() {
1382 return false
1383 }
1384
1385 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1386 v = strings.TrimSpace(v)
1387 if v != "" && v != "false" {
1388 return false
1389 }
1390 }
1391 return true
1392}
1393
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001394func (c *configImpl) rbeProxyLogsDir() string {
1395 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001396 if v, ok := c.environ.Get(f); ok {
1397 return v
1398 }
1399 }
Ramy Medhatbc061762023-10-10 18:36:59 +00001400 return c.rbeTmpDir()
1401}
1402
1403func (c *configImpl) rbeDownloadTmpDir() string {
Cole Faust06ea5312023-10-18 17:38:40 -07001404 for _, f := range []string{"RBE_download_tmp_dir", "FLAG_download_tmp_dir"} {
Ramy Medhatbc061762023-10-10 18:36:59 +00001405 if v, ok := c.environ.Get(f); ok {
1406 return v
1407 }
1408 }
1409 return c.rbeTmpDir()
1410}
1411
1412func (c *configImpl) rbeTmpDir() string {
Yaowen Meid4da2662024-07-24 08:25:12 +00001413 return filepath.Join(c.SoongOutDir(), "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001414}
1415
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001416func (c *configImpl) rbeCacheDir() string {
1417 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1418 if v, ok := c.environ.Get(f); ok {
1419 return v
1420 }
1421 }
1422 return shared.JoinPath(c.SoongOutDir(), "rbe")
1423}
1424
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001425func (c *configImpl) shouldCleanupRBELogsDir() bool {
1426 // Perform a log directory cleanup only when the log directory
1427 // is auto created by the build rather than user-specified.
1428 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Yaowen Meid9108d22024-08-29 16:56:32 +00001429 if v, ok := c.environ.Get(f); ok {
1430 if v != c.rbeTmpDir() {
1431 return false
1432 }
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001433 }
1434 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001435 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001436}
1437
1438func (c *configImpl) rbeExecRoot() string {
1439 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1440 if v, ok := c.environ.Get(f); ok {
1441 return v
1442 }
1443 }
1444 wd, err := os.Getwd()
1445 if err != nil {
1446 return ""
1447 }
1448 return wd
1449}
1450
1451func (c *configImpl) rbeDir() string {
1452 if v, ok := c.environ.Get("RBE_DIR"); ok {
1453 return v
1454 }
1455 return "prebuilts/remoteexecution-client/live/"
1456}
1457
1458func (c *configImpl) rbeReproxy() string {
1459 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1460 if v, ok := c.environ.Get(f); ok {
1461 return v
1462 }
1463 }
1464 return filepath.Join(c.rbeDir(), "reproxy")
1465}
1466
1467func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001468 credFlags := []string{
1469 "use_application_default_credentials",
1470 "use_gce_credentials",
1471 "credential_file",
1472 "use_google_prod_creds",
1473 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001474 for _, cf := range credFlags {
1475 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1476 if v, ok := c.environ.Get(f); ok {
1477 v = strings.TrimSpace(v)
1478 if v != "" && v != "false" && v != "0" {
1479 return "RBE_" + cf, v
1480 }
1481 }
1482 }
1483 }
1484 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001485}
1486
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001487func (c *configImpl) rbeSockAddr(dir string) (string, error) {
Andus Yuc917eb82024-03-06 21:54:15 +00001488 // Absolute path socket addresses have a prefix of //. This should
1489 // be included in the length limit.
1490 maxNameLen := len(syscall.RawSockaddrUnix{}.Path) - 2
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001491 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1492
1493 name := filepath.Join(dir, base)
1494 if len(name) < maxNameLen {
1495 return name, nil
1496 }
1497
1498 name = filepath.Join("/tmp", base)
1499 if len(name) < maxNameLen {
1500 return name, nil
1501 }
1502
1503 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1504}
1505
Kousik Kumar7bc78192022-04-27 14:52:56 -04001506// IsGooglerEnvironment returns true if the current build is running
1507// on a Google developer machine and false otherwise.
1508func (c *configImpl) IsGooglerEnvironment() bool {
1509 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1510 if v, ok := c.environ.Get(cf); ok {
1511 return v == "googler"
1512 }
1513 return false
1514}
1515
1516// GoogleProdCredsExist determine whether credentials exist on the
1517// Googler machine to use remote execution.
1518func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001519 if googleProdCredsExistCache {
1520 return googleProdCredsExistCache
1521 }
andusyu0b3dc032023-06-21 17:29:32 -04001522 if _, err := exec.Command("/usr/bin/gcertstatus", "-nocheck_ssh").Output(); err != nil {
Kousik Kumar7bc78192022-04-27 14:52:56 -04001523 return false
1524 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001525 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001526 return true
1527}
1528
1529// UseRemoteBuild indicates whether to use a remote build acceleration system
1530// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001531func (c *configImpl) UseRemoteBuild() bool {
1532 return c.UseGoma() || c.UseRBE()
1533}
1534
Kousik Kumar7bc78192022-04-27 14:52:56 -04001535// StubbyExists checks whether the stubby binary exists on the machine running
1536// the build.
1537func (c *configImpl) StubbyExists() bool {
1538 if _, err := exec.LookPath("stubby"); err != nil {
1539 return false
1540 }
1541 return true
1542}
1543
Dan Willemsen1e704462016-08-21 15:17:17 -07001544// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001545// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001546// still limited by Parallel()
1547func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001548 if !c.UseRemoteBuild() {
1549 return 0
1550 }
1551 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1552 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001553 }
1554 return 500
1555}
1556
1557func (c *configImpl) SetKatiArgs(args []string) {
1558 c.katiArgs = args
1559}
1560
1561func (c *configImpl) SetNinjaArgs(args []string) {
1562 c.ninjaArgs = args
1563}
1564
1565func (c *configImpl) SetKatiSuffix(suffix string) {
1566 c.katiSuffix = suffix
1567}
1568
Dan Willemsene0879fc2017-08-04 15:06:27 -07001569func (c *configImpl) LastKatiSuffixFile() string {
1570 return filepath.Join(c.OutDir(), "last_kati_suffix")
1571}
1572
1573func (c *configImpl) HasKatiSuffix() bool {
1574 return c.katiSuffix != ""
1575}
1576
Dan Willemsen1e704462016-08-21 15:17:17 -07001577func (c *configImpl) KatiEnvFile() string {
1578 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1579}
1580
Dan Willemsen29971232018-09-26 14:58:30 -07001581func (c *configImpl) KatiBuildNinjaFile() string {
1582 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001583}
1584
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001585func (c *configImpl) KatiPackageNinjaFile() string {
1586 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1587}
1588
Cole Faustc5bfbdd2025-01-08 13:05:40 -08001589func (c *configImpl) KatiSoongOnlyPackageNinjaFile() string {
1590 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiSoongOnlyPackageSuffix+".ninja")
1591}
1592
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001593func (c *configImpl) SoongVarsFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001594 targetProduct, err := c.TargetProductOrErr()
1595 if err != nil {
1596 return filepath.Join(c.SoongOutDir(), "soong.variables")
1597 } else {
Qing Shen713c5422024-08-23 04:09:18 +00001598 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+c.CoverageSuffix()+".variables")
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001599 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001600}
1601
Inseob Kim58c802f2024-06-11 10:59:00 +09001602func (c *configImpl) SoongExtraVarsFile() string {
1603 targetProduct, err := c.TargetProductOrErr()
1604 if err != nil {
1605 return filepath.Join(c.SoongOutDir(), "soong.extra.variables")
1606 } else {
Qing Shen713c5422024-08-23 04:09:18 +00001607 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+c.CoverageSuffix()+".extra.variables")
Inseob Kim58c802f2024-06-11 10:59:00 +09001608 }
1609}
1610
Dan Willemsen1e704462016-08-21 15:17:17 -07001611func (c *configImpl) SoongNinjaFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001612 targetProduct, err := c.TargetProductOrErr()
1613 if err != nil {
1614 return filepath.Join(c.SoongOutDir(), "build.ninja")
1615 } else {
Qing Shen713c5422024-08-23 04:09:18 +00001616 return filepath.Join(c.SoongOutDir(), "build."+targetProduct+c.CoverageSuffix()+".ninja")
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001617 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001618}
1619
1620func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001621 if c.katiSuffix == "" {
1622 return filepath.Join(c.OutDir(), "combined.ninja")
1623 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001624 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1625}
1626
1627func (c *configImpl) SoongAndroidMk() string {
Qing Shen713c5422024-08-23 04:09:18 +00001628 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+c.CoverageSuffix()+".mk")
Dan Willemsen1e704462016-08-21 15:17:17 -07001629}
1630
1631func (c *configImpl) SoongMakeVarsMk() string {
Qing Shen713c5422024-08-23 04:09:18 +00001632 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+c.CoverageSuffix()+".mk")
Dan Willemsen1e704462016-08-21 15:17:17 -07001633}
1634
Colin Crossaa9a2732023-10-27 10:54:27 -07001635func (c *configImpl) SoongBuildMetrics() string {
Colin Crossb67b0612023-10-31 10:02:45 -07001636 return filepath.Join(c.LogsDir(), "soong_build_metrics.pb")
Colin Crossaa9a2732023-10-27 10:54:27 -07001637}
1638
Dan Willemsenf052f782017-05-18 15:29:04 -07001639func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001640 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001641}
1642
Dan Willemsen02781d52017-05-12 19:28:13 -07001643func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001644 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1645}
1646
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001647func (c *configImpl) KatiPackageMkDir() string {
Cole Faustc5bfbdd2025-01-08 13:05:40 -08001648 return filepath.Join(c.SoongOutDir(), "kati_packaging"+c.KatiSuffix())
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001649}
1650
Dan Willemsenf052f782017-05-18 15:29:04 -07001651func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001652 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001653}
1654
1655func (c *configImpl) HostOut() string {
1656 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1657}
1658
1659// This probably needs to be multi-valued, so not exporting it for now
1660func (c *configImpl) hostCrossOut() string {
1661 if runtime.GOOS == "linux" {
1662 return filepath.Join(c.hostOutRoot(), "windows-x86")
1663 } else {
1664 return ""
1665 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001666}
1667
Dan Willemsen1e704462016-08-21 15:17:17 -07001668func (c *configImpl) HostPrebuiltTag() string {
1669 if runtime.GOOS == "linux" {
1670 return "linux-x86"
1671 } else if runtime.GOOS == "darwin" {
1672 return "darwin-x86"
1673 } else {
1674 panic("Unsupported OS")
1675 }
1676}
Dan Willemsenf173d592017-04-27 14:28:00 -07001677
Taylor Santiago3c16e612024-05-30 14:41:31 -07001678func (c *configImpl) KatiBin() string {
1679 binName := "ckati"
1680 if c.UseABFS() {
1681 binName = "ckati-wrap"
1682 }
1683
1684 return c.PrebuiltBuildTool(binName)
1685}
1686
1687func (c *configImpl) NinjaBin() string {
1688 binName := "ninja"
1689 if c.UseABFS() {
1690 binName = "ninjago"
1691 }
1692 return c.PrebuiltBuildTool(binName)
1693}
1694
Cole Faust4e58bba2024-08-22 14:27:03 -07001695func (c *configImpl) N2Bin() string {
1696 path := c.PrebuiltBuildTool("n2")
1697 // Use musl instead of glibc because glibc on the build server is old and has bugs
1698 return strings.ReplaceAll(path, "/linux-x86/", "/linux_musl-x86/")
1699}
1700
LaMont Jonesece626c2024-09-03 11:19:31 -07001701func (c *configImpl) SisoBin() string {
1702 path := c.PrebuiltBuildTool("siso")
1703 // Use musl instead of glibc because glibc on the build server is old and has bugs
1704 return strings.ReplaceAll(path, "/linux-x86/", "/linux_musl-x86/")
1705}
1706
Dan Willemsen8122bd52017-10-12 20:20:41 -07001707func (c *configImpl) PrebuiltBuildTool(name string) string {
Colin Cross7077be42024-10-04 20:37:16 +00001708 if c.environ.IsEnvTrue("SANITIZE_BUILD_TOOL_PREBUILTS") {
1709 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1710 if _, err := os.Stat(asan); err == nil {
1711 return asan
Dan Willemsenf173d592017-04-27 14:28:00 -07001712 }
1713 }
1714 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1715}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001716
1717func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1718 c.brokenDupRules = val
1719}
1720
1721func (c *configImpl) BuildBrokenDupRules() bool {
1722 return c.brokenDupRules
1723}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001724
Dan Willemsen25e6f092019-04-09 10:22:43 -07001725func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1726 c.brokenUsesNetwork = val
1727}
1728
1729func (c *configImpl) BuildBrokenUsesNetwork() bool {
1730 return c.brokenUsesNetwork
1731}
1732
Dan Willemsene3336352020-01-02 19:10:38 -08001733func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1734 c.brokenNinjaEnvVars = val
1735}
1736
1737func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1738 return c.brokenNinjaEnvVars
1739}
1740
Spandan Das28a6f192024-07-01 21:00:25 +00001741func (c *configImpl) SetBuildBrokenMissingOutputs(val bool) {
1742 c.brokenMissingOutputs = val
1743}
1744
1745func (c *configImpl) BuildBrokenMissingOutputs() bool {
1746 return c.brokenMissingOutputs
1747}
1748
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001749func (c *configImpl) SetTargetDeviceDir(dir string) {
1750 c.targetDeviceDir = dir
1751}
1752
1753func (c *configImpl) TargetDeviceDir() string {
1754 return c.targetDeviceDir
1755}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001756
Patrice Arruda219eef32020-06-01 17:29:30 +00001757func (c *configImpl) BuildDateTime() string {
1758 return c.buildDateTime
1759}
1760
1761func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001762 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001763}
Patrice Arruda83842d72020-12-08 19:42:08 +00001764
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001765// LogsDir returns the absolute path to the logs directory where build log and
1766// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001767// directory. If the argument dist is specified, the logs directory
1768// is <dist_dir>/logs.
1769func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001770 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001771 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001772 // 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 -05001773 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001774 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001775 absDir, err := filepath.Abs(dir)
1776 if err != nil {
1777 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1778 os.Exit(1)
1779 }
1780 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001781}
1782
Chris Parsons53f68ae2022-03-03 12:01:40 -05001783// MkFileMetrics returns the file path for make-related metrics.
1784func (c *configImpl) MkMetrics() string {
1785 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1786}
1787
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001788func (c *configImpl) SetEmptyNinjaFile(v bool) {
1789 c.emptyNinjaFile = v
1790}
1791
1792func (c *configImpl) EmptyNinjaFile() bool {
1793 return c.emptyNinjaFile
1794}
Yu Liu6e13b402021-07-27 14:29:06 -07001795
MarkDacekd0e7cd32022-12-02 22:22:40 +00001796func (c *configImpl) SkipMetricsUpload() bool {
Taylor Santiago8b0bed72024-09-03 13:30:22 -07001797 // b/362625275 - Metrics upload sometimes prevents abfs unmount
1798 if c.UseABFS() {
1799 return true
1800 }
1801
MarkDacekd0e7cd32022-12-02 22:22:40 +00001802 return c.skipMetricsUpload
1803}
1804
MarkDacekf47e1422023-04-19 16:47:36 +00001805func (c *configImpl) EnsureAllowlistIntegrity() bool {
1806 return c.ensureAllowlistIntegrity
1807}
1808
MarkDacek6614d9c2022-12-07 21:57:38 +00001809// Returns a Time object if one was passed via a command-line flag.
1810// Otherwise returns the passed default.
1811func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1812 if c.buildStartedTime == 0 {
1813 return defaultTime
1814 }
1815 return time.UnixMilli(c.buildStartedTime)
1816}
1817
Yu Liu6e13b402021-07-27 14:29:06 -07001818func GetMetricsUploader(topDir string, env *Environment) string {
1819 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1820 metricsUploader := filepath.Join(topDir, p)
1821 if _, err := os.Stat(metricsUploader); err == nil {
1822 return metricsUploader
1823 }
1824 }
1825
1826 return ""
1827}