blob: 75edfcd8af9f9c49b95df4dc9af1b8b28a2cab78 [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"
Taylor Santiago8b0bed72024-09-03 13:30:22 -070044 abfsSrcDir = "/src"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050045)
46
Kousik Kumar4c180ad2022-05-27 07:48:37 -040047var (
Kevin Dagostino096ab2f2023-03-03 19:47:17 +000048 rbeRandPrefix int
49 googleProdCredsExistCache bool
Kousik Kumar4c180ad2022-05-27 07:48:37 -040050)
51
52func init() {
53 rand.Seed(time.Now().UnixNano())
54 rbeRandPrefix = rand.Intn(1000)
55}
56
LaMont Jonesece626c2024-09-03 11:19:31 -070057// Which builder are we using?
58type ninjaCommandType = int
59
60const (
61 _ = iota
62 NINJA_NINJA
63 NINJA_N2
64 NINJA_SISO
65)
66
Dan Willemsen1e704462016-08-21 15:17:17 -070067type Config struct{ *configImpl }
68
69type configImpl struct {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020070 // Some targets that are implemented in soong_build
71 // (bp2build, json-module-graph) are not here and have their own bits below.
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 queryview bool
87 reportMkMetrics bool // Collect and report mk2bp migration progress metrics.
88 soongDocs bool
MarkDacekf47e1422023-04-19 16:47:36 +000089 skipConfig bool
90 skipKati bool
91 skipKatiNinja bool
92 skipSoong bool
93 skipNinja bool
94 skipSoongTests bool
95 searchApiDir bool // Scan the Android.bp files generated in out/api_surfaces
96 skipMetricsUpload bool
97 buildStartedTime int64 // For metrics-upload-only - manually specify a build-started time
Jihoon Kang2a929ad2023-06-08 19:02:07 +000098 buildFromSourceStub bool
Yu Liufa297642024-06-11 00:13:02 +000099 incrementalBuildActions bool
Colin Cross8d411ff2023-12-07 10:31:24 -0800100 ensureAllowlistIntegrity bool // For CI builds - make sure modules are mixed-built
LaMont Jones523db942024-10-01 15:32:39 -0700101 partialCompileFlags partialCompileFlags
Dan Willemsen1e704462016-08-21 15:17:17 -0700102
103 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -0700104 katiArgs []string
105 ninjaArgs []string
106 katiSuffix string
107 targetDevice string
108 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +0000109 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -0700110
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800111 // Autodetected
112 totalRAM uint64
113
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
LaMont Jones523db942024-10-01 15:32:39 -0700141type partialCompileFlags struct {
142 // Is partial compilation enabled at all?
143 enabled bool
144
145 // Whether to use d8 instead of r8
146 use_d8 bool
147
148 // Add others as needed.
149}
150
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900151type NinjaWeightListSource uint
152
153const (
154 // ninja doesn't use weight list.
155 NOT_USED NinjaWeightListSource = iota
156 // ninja uses weight list based on previous builds by ninja log
157 NINJA_LOG
158 // ninja thinks every task has the same weight.
159 EVENLY_DISTRIBUTED
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900160 // ninja uses an external custom weight list
161 EXTERNAL_FILE
Jeongik Chae114e602023-03-19 00:12:39 +0900162 // ninja uses a prioritized module list from Soong
163 HINT_FROM_SOONG
Jeongik Chaa87506f2023-06-01 23:16:41 +0900164 // If ninja log exists, use NINJA_LOG, if not, use HINT_FROM_SOONG instead.
165 // We can assume it is an incremental build if ninja log exists.
166 DEFAULT
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900167)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800168const srcDirFileCheck = "build/soong/root.bp"
169
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700170var buildFiles = []string{"Android.mk", "Android.bp"}
171
Patrice Arruda13848222019-04-22 17:12:02 -0700172type BuildAction uint
173
174const (
175 // Builds all of the modules and their dependencies of a specified directory, relative to the root
176 // directory of the source tree.
177 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
178
179 // Builds all of the modules and their dependencies of a list of specified directories. All specified
180 // directories are relative to the root directory of the source tree.
181 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700182
183 // Build a list of specified modules. If none was specified, simply build the whole source tree.
184 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700185)
186
187// checkTopDir validates that the current directory is at the root directory of the source tree.
188func checkTopDir(ctx Context) {
189 if _, err := os.Stat(srcDirFileCheck); err != nil {
190 if os.IsNotExist(err) {
191 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
192 }
193 ctx.Fatalln("Error verifying tree state:", err)
194 }
195}
196
MarkDacek7901e582023-01-09 19:48:01 +0000197func loadEnvConfig(ctx Context, config *configImpl, bc string) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500198 if bc == "" {
199 return nil
200 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500201
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500202 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500203 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500204 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500205 envConfigDir,
206 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500207 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500208 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
209 envVarsJSON, err := ioutil.ReadFile(cfgFile)
210 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500211 continue
212 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500213 ctx.Verbosef("Loading config file %v\n", cfgFile)
214 var envVars map[string]map[string]string
215 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
216 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
217 continue
218 }
219 for k, v := range envVars["env"] {
220 if os.Getenv(k) != "" {
221 continue
222 }
223 config.environ.Set(k, v)
224 }
225 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
226 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500227 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500228
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500229 return nil
230}
231
Dan Willemsen1e704462016-08-21 15:17:17 -0700232func NewConfig(ctx Context, args ...string) Config {
233 ret := &configImpl{
Jeongik Chaf2ecf762023-05-19 14:03:45 +0900234 environ: OsEnvironment(),
235 sandboxConfig: &SandboxConfig{},
Jeongik Chaa87506f2023-06-01 23:16:41 +0900236 ninjaWeightListSource: DEFAULT,
Dan Willemsen1e704462016-08-21 15:17:17 -0700237 }
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700238 wd, err := os.Getwd()
239 if err != nil {
240 ctx.Fatalln("Failed to get working directory:", err)
241 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700242
Colin Cross106d6ef2023-10-24 10:34:56 -0700243 // Skip soong tests by default on Linux
244 if runtime.GOOS == "linux" {
245 ret.skipSoongTests = true
246 }
247
Patrice Arruda90109172020-07-28 18:07:27 +0000248 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700249 ret.parallel = runtime.NumCPU() + 2
250 ret.keepGoing = 1
251
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800252 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700253 ret.parseArgs(ctx, args)
Jeongik Chae114e602023-03-19 00:12:39 +0900254
255 if ret.ninjaWeightListSource == HINT_FROM_SOONG {
Jeongik Chaa87506f2023-06-01 23:16:41 +0900256 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "always")
257 } else if ret.ninjaWeightListSource == DEFAULT {
258 defaultNinjaWeightListSource := NINJA_LOG
259 if _, err := os.Stat(filepath.Join(ret.OutDir(), ninjaLogFileName)); errors.Is(err, os.ErrNotExist) {
260 ctx.Verboseln("$OUT/.ninja_log doesn't exist, use HINT_FROM_SOONG instead")
261 defaultNinjaWeightListSource = HINT_FROM_SOONG
262 } else {
263 ctx.Verboseln("$OUT/.ninja_log exist, use NINJA_LOG")
264 }
265 ret.ninjaWeightListSource = defaultNinjaWeightListSource
266 // soong_build generates ninja hint depending on ninja log existence.
267 // Set it "depend" to avoid soong re-run due to env variable change.
268 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "depend")
Jeongik Chae114e602023-03-19 00:12:39 +0900269 }
Jeongik Chaa87506f2023-06-01 23:16:41 +0900270
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800271 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700272 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700273 ret.environ.Set("OUT_DIR", ret.sandboxPath(wd, filepath.Clean(outDir)))
Dan Willemsen02f3add2017-05-12 13:50:19 -0700274 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800275 outDir := "out"
276 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700277 outDir = filepath.Join(baseDir, filepath.Base(wd))
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800278 }
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700279 ret.environ.Set("OUT_DIR", ret.sandboxPath(wd, outDir))
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800280 }
281
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500282 // loadEnvConfig needs to know what the OUT_DIR is, so it should
283 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000284 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
285
286 if bc != "" {
Kousik Kumarc8818332023-01-16 16:33:05 +0000287 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000288 ctx.Fatalln("Failed to parse env config files: %v", err)
289 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +0000290 if !ret.canSupportRBE() {
291 // Explicitly set USE_RBE env variable to false when we cannot run
292 // an RBE build to avoid ninja local execution pool issues.
293 ret.environ.Set("USE_RBE", "false")
294 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500295 }
296
Dan Willemsen2d31a442018-10-20 21:33:41 -0700297 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
298 ret.distDir = filepath.Clean(distDir)
299 } else {
300 ret.distDir = filepath.Join(ret.OutDir(), "dist")
301 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700302
Spandan Das05063612021-06-25 01:39:04 +0000303 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
304 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
305 }
306
LaMont Jones523db942024-10-01 15:32:39 -0700307 ret.partialCompileFlags = parsePartialCompileFlags(ctx)
308
Joe Onoratoe5ed3472024-02-02 14:52:05 -0800309 if os.Getenv("GENERATE_SOONG_DEBUG") == "true" {
310 ret.moduleDebugFile, _ = filepath.Abs(shared.JoinPath(ret.SoongOutDir(), "soong-debug-info.json"))
311 }
312
LaMont Jonesece626c2024-09-03 11:19:31 -0700313 ret.ninjaCommand = NINJA_NINJA
314 switch os.Getenv("SOONG_NINJA") {
315 case "n2":
316 ret.ninjaCommand = NINJA_N2
317 case "siso":
318 ret.ninjaCommand = NINJA_SISO
319 default:
320 if os.Getenv("SOONG_USE_N2") == "true" {
321 ret.ninjaCommand = NINJA_N2
322 }
Cole Faustbee030d2024-01-03 13:45:48 -0800323 }
324
Dan Willemsen1e704462016-08-21 15:17:17 -0700325 ret.environ.Unset(
326 // We're already using it
327 "USE_SOONG_UI",
328
329 // We should never use GOROOT/GOPATH from the shell environment
330 "GOROOT",
331 "GOPATH",
332
333 // These should only come from Soong, not the environment.
334 "CLANG",
335 "CLANG_CXX",
336 "CCC_CC",
337 "CCC_CXX",
338
339 // Used by the goma compiler wrapper, but should only be set by
340 // gomacc
341 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800342
343 // We handle this above
344 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700345
Dan Willemsen2d31a442018-10-20 21:33:41 -0700346 // This is handled above too, and set for individual commands later
347 "DIST_DIR",
348
Dan Willemsen68a09852017-04-18 13:56:57 -0700349 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000350 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700351 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700352 "DISPLAY",
353 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000354 "JAVAC",
Nathan Egge978c9342024-07-03 21:13:03 +0000355 "LEX",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700356 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700357 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700358
359 // Drop make flags
360 "MAKEFLAGS",
361 "MAKELEVEL",
362 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700363
364 // Set in envsetup.sh, reset in makefiles
365 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700366
367 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
368 "ANDROID_BUILD_TOP",
369 "ANDROID_HOST_OUT",
370 "ANDROID_PRODUCT_OUT",
371 "ANDROID_HOST_OUT_TESTCASES",
372 "ANDROID_TARGET_OUT_TESTCASES",
373 "ANDROID_TOOLCHAIN",
374 "ANDROID_TOOLCHAIN_2ND_ARCH",
375 "ANDROID_DEV_SCRIPTS",
376 "ANDROID_EMULATOR_PREBUILTS",
377 "ANDROID_PRE_BUILD_PATHS",
Joe Onoratoe5ed3472024-02-02 14:52:05 -0800378
379 // We read it here already, don't let others share in the fun
380 "GENERATE_SOONG_DEBUG",
Cole Faustbee030d2024-01-03 13:45:48 -0800381
LaMont Jonesece626c2024-09-03 11:19:31 -0700382 // Use config.ninjaCommand instead.
383 "SOONG_NINJA",
Cole Faustbee030d2024-01-03 13:45:48 -0800384 "SOONG_USE_N2",
LaMont Jones523db942024-10-01 15:32:39 -0700385 "SOONG_PARTIAL_COMPILE",
Dan Willemsen1e704462016-08-21 15:17:17 -0700386 )
387
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400388 if ret.UseGoma() || ret.ForceUseGoma() {
389 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
390 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400391 }
392
Dan Willemsen1e704462016-08-21 15:17:17 -0700393 // Tell python not to spam the source tree with .pyc files.
394 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
395
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400396 tmpDir := absPath(ctx, ret.TempDir())
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700397 ret.environ.Set("TMPDIR", ret.sandboxPath(wd, tmpDir))
Dan Willemsen32a669b2018-03-08 19:42:00 -0800398
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700399 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
400 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
401 "llvm-binutils-stable/llvm-symbolizer")
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700402 ret.environ.Set("ASAN_SYMBOLIZER_PATH", ret.sandboxPath(wd, absPath(ctx, symbolizerPath)))
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700403
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800404 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700405 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800406
Yu Liu6e13b402021-07-27 14:29:06 -0700407 srcDir := absPath(ctx, ".")
408 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700409 ctx.Println("You are building in a directory whose absolute path contains a space character:")
410 ctx.Println()
411 ctx.Printf("%q\n", srcDir)
412 ctx.Println()
413 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700414 }
415
Yu Liu6e13b402021-07-27 14:29:06 -0700416 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
417
Dan Willemsendb8457c2017-05-12 16:38:17 -0700418 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700419 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
420 ctx.Println()
421 ctx.Printf("%q\n", outDir)
422 ctx.Println()
423 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700424 }
425
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000426 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700427 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
428 ctx.Println()
429 ctx.Printf("%q\n", distDir)
430 ctx.Println()
431 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700432 }
433
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700434 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000435 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
Sorin Basca0760c892023-11-29 19:13:55 +0000436 java21Home := filepath.Join("prebuilts/jdk/jdk21", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700437 javaHome := func() string {
438 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
439 return override
440 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000441 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
Sorin Basca5dfa2382024-03-11 17:23:06 +0000442 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 +0100443 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000444 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
Sorin Basca5dfa2382024-03-11 17:23:06 +0000445 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 +0000446 }
Sorin Basca5dfa2382024-03-11 17:23:06 +0000447 if toolchain21, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK21_TOOLCHAIN"); ok && toolchain21 != "true" {
448 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK21_TOOLCHAIN is no longer supported. An OpenJDK 21 toolchain is now the global default.")
449 }
450 return java21Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700451 }()
452 absJavaHome := absPath(ctx, javaHome)
453
Dan Willemsened869522018-01-08 14:58:46 -0800454 ret.configureLocale(ctx)
455
PODISHETTY KUMAR (xWF)9543d192024-09-02 03:54:36 +0000456 newPath := []string{filepath.Join(absJavaHome, "bin")}
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700457 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
PODISHETTY KUMAR (xWF)9543d192024-09-02 03:54:36 +0000458 newPath = append(newPath, path)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700459 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100460
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700461 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700462 ret.environ.Set("JAVA_HOME", ret.sandboxPath(wd, absJavaHome))
463 ret.environ.Set("ANDROID_JAVA_HOME", ret.sandboxPath(wd, javaHome))
464 ret.environ.Set("ANDROID_JAVA8_HOME", ret.sandboxPath(wd, java8Home))
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700465 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
466
Colin Crossfe5ed4d2023-07-28 09:27:23 -0700467 // b/286885495, https://bugzilla.redhat.com/show_bug.cgi?id=2227130: some versions of Fedora include patches
468 // to unzip to enable zipbomb detection that incorrectly handle zip64 and data descriptors and fail on large
469 // zip files produced by soong_zip. Disable zipbomb detection.
470 ret.environ.Set("UNZIP_DISABLE_ZIPBOMB_DETECTION", "TRUE")
471
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800472 outDir := ret.OutDir()
473 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800474 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800475 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800476 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800477 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800478 }
Colin Cross28f527c2019-11-26 16:19:04 -0800479
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700480 ret.environ.Set("BUILD_DATETIME_FILE", ret.sandboxPath(wd, buildDateTimeFile))
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800481
Cole Faust583dfb42023-09-28 13:56:30 -0700482 if _, ok := ret.environ.Get("BUILD_USERNAME"); !ok {
483 username := "unknown"
484 if u, err := user.Current(); err == nil {
485 username = u.Username
486 } else {
487 ctx.Println("Failed to get current user:", err)
488 }
489 ret.environ.Set("BUILD_USERNAME", username)
490 }
Taylor Santiago8b0bed72024-09-03 13:30:22 -0700491 ret.environ.Set("PWD", ret.sandboxPath(wd, wd))
Cole Faust583dfb42023-09-28 13:56:30 -0700492
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400493 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400494 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400495 ret.environ.Set(k, v)
496 }
497 }
498
Patrice Arruda96850362020-08-11 20:41:11 +0000499 c := Config{ret}
500 storeConfigMetrics(ctx, c)
501 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700502}
503
LaMont Jones523db942024-10-01 15:32:39 -0700504// Parse SOONG_PARTIAL_COMPILE.
505//
506// The user-facing documentation shows:
507//
508// - empty or not set: "The current default state"
509// - "true" or "on": enable all stable partial compile features.
510// - "false" or "off": disable partial compile completely.
511//
512// What we actually allow is a comma separated list of tokens, whose first
513// character may be "+" (enable) or "-" (disable). If neither is present, "+"
514// is assumed. For example, "on,+use_d8" will enable partial compilation, and
515// additionally set the use_d8 flag (regardless of whether it is opt-in or
516// opt-out).
517//
518// To add a new feature to the list, add the field in the struct
519// `partialCompileFlags` above, and then add the name of the field in the
520// switch statement below.
521func parsePartialCompileFlags(ctx Context) partialCompileFlags {
522 defaultFlags := partialCompileFlags{
523 // Set any opt-out flags here. Opt-in flags are off by default.
524 enabled: false,
525 }
526 value, ok := os.LookupEnv("SOONG_PARTIAL_COMPILE")
527
528 if !ok {
529 return defaultFlags
530 }
531
532 ret := defaultFlags
533 tokens := strings.Split(strings.ToLower(value), ",")
534 makeVal := func(state string, defaultValue bool) bool {
535 switch state {
536 case "":
537 return defaultValue
538 case "-":
539 return false
540 case "+":
541 return true
542 }
543 return false
544 }
545 for _, tok := range tokens {
546 var state string
547 switch tok[0:1] {
548 case "":
549 // Ignore empty tokens.
550 continue
551 case "-", "+":
552 state = tok[0:1]
553 tok = tok[1:]
554 default:
555 // Treat `feature` as `+feature`.
556 state = "+"
557 }
558 switch tok {
559 case "true", "on", "yes":
560 ret = defaultFlags
561 ret.enabled = true
562 case "false", "off", "no":
563 // Set everything to false.
564 ret = partialCompileFlags{}
565 case "enabled":
566 ret.enabled = makeVal(state, defaultFlags.enabled)
567 case "use_d8":
568 ret.use_d8 = makeVal(state, defaultFlags.use_d8)
569 default:
570 ctx.Fatalln("Unknown SOONG_PARTIAL_COMPILE value:", value)
571 }
572 }
573 return ret
574}
575
Patrice Arruda13848222019-04-22 17:12:02 -0700576// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
577// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700578func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
579 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700580}
581
LaMont Jones9a912862023-11-06 22:11:08 +0000582// Prepare for getting make variables. For them to be accurate, we need to have
583// obtained PRODUCT_RELEASE_CONFIG_MAPS.
584//
585// Returns:
586//
587// Whether config should be called again.
588//
589// TODO: when converting product config to a declarative language, make sure
590// that PRODUCT_RELEASE_CONFIG_MAPS is properly handled as a separate step in
591// that process.
592func SetProductReleaseConfigMaps(ctx Context, config Config) bool {
593 ctx.BeginTrace(metrics.RunKati, "SetProductReleaseConfigMaps")
594 defer ctx.EndTrace()
595
596 if config.SkipConfig() {
597 // This duplicates the logic from Build to skip product config
598 // if the user has explicitly said to.
599 return false
600 }
601
602 releaseConfigVars := []string{
603 "PRODUCT_RELEASE_CONFIG_MAPS",
604 }
605
606 origValue, _ := config.environ.Get("PRODUCT_RELEASE_CONFIG_MAPS")
607 // Get the PRODUCT_RELEASE_CONFIG_MAPS for this product, to avoid polluting the environment
608 // when we run product config to get the rest of the make vars.
609 releaseMapVars, err := dumpMakeVars(ctx, config, nil, releaseConfigVars, false, "")
610 if err != nil {
611 ctx.Fatalln("Error getting PRODUCT_RELEASE_CONFIG_MAPS:", err)
612 }
613 productReleaseConfigMaps := releaseMapVars["PRODUCT_RELEASE_CONFIG_MAPS"]
614 os.Setenv("PRODUCT_RELEASE_CONFIG_MAPS", productReleaseConfigMaps)
615 return origValue != productReleaseConfigMaps
616}
617
Patrice Arruda96850362020-08-11 20:41:11 +0000618// storeConfigMetrics selects a set of configuration information and store in
619// the metrics system for further analysis.
620func storeConfigMetrics(ctx Context, config Config) {
621 if ctx.Metrics == nil {
622 return
623 }
624
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400625 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000626
627 s := &smpb.SystemResourceInfo{
628 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
629 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
630 }
631 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000632}
633
Jeongik Cha8d63d562023-03-17 03:52:13 +0900634func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900635 switch s {
636 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900637 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900638 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900639 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900640 case EXTERNAL_FILE:
641 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900642 case HINT_FROM_SOONG:
643 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900644 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900645 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900646 }
647}
648
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400649func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700650 c := &smpb.BuildConfig{
Colin Cross8d411ff2023-12-07 10:31:24 -0800651 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
652 UseGoma: proto.Bool(config.UseGoma()),
653 UseRbe: proto.Bool(config.UseRBE()),
654 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400655 }
Yu Liue737a992021-10-04 13:21:41 -0700656 c.Targets = append(c.Targets, config.arguments...)
657
658 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400659}
660
Patrice Arruda13848222019-04-22 17:12:02 -0700661// getConfigArgs processes the command arguments based on the build action and creates a set of new
662// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700663func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700664 // The next block of code verifies that the current directory is the root directory of the source
665 // tree. It then finds the relative path of dir based on the root directory of the source tree
666 // and verify that dir is inside of the source tree.
667 checkTopDir(ctx)
668 topDir, err := os.Getwd()
669 if err != nil {
670 ctx.Fatalf("Error retrieving top directory: %v", err)
671 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700672 dir, err = filepath.EvalSymlinks(dir)
673 if err != nil {
674 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
675 }
Patrice Arruda13848222019-04-22 17:12:02 -0700676 dir, err = filepath.Abs(dir)
677 if err != nil {
678 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
679 }
680 relDir, err := filepath.Rel(topDir, dir)
681 if err != nil {
682 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
683 }
684 // If there are ".." in the path, it's not in the source tree.
685 if strings.Contains(relDir, "..") {
686 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
687 }
688
689 configArgs := args[:]
690
691 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
692 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
693 targetNamePrefix := "MODULES-IN-"
694 if inList("GET-INSTALL-PATH", configArgs) {
695 targetNamePrefix = "GET-INSTALL-PATH-IN-"
696 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
697 }
698
Patrice Arruda13848222019-04-22 17:12:02 -0700699 var targets []string
700
701 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700702 case BUILD_MODULES:
703 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700704 case BUILD_MODULES_IN_A_DIRECTORY:
705 // If dir is the root source tree, all the modules are built of the source tree are built so
706 // no need to find the build file.
707 if topDir == dir {
708 break
709 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700710
Patrice Arruda13848222019-04-22 17:12:02 -0700711 buildFile := findBuildFile(ctx, relDir)
712 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700713 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700714 }
Patrice Arruda13848222019-04-22 17:12:02 -0700715 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
716 case BUILD_MODULES_IN_DIRECTORIES:
717 newConfigArgs, dirs := splitArgs(configArgs)
718 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700719 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700720 }
721
722 // Tidy only override all other specified targets.
723 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
724 if tidyOnly == "true" || tidyOnly == "1" {
725 configArgs = append(configArgs, "tidy_only")
726 } else {
727 configArgs = append(configArgs, targets...)
728 }
729
730 return configArgs
731}
732
733// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
734func convertToTarget(dir string, targetNamePrefix string) string {
735 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
736}
737
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700738// hasBuildFile returns true if dir contains an Android build file.
739func hasBuildFile(ctx Context, dir string) bool {
740 for _, buildFile := range buildFiles {
741 _, err := os.Stat(filepath.Join(dir, buildFile))
742 if err == nil {
743 return true
744 }
745 if !os.IsNotExist(err) {
746 ctx.Fatalf("Error retrieving the build file stats: %v", err)
747 }
748 }
749 return false
750}
751
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700752// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
753// in the current and any sub directory of dir. If a build file is not found, traverse the path
754// up by one directory and repeat again until either a build file is found or reached to the root
755// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
756// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700757func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700758 // If the string is empty or ".", assume it is top directory of the source tree.
759 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700760 return ""
761 }
762
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700763 found := false
764 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
765 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
766 if err != nil {
767 return err
768 }
769 if found {
770 return filepath.SkipDir
771 }
772 if info.IsDir() {
773 return nil
774 }
775 for _, buildFile := range buildFiles {
776 if info.Name() == buildFile {
777 found = true
778 return filepath.SkipDir
779 }
780 }
781 return nil
782 })
783 if err != nil {
784 ctx.Fatalf("Error finding Android build file: %v", err)
785 }
786
787 if found {
788 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700789 }
790 }
791
792 return ""
793}
794
795// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
796func splitArgs(args []string) (newArgs []string, dirs []string) {
797 specialArgs := map[string]bool{
798 "showcommands": true,
799 "snod": true,
800 "dist": true,
801 "checkbuild": true,
802 }
803
804 newArgs = []string{}
805 dirs = []string{}
806
807 for _, arg := range args {
808 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
809 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
810 newArgs = append(newArgs, arg)
811 continue
812 }
813
814 if _, ok := specialArgs[arg]; ok {
815 newArgs = append(newArgs, arg)
816 continue
817 }
818
819 dirs = append(dirs, arg)
820 }
821
822 return newArgs, dirs
823}
824
825// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
826// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
827// source root tree where the build action command was invoked. Each directory is validated if the
828// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700829func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700830 for _, dir := range dirs {
831 // The directory may have specified specific modules to build. ":" is the separator to separate
832 // the directory and the list of modules.
833 s := strings.Split(dir, ":")
834 l := len(s)
835 if l > 2 { // more than one ":" was specified.
836 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
837 }
838
839 dir = filepath.Join(relDir, s[0])
840 if _, err := os.Stat(dir); err != nil {
841 ctx.Fatalf("couldn't find directory %s", dir)
842 }
843
844 // Verify that if there are any targets specified after ":". Each target is separated by ",".
845 var newTargets []string
846 if l == 2 && s[1] != "" {
847 newTargets = strings.Split(s[1], ",")
848 if inList("", newTargets) {
849 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
850 }
851 }
852
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700853 // If there are specified targets to build in dir, an android build file must exist for the one
854 // shot build. For the non-targets case, find the appropriate build file and build all the
855 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700856 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700857 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700858 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
859 }
860 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700861 buildFile := findBuildFile(ctx, dir)
862 if buildFile == "" {
863 ctx.Fatalf("Build file not found for %s directory", dir)
864 }
865 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700866 }
867
Patrice Arruda13848222019-04-22 17:12:02 -0700868 targets = append(targets, newTargets...)
869 }
870
Dan Willemsence41e942019-07-29 23:39:30 -0700871 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700872}
873
Dan Willemsen9b587492017-07-10 22:13:00 -0700874func (c *configImpl) parseArgs(ctx Context, args []string) {
875 for i := 0; i < len(args); i++ {
876 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100877 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700878 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200879 } else if arg == "--empty-ninja-file" {
880 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100881 } else if arg == "--skip-ninja" {
882 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700883 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700884 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
885 // but it does run a Kati ninja file if the .kati_enabled marker file was created
886 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000887 c.skipConfig = true
888 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100889 } else if arg == "--soong-only" {
890 c.skipKati = true
891 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200892 } else if arg == "--config-only" {
893 c.skipKati = true
894 c.skipKatiNinja = true
895 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700896 } else if arg == "--skip-config" {
897 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700898 } else if arg == "--skip-soong-tests" {
899 c.skipSoongTests = true
Colin Cross106d6ef2023-10-24 10:34:56 -0700900 } else if arg == "--no-skip-soong-tests" {
901 c.skipSoongTests = false
MarkDacekd0e7cd32022-12-02 22:22:40 +0000902 } else if arg == "--skip-metrics-upload" {
903 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500904 } else if arg == "--mk-metrics" {
905 c.reportMkMetrics = true
Spandan Das394aa322022-11-03 17:02:10 +0000906 } else if arg == "--search-api-dir" {
907 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900908 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
909 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
910 if source == "ninja_log" {
911 c.ninjaWeightListSource = NINJA_LOG
912 } else if source == "evenly_distributed" {
913 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
914 } else if source == "not_used" {
915 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900916 } else if source == "soong" {
917 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900918 } else if strings.HasPrefix(source, "file,") {
919 c.ninjaWeightListSource = EXTERNAL_FILE
920 filePath := strings.TrimPrefix(source, "file,")
921 err := validateNinjaWeightList(filePath)
922 if err != nil {
923 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
924 }
925 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
926 if err != nil {
927 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
928 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900929 } else {
930 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
931 }
Jihoon Kang2a929ad2023-06-08 19:02:07 +0000932 } else if arg == "--build-from-source-stub" {
933 c.buildFromSourceStub = true
Yu Liufa297642024-06-11 00:13:02 +0000934 } else if arg == "--incremental-build-actions" {
935 c.incrementalBuildActions = true
MarkDacekb96561e2022-12-02 04:34:43 +0000936 } else if strings.HasPrefix(arg, "--build-command=") {
937 buildCmd := strings.TrimPrefix(arg, "--build-command=")
938 // remove quotations
939 buildCmd = strings.TrimPrefix(buildCmd, "\"")
940 buildCmd = strings.TrimSuffix(buildCmd, "\"")
941 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacek6614d9c2022-12-07 21:57:38 +0000942 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
943 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
944 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
945 if err == nil {
946 c.buildStartedTime = val
947 } else {
948 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
949 }
MarkDacekf47e1422023-04-19 16:47:36 +0000950 } else if arg == "--ensure-allowlist-integrity" {
951 c.ensureAllowlistIntegrity = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700952 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700953 parseArgNum := func(def int) int {
954 if len(arg) > 2 {
955 p, err := strconv.ParseUint(arg[2:], 10, 31)
956 if err != nil {
957 ctx.Fatalf("Failed to parse %q: %v", arg, err)
958 }
959 return int(p)
960 } else if i+1 < len(args) {
961 p, err := strconv.ParseUint(args[i+1], 10, 31)
962 if err == nil {
963 i++
964 return int(p)
965 }
966 }
967 return def
968 }
969
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700970 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700971 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700972 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700973 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700974 } else {
975 ctx.Fatalln("Unknown option:", arg)
976 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700977 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700978 if k == "OUT_DIR" {
979 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
980 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700981 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700982 } else if arg == "dist" {
983 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200984 } else if arg == "json-module-graph" {
985 c.jsonModuleGraph = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200986 } else if arg == "queryview" {
987 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200988 } else if arg == "soong_docs" {
989 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700990 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700991 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800992 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700993 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700994 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700995 }
996 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700997}
998
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900999func validateNinjaWeightList(weightListFilePath string) (err error) {
1000 data, err := os.ReadFile(weightListFilePath)
1001 if err != nil {
1002 return
1003 }
1004 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
1005 for _, line := range lines {
1006 fields := strings.Split(line, ",")
1007 if len(fields) != 2 {
1008 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
1009 }
1010 _, err = strconv.Atoi(fields[1])
1011 if err != nil {
1012 return
1013 }
1014 }
1015 return
1016}
1017
Dan Willemsened869522018-01-08 14:58:46 -08001018func (c *configImpl) configureLocale(ctx Context) {
1019 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
1020 output, err := cmd.Output()
1021
1022 var locales []string
1023 if err == nil {
1024 locales = strings.Split(string(output), "\n")
1025 } else {
1026 // If we're unable to list the locales, let's assume en_US.UTF-8
1027 locales = []string{"en_US.UTF-8"}
1028 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
1029 }
1030
1031 // gettext uses LANGUAGE, which is passed directly through
1032
1033 // For LANG and LC_*, only preserve the evaluated version of
1034 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001035 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -08001036 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001037 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -08001038 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001039 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -08001040 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001041 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -08001042 }
1043
1044 c.environ.UnsetWithPrefix("LC_")
1045
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001046 if userLang != "" {
1047 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -08001048 }
1049
1050 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
1051 // for others)
1052 if inList("C.UTF-8", locales) {
1053 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -05001054 } else if inList("C.utf8", locales) {
1055 // These normalize to the same thing
1056 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -08001057 } else if inList("en_US.UTF-8", locales) {
1058 c.environ.Set("LANG", "en_US.UTF-8")
1059 } else if inList("en_US.utf8", locales) {
1060 // These normalize to the same thing
1061 c.environ.Set("LANG", "en_US.UTF-8")
1062 } else {
1063 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
1064 }
1065}
1066
Dan Willemsen1e704462016-08-21 15:17:17 -07001067func (c *configImpl) Environment() *Environment {
1068 return c.environ
1069}
1070
1071func (c *configImpl) Arguments() []string {
1072 return c.arguments
1073}
1074
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001075func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001076 if len(c.Arguments()) > 0 {
1077 // Explicit targets requested that are not special targets like b2pbuild
1078 // or the JSON module graph
1079 return true
1080 }
1081
Colin Cross8d411ff2023-12-07 10:31:24 -08001082 if !c.JsonModuleGraph() && !c.Queryview() && !c.SoongDocs() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001083 // Command line was empty, the default Ninja target is built
1084 return true
1085 }
1086
Colin Cross8d411ff2023-12-07 10:31:24 -08001087 if c.Dist() {
Liz Kammer88677422021-12-15 15:03:19 -05001088 return true
1089 }
1090
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001091 // build.ninja doesn't need to be generated
1092 return false
1093}
1094
Dan Willemsen1e704462016-08-21 15:17:17 -07001095func (c *configImpl) OutDir() string {
1096 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -07001097 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -07001098 }
1099 return "out"
1100}
1101
Dan Willemsen8a073a82017-02-04 17:30:44 -08001102func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -04001103 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001104}
1105
1106func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -07001107 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -08001108}
1109
Dan Willemsen1e704462016-08-21 15:17:17 -07001110func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001111 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001112 return c.arguments
1113 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001114 return c.ninjaArgs
1115}
1116
1117func (c *configImpl) SoongOutDir() string {
1118 return filepath.Join(c.OutDir(), "soong")
1119}
1120
Spandan Das394aa322022-11-03 17:02:10 +00001121func (c *configImpl) ApiSurfacesOutDir() string {
1122 return filepath.Join(c.OutDir(), "api_surfaces")
1123}
1124
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001125func (c *configImpl) PrebuiltOS() string {
1126 switch runtime.GOOS {
1127 case "linux":
1128 return "linux-x86"
1129 case "darwin":
1130 return "darwin-x86"
1131 default:
1132 panic("Unknown GOOS")
1133 }
1134}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001135
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001136func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001137 if c.SkipKatiNinja() {
1138 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1139 } else {
1140 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1141 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001142}
1143
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001144func (c *configImpl) UsedEnvFile(tag string) string {
Kiyoung Kimeaa55a82023-06-05 16:56:49 +09001145 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
Qing Shen713c5422024-08-23 04:09:18 +00001146 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+v+c.CoverageSuffix()+"."+tag)
Kiyoung Kimeaa55a82023-06-05 16:56:49 +09001147 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001148 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1149}
1150
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001151func (c *configImpl) SoongDocsHtml() string {
1152 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1153}
1154
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001155func (c *configImpl) QueryviewMarkerFile() string {
1156 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1157}
1158
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001159func (c *configImpl) ModuleGraphFile() string {
1160 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1161}
1162
kgui67007242022-01-25 13:50:25 +08001163func (c *configImpl) ModuleActionsFile() string {
1164 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1165}
1166
Jeff Gastonefc1b412017-03-29 17:29:06 -07001167func (c *configImpl) TempDir() string {
1168 return shared.TempDirForOutDir(c.SoongOutDir())
1169}
1170
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001171func (c *configImpl) FileListDir() string {
1172 return filepath.Join(c.OutDir(), ".module_paths")
1173}
1174
Dan Willemsen1e704462016-08-21 15:17:17 -07001175func (c *configImpl) KatiSuffix() string {
1176 if c.katiSuffix != "" {
1177 return c.katiSuffix
1178 }
1179 panic("SetKatiSuffix has not been called")
1180}
1181
Colin Cross37193492017-11-16 17:55:00 -08001182// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1183// user is interested in additional checks at the expense of build time.
1184func (c *configImpl) Checkbuild() bool {
1185 return c.checkbuild
1186}
1187
Dan Willemsen8a073a82017-02-04 17:30:44 -08001188func (c *configImpl) Dist() bool {
1189 return c.dist
1190}
1191
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001192func (c *configImpl) JsonModuleGraph() bool {
1193 return c.jsonModuleGraph
1194}
1195
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001196func (c *configImpl) Queryview() bool {
1197 return c.queryview
1198}
1199
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001200func (c *configImpl) SoongDocs() bool {
1201 return c.soongDocs
1202}
1203
Dan Willemsen1e704462016-08-21 15:17:17 -07001204func (c *configImpl) IsVerbose() bool {
1205 return c.verbose
1206}
1207
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001208func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1209 return c.ninjaWeightListSource
1210}
1211
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001212func (c *configImpl) SkipKati() bool {
1213 return c.skipKati
1214}
1215
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001216func (c *configImpl) SkipKatiNinja() bool {
1217 return c.skipKatiNinja
1218}
1219
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001220func (c *configImpl) SkipSoong() bool {
1221 return c.skipSoong
1222}
1223
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001224func (c *configImpl) SkipNinja() bool {
1225 return c.skipNinja
1226}
1227
Anton Hansson5a7861a2021-06-04 10:09:01 +01001228func (c *configImpl) SetSkipNinja(v bool) {
1229 c.skipNinja = v
1230}
1231
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001232func (c *configImpl) SkipConfig() bool {
1233 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001234}
1235
Jihoon Kang1bff0342023-01-17 20:40:22 +00001236func (c *configImpl) BuildFromTextStub() bool {
Jihoon Kang2a929ad2023-06-08 19:02:07 +00001237 return !c.buildFromSourceStub
Jihoon Kang1bff0342023-01-17 20:40:22 +00001238}
1239
Dan Willemsen1e704462016-08-21 15:17:17 -07001240func (c *configImpl) TargetProduct() string {
1241 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1242 return v
1243 }
1244 panic("TARGET_PRODUCT is not defined")
1245}
1246
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001247func (c *configImpl) TargetProductOrErr() (string, error) {
1248 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1249 return v, nil
1250 }
1251 return "", fmt.Errorf("TARGET_PRODUCT is not defined")
1252}
1253
Qing Shen713c5422024-08-23 04:09:18 +00001254func (c *configImpl) CoverageSuffix() string {
1255 if v := c.environ.IsEnvTrue("EMMA_INSTRUMENT"); v {
1256 return ".coverage"
1257 }
1258 return ""
1259}
1260
Dan Willemsen02781d52017-05-12 19:28:13 -07001261func (c *configImpl) TargetDevice() string {
1262 return c.targetDevice
1263}
1264
1265func (c *configImpl) SetTargetDevice(device string) {
1266 c.targetDevice = device
1267}
1268
1269func (c *configImpl) TargetBuildVariant() string {
1270 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1271 return v
1272 }
1273 panic("TARGET_BUILD_VARIANT is not defined")
1274}
1275
Dan Willemsen1e704462016-08-21 15:17:17 -07001276func (c *configImpl) KatiArgs() []string {
1277 return c.katiArgs
1278}
1279
1280func (c *configImpl) Parallel() int {
1281 return c.parallel
1282}
1283
Sam Delmerico98a73292023-02-21 11:50:29 -05001284func (c *configImpl) GetSourceRootDirs() []string {
1285 return c.sourceRootDirs
1286}
1287
1288func (c *configImpl) SetSourceRootDirs(i []string) {
1289 c.sourceRootDirs = i
1290}
1291
MarkDacek6614d9c2022-12-07 21:57:38 +00001292func (c *configImpl) GetLogsPrefix() string {
1293 return c.logsPrefix
1294}
1295
1296func (c *configImpl) SetLogsPrefix(prefix string) {
1297 c.logsPrefix = prefix
1298}
1299
Colin Cross8b8bec32019-11-15 13:18:43 -08001300func (c *configImpl) HighmemParallel() int {
1301 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1302 return i
1303 }
1304
1305 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1306 parallel := c.Parallel()
1307 if c.UseRemoteBuild() {
1308 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1309 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1310 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1311 // Return 1/16th of the size of the local pool, rounding up.
1312 return (parallel + 15) / 16
1313 } else if c.totalRAM == 0 {
1314 // Couldn't detect the total RAM, don't restrict highmem processes.
1315 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001316 } else if c.totalRAM <= 16*1024*1024*1024 {
1317 // Less than 16GB of ram, restrict to 1 highmem processes
1318 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001319 } else if c.totalRAM <= 32*1024*1024*1024 {
1320 // Less than 32GB of ram, restrict to 2 highmem processes
1321 return 2
1322 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1323 // If less than 8GB total RAM per process, reduce the number of highmem processes
1324 return p
1325 }
1326 // No restriction on highmem processes
1327 return parallel
1328}
1329
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001330func (c *configImpl) TotalRAM() uint64 {
1331 return c.totalRAM
1332}
1333
Kousik Kumarec478642020-09-21 13:39:24 -04001334// ForceUseGoma determines whether we should override Goma deprecation
1335// and use Goma for the current build or not.
1336func (c *configImpl) ForceUseGoma() bool {
1337 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1338 v = strings.TrimSpace(v)
1339 if v != "" && v != "false" {
1340 return true
1341 }
1342 }
1343 return false
1344}
1345
Dan Willemsen1e704462016-08-21 15:17:17 -07001346func (c *configImpl) UseGoma() bool {
1347 if v, ok := c.environ.Get("USE_GOMA"); ok {
1348 v = strings.TrimSpace(v)
1349 if v != "" && v != "false" {
1350 return true
1351 }
1352 }
1353 return false
1354}
1355
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001356func (c *configImpl) StartGoma() bool {
1357 if !c.UseGoma() {
1358 return false
1359 }
1360
1361 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1362 v = strings.TrimSpace(v)
1363 if v != "" && v != "false" {
1364 return false
1365 }
1366 }
1367 return true
1368}
1369
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001370func (c *configImpl) canSupportRBE() bool {
Joe Onorato86f50e72024-06-24 14:28:25 -07001371 // Only supported on linux
1372 if runtime.GOOS != "linux" {
1373 return false
1374 }
1375
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001376 // Do not use RBE with prod credentials in scenarios when stubby doesn't exist, since
1377 // its unlikely that we will be able to obtain necessary creds without stubby.
1378 authType, _ := c.rbeAuth()
1379 if !c.StubbyExists() && strings.Contains(authType, "use_google_prod_creds") {
1380 return false
1381 }
Taylor Santiago3c16e612024-05-30 14:41:31 -07001382 if c.UseABFS() {
1383 return false
1384 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001385 return true
1386}
1387
Taylor Santiago3c16e612024-05-30 14:41:31 -07001388func (c *configImpl) UseABFS() bool {
1389 if v, ok := c.environ.Get("NO_ABFS"); ok {
1390 v = strings.ToLower(strings.TrimSpace(v))
1391 if v == "true" || v == "1" {
1392 return false
1393 }
1394 }
1395
1396 abfsBox := c.PrebuiltBuildTool("abfsbox")
1397 err := exec.Command(abfsBox, "hash", srcDirFileCheck).Run()
1398 return err == nil
1399}
1400
Taylor Santiago8b0bed72024-09-03 13:30:22 -07001401func (c *configImpl) sandboxPath(base, in string) string {
1402 if !c.UseABFS() {
1403 return in
1404 }
1405
1406 rel, err := filepath.Rel(base, in)
1407 if err != nil {
1408 return in
1409 }
1410
1411 return filepath.Join(abfsSrcDir, rel)
1412}
1413
Ramy Medhatbbf25672019-07-17 12:30:04 +00001414func (c *configImpl) UseRBE() bool {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001415 // These alternate modes of running Soong do not use RBE / reclient.
Colin Cross8d411ff2023-12-07 10:31:24 -08001416 if c.Queryview() || c.JsonModuleGraph() {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001417 return false
1418 }
1419
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001420 if !c.canSupportRBE() {
Kousik Kumar67ad4342023-06-06 15:09:27 -04001421 return false
1422 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001423
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001424 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001425 v = strings.TrimSpace(v)
1426 if v != "" && v != "false" {
1427 return true
1428 }
1429 }
1430 return false
1431}
1432
1433func (c *configImpl) StartRBE() bool {
1434 if !c.UseRBE() {
1435 return false
1436 }
1437
1438 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1439 v = strings.TrimSpace(v)
1440 if v != "" && v != "false" {
1441 return false
1442 }
1443 }
1444 return true
1445}
1446
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001447func (c *configImpl) rbeProxyLogsDir() string {
1448 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001449 if v, ok := c.environ.Get(f); ok {
1450 return v
1451 }
1452 }
Ramy Medhatbc061762023-10-10 18:36:59 +00001453 return c.rbeTmpDir()
1454}
1455
1456func (c *configImpl) rbeDownloadTmpDir() string {
Cole Faust06ea5312023-10-18 17:38:40 -07001457 for _, f := range []string{"RBE_download_tmp_dir", "FLAG_download_tmp_dir"} {
Ramy Medhatbc061762023-10-10 18:36:59 +00001458 if v, ok := c.environ.Get(f); ok {
1459 return v
1460 }
1461 }
1462 return c.rbeTmpDir()
1463}
1464
1465func (c *configImpl) rbeTmpDir() string {
Yaowen Meid4da2662024-07-24 08:25:12 +00001466 return filepath.Join(c.SoongOutDir(), "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001467}
1468
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001469func (c *configImpl) rbeCacheDir() string {
1470 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1471 if v, ok := c.environ.Get(f); ok {
1472 return v
1473 }
1474 }
1475 return shared.JoinPath(c.SoongOutDir(), "rbe")
1476}
1477
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001478func (c *configImpl) shouldCleanupRBELogsDir() bool {
1479 // Perform a log directory cleanup only when the log directory
1480 // is auto created by the build rather than user-specified.
1481 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Yaowen Meid9108d22024-08-29 16:56:32 +00001482 if v, ok := c.environ.Get(f); ok {
1483 if v != c.rbeTmpDir() {
1484 return false
1485 }
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001486 }
1487 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001488 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001489}
1490
1491func (c *configImpl) rbeExecRoot() string {
1492 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1493 if v, ok := c.environ.Get(f); ok {
1494 return v
1495 }
1496 }
1497 wd, err := os.Getwd()
1498 if err != nil {
1499 return ""
1500 }
1501 return wd
1502}
1503
1504func (c *configImpl) rbeDir() string {
1505 if v, ok := c.environ.Get("RBE_DIR"); ok {
1506 return v
1507 }
1508 return "prebuilts/remoteexecution-client/live/"
1509}
1510
1511func (c *configImpl) rbeReproxy() string {
1512 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1513 if v, ok := c.environ.Get(f); ok {
1514 return v
1515 }
1516 }
1517 return filepath.Join(c.rbeDir(), "reproxy")
1518}
1519
1520func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001521 credFlags := []string{
1522 "use_application_default_credentials",
1523 "use_gce_credentials",
1524 "credential_file",
1525 "use_google_prod_creds",
1526 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001527 for _, cf := range credFlags {
1528 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1529 if v, ok := c.environ.Get(f); ok {
1530 v = strings.TrimSpace(v)
1531 if v != "" && v != "false" && v != "0" {
1532 return "RBE_" + cf, v
1533 }
1534 }
1535 }
1536 }
1537 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001538}
1539
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001540func (c *configImpl) rbeSockAddr(dir string) (string, error) {
Andus Yuc917eb82024-03-06 21:54:15 +00001541 // Absolute path socket addresses have a prefix of //. This should
1542 // be included in the length limit.
1543 maxNameLen := len(syscall.RawSockaddrUnix{}.Path) - 2
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001544 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1545
1546 name := filepath.Join(dir, base)
1547 if len(name) < maxNameLen {
1548 return name, nil
1549 }
1550
1551 name = filepath.Join("/tmp", base)
1552 if len(name) < maxNameLen {
1553 return name, nil
1554 }
1555
1556 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1557}
1558
Kousik Kumar7bc78192022-04-27 14:52:56 -04001559// IsGooglerEnvironment returns true if the current build is running
1560// on a Google developer machine and false otherwise.
1561func (c *configImpl) IsGooglerEnvironment() bool {
1562 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1563 if v, ok := c.environ.Get(cf); ok {
1564 return v == "googler"
1565 }
1566 return false
1567}
1568
1569// GoogleProdCredsExist determine whether credentials exist on the
1570// Googler machine to use remote execution.
1571func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001572 if googleProdCredsExistCache {
1573 return googleProdCredsExistCache
1574 }
andusyu0b3dc032023-06-21 17:29:32 -04001575 if _, err := exec.Command("/usr/bin/gcertstatus", "-nocheck_ssh").Output(); err != nil {
Kousik Kumar7bc78192022-04-27 14:52:56 -04001576 return false
1577 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001578 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001579 return true
1580}
1581
1582// UseRemoteBuild indicates whether to use a remote build acceleration system
1583// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001584func (c *configImpl) UseRemoteBuild() bool {
1585 return c.UseGoma() || c.UseRBE()
1586}
1587
Kousik Kumar7bc78192022-04-27 14:52:56 -04001588// StubbyExists checks whether the stubby binary exists on the machine running
1589// the build.
1590func (c *configImpl) StubbyExists() bool {
1591 if _, err := exec.LookPath("stubby"); err != nil {
1592 return false
1593 }
1594 return true
1595}
1596
Dan Willemsen1e704462016-08-21 15:17:17 -07001597// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001598// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001599// still limited by Parallel()
1600func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001601 if !c.UseRemoteBuild() {
1602 return 0
1603 }
1604 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1605 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001606 }
1607 return 500
1608}
1609
1610func (c *configImpl) SetKatiArgs(args []string) {
1611 c.katiArgs = args
1612}
1613
1614func (c *configImpl) SetNinjaArgs(args []string) {
1615 c.ninjaArgs = args
1616}
1617
1618func (c *configImpl) SetKatiSuffix(suffix string) {
1619 c.katiSuffix = suffix
1620}
1621
Dan Willemsene0879fc2017-08-04 15:06:27 -07001622func (c *configImpl) LastKatiSuffixFile() string {
1623 return filepath.Join(c.OutDir(), "last_kati_suffix")
1624}
1625
1626func (c *configImpl) HasKatiSuffix() bool {
1627 return c.katiSuffix != ""
1628}
1629
Dan Willemsen1e704462016-08-21 15:17:17 -07001630func (c *configImpl) KatiEnvFile() string {
1631 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1632}
1633
Dan Willemsen29971232018-09-26 14:58:30 -07001634func (c *configImpl) KatiBuildNinjaFile() string {
1635 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001636}
1637
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001638func (c *configImpl) KatiPackageNinjaFile() string {
1639 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1640}
1641
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001642func (c *configImpl) SoongVarsFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001643 targetProduct, err := c.TargetProductOrErr()
1644 if err != nil {
1645 return filepath.Join(c.SoongOutDir(), "soong.variables")
1646 } else {
Qing Shen713c5422024-08-23 04:09:18 +00001647 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+c.CoverageSuffix()+".variables")
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001648 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001649}
1650
Inseob Kim58c802f2024-06-11 10:59:00 +09001651func (c *configImpl) SoongExtraVarsFile() string {
1652 targetProduct, err := c.TargetProductOrErr()
1653 if err != nil {
1654 return filepath.Join(c.SoongOutDir(), "soong.extra.variables")
1655 } else {
Qing Shen713c5422024-08-23 04:09:18 +00001656 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+c.CoverageSuffix()+".extra.variables")
Inseob Kim58c802f2024-06-11 10:59:00 +09001657 }
1658}
1659
Dan Willemsen1e704462016-08-21 15:17:17 -07001660func (c *configImpl) SoongNinjaFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001661 targetProduct, err := c.TargetProductOrErr()
1662 if err != nil {
1663 return filepath.Join(c.SoongOutDir(), "build.ninja")
1664 } else {
Qing Shen713c5422024-08-23 04:09:18 +00001665 return filepath.Join(c.SoongOutDir(), "build."+targetProduct+c.CoverageSuffix()+".ninja")
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001666 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001667}
1668
1669func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001670 if c.katiSuffix == "" {
1671 return filepath.Join(c.OutDir(), "combined.ninja")
1672 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001673 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1674}
1675
1676func (c *configImpl) SoongAndroidMk() string {
Qing Shen713c5422024-08-23 04:09:18 +00001677 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+c.CoverageSuffix()+".mk")
Dan Willemsen1e704462016-08-21 15:17:17 -07001678}
1679
1680func (c *configImpl) SoongMakeVarsMk() string {
Qing Shen713c5422024-08-23 04:09:18 +00001681 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+c.CoverageSuffix()+".mk")
Dan Willemsen1e704462016-08-21 15:17:17 -07001682}
1683
Colin Crossaa9a2732023-10-27 10:54:27 -07001684func (c *configImpl) SoongBuildMetrics() string {
Colin Crossb67b0612023-10-31 10:02:45 -07001685 return filepath.Join(c.LogsDir(), "soong_build_metrics.pb")
Colin Crossaa9a2732023-10-27 10:54:27 -07001686}
1687
Dan Willemsenf052f782017-05-18 15:29:04 -07001688func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001689 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001690}
1691
Dan Willemsen02781d52017-05-12 19:28:13 -07001692func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001693 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1694}
1695
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001696func (c *configImpl) KatiPackageMkDir() string {
1697 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1698}
1699
Dan Willemsenf052f782017-05-18 15:29:04 -07001700func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001701 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001702}
1703
1704func (c *configImpl) HostOut() string {
1705 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1706}
1707
1708// This probably needs to be multi-valued, so not exporting it for now
1709func (c *configImpl) hostCrossOut() string {
1710 if runtime.GOOS == "linux" {
1711 return filepath.Join(c.hostOutRoot(), "windows-x86")
1712 } else {
1713 return ""
1714 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001715}
1716
Dan Willemsen1e704462016-08-21 15:17:17 -07001717func (c *configImpl) HostPrebuiltTag() string {
1718 if runtime.GOOS == "linux" {
1719 return "linux-x86"
1720 } else if runtime.GOOS == "darwin" {
1721 return "darwin-x86"
1722 } else {
1723 panic("Unsupported OS")
1724 }
1725}
Dan Willemsenf173d592017-04-27 14:28:00 -07001726
Taylor Santiago3c16e612024-05-30 14:41:31 -07001727func (c *configImpl) KatiBin() string {
1728 binName := "ckati"
1729 if c.UseABFS() {
1730 binName = "ckati-wrap"
1731 }
1732
1733 return c.PrebuiltBuildTool(binName)
1734}
1735
1736func (c *configImpl) NinjaBin() string {
1737 binName := "ninja"
1738 if c.UseABFS() {
1739 binName = "ninjago"
1740 }
1741 return c.PrebuiltBuildTool(binName)
1742}
1743
Cole Faust4e58bba2024-08-22 14:27:03 -07001744func (c *configImpl) N2Bin() string {
1745 path := c.PrebuiltBuildTool("n2")
1746 // Use musl instead of glibc because glibc on the build server is old and has bugs
1747 return strings.ReplaceAll(path, "/linux-x86/", "/linux_musl-x86/")
1748}
1749
LaMont Jonesece626c2024-09-03 11:19:31 -07001750func (c *configImpl) SisoBin() string {
1751 path := c.PrebuiltBuildTool("siso")
1752 // Use musl instead of glibc because glibc on the build server is old and has bugs
1753 return strings.ReplaceAll(path, "/linux-x86/", "/linux_musl-x86/")
1754}
1755
Dan Willemsen8122bd52017-10-12 20:20:41 -07001756func (c *configImpl) PrebuiltBuildTool(name string) string {
Colin Cross7077be42024-10-04 20:37:16 +00001757 if c.environ.IsEnvTrue("SANITIZE_BUILD_TOOL_PREBUILTS") {
1758 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1759 if _, err := os.Stat(asan); err == nil {
1760 return asan
Dan Willemsenf173d592017-04-27 14:28:00 -07001761 }
1762 }
1763 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1764}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001765
1766func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1767 c.brokenDupRules = val
1768}
1769
1770func (c *configImpl) BuildBrokenDupRules() bool {
1771 return c.brokenDupRules
1772}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001773
Dan Willemsen25e6f092019-04-09 10:22:43 -07001774func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1775 c.brokenUsesNetwork = val
1776}
1777
1778func (c *configImpl) BuildBrokenUsesNetwork() bool {
1779 return c.brokenUsesNetwork
1780}
1781
Dan Willemsene3336352020-01-02 19:10:38 -08001782func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1783 c.brokenNinjaEnvVars = val
1784}
1785
1786func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1787 return c.brokenNinjaEnvVars
1788}
1789
Spandan Das28a6f192024-07-01 21:00:25 +00001790func (c *configImpl) SetBuildBrokenMissingOutputs(val bool) {
1791 c.brokenMissingOutputs = val
1792}
1793
1794func (c *configImpl) BuildBrokenMissingOutputs() bool {
1795 return c.brokenMissingOutputs
1796}
1797
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001798func (c *configImpl) SetTargetDeviceDir(dir string) {
1799 c.targetDeviceDir = dir
1800}
1801
1802func (c *configImpl) TargetDeviceDir() string {
1803 return c.targetDeviceDir
1804}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001805
Patrice Arruda219eef32020-06-01 17:29:30 +00001806func (c *configImpl) BuildDateTime() string {
1807 return c.buildDateTime
1808}
1809
1810func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001811 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001812}
Patrice Arruda83842d72020-12-08 19:42:08 +00001813
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001814// LogsDir returns the absolute path to the logs directory where build log and
1815// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001816// directory. If the argument dist is specified, the logs directory
1817// is <dist_dir>/logs.
1818func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001819 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001820 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001821 // 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 -05001822 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001823 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001824 absDir, err := filepath.Abs(dir)
1825 if err != nil {
1826 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1827 os.Exit(1)
1828 }
1829 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001830}
1831
Chris Parsons53f68ae2022-03-03 12:01:40 -05001832// MkFileMetrics returns the file path for make-related metrics.
1833func (c *configImpl) MkMetrics() string {
1834 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1835}
1836
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001837func (c *configImpl) SetEmptyNinjaFile(v bool) {
1838 c.emptyNinjaFile = v
1839}
1840
1841func (c *configImpl) EmptyNinjaFile() bool {
1842 return c.emptyNinjaFile
1843}
Yu Liu6e13b402021-07-27 14:29:06 -07001844
MarkDacekd0e7cd32022-12-02 22:22:40 +00001845func (c *configImpl) SkipMetricsUpload() bool {
Taylor Santiago8b0bed72024-09-03 13:30:22 -07001846 // b/362625275 - Metrics upload sometimes prevents abfs unmount
1847 if c.UseABFS() {
1848 return true
1849 }
1850
MarkDacekd0e7cd32022-12-02 22:22:40 +00001851 return c.skipMetricsUpload
1852}
1853
MarkDacekf47e1422023-04-19 16:47:36 +00001854func (c *configImpl) EnsureAllowlistIntegrity() bool {
1855 return c.ensureAllowlistIntegrity
1856}
1857
LaMont Jones523db942024-10-01 15:32:39 -07001858func (c *configImpl) PartialCompileFlags() partialCompileFlags {
1859 return c.partialCompileFlags
1860}
1861
MarkDacek6614d9c2022-12-07 21:57:38 +00001862// Returns a Time object if one was passed via a command-line flag.
1863// Otherwise returns the passed default.
1864func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1865 if c.buildStartedTime == 0 {
1866 return defaultTime
1867 }
1868 return time.UnixMilli(c.buildStartedTime)
1869}
1870
Yu Liu6e13b402021-07-27 14:29:06 -07001871func GetMetricsUploader(topDir string, env *Environment) string {
1872 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1873 metricsUploader := filepath.Join(topDir, p)
1874 if _, err := os.Stat(metricsUploader); err == nil {
1875 return metricsUploader
1876 }
1877 }
1878
1879 return ""
1880}