blob: 5085c6845ecfa0316bb6c44cfa708dc969fff9f3 [file] [log] [blame]
Dan Willemsen1e704462016-08-21 15:17:17 -07001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package build
16
17import (
Kousik Kumar3ff037e2022-01-25 22:11:01 -050018 "encoding/json"
Jeongik Chaa87506f2023-06-01 23:16:41 +090019 "errors"
Ramy Medhat0fc67eb2020-08-12 01:26:23 -040020 "fmt"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050021 "io/ioutil"
Kousik Kumar4c180ad2022-05-27 07:48:37 -040022 "math/rand"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080023 "os"
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050024 "os/exec"
Cole Faust583dfb42023-09-28 13:56:30 -070025 "os/user"
Dan Willemsen1e704462016-08-21 15:17:17 -070026 "path/filepath"
27 "runtime"
28 "strconv"
29 "strings"
Kousik Kumar4c180ad2022-05-27 07:48:37 -040030 "syscall"
Nan Zhang2e6a4ff2018-02-14 13:27:26 -080031 "time"
Jeff Gastonefc1b412017-03-29 17:29:06 -070032
33 "android/soong/shared"
LaMont Jones9a912862023-11-06 22:11:08 +000034 "android/soong/ui/metrics"
Kousik Kumarec478642020-09-21 13:39:24 -040035
Dan Willemsen4591b642021-05-24 14:24:12 -070036 "google.golang.org/protobuf/proto"
Patrice Arruda96850362020-08-11 20:41:11 +000037
38 smpb "android/soong/ui/metrics/metrics_proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070039)
40
Kousik Kumar3ff037e2022-01-25 22:11:01 -050041const (
Chris Parsons53f68ae2022-03-03 12:01:40 -050042 envConfigDir = "vendor/google/tools/soong_config"
43 jsonSuffix = "json"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050044)
45
Kousik Kumar4c180ad2022-05-27 07:48:37 -040046var (
Kevin Dagostino096ab2f2023-03-03 19:47:17 +000047 rbeRandPrefix int
48 googleProdCredsExistCache bool
Kousik Kumar4c180ad2022-05-27 07:48:37 -040049)
50
51func init() {
52 rand.Seed(time.Now().UnixNano())
53 rbeRandPrefix = rand.Intn(1000)
54}
55
Dan Willemsen1e704462016-08-21 15:17:17 -070056type Config struct{ *configImpl }
57
58type configImpl struct {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020059 // Some targets that are implemented in soong_build
60 // (bp2build, json-module-graph) are not here and have their own bits below.
Colin Cross28f527c2019-11-26 16:19:04 -080061 arguments []string
62 goma bool
63 environ *Environment
64 distDir string
65 buildDateTime string
MarkDacek6614d9c2022-12-07 21:57:38 +000066 logsPrefix string
Dan Willemsen1e704462016-08-21 15:17:17 -070067
68 // From the arguments
MarkDacekf47e1422023-04-19 16:47:36 +000069 parallel int
70 keepGoing int
71 verbose bool
72 checkbuild bool
73 dist bool
74 jsonModuleGraph bool
MarkDacekf47e1422023-04-19 16:47:36 +000075 queryview bool
76 reportMkMetrics bool // Collect and report mk2bp migration progress metrics.
77 soongDocs bool
78 multitreeBuild bool // This is a multitree build.
79 skipConfig bool
80 skipKati bool
81 skipKatiNinja bool
82 skipSoong bool
83 skipNinja bool
84 skipSoongTests bool
85 searchApiDir bool // Scan the Android.bp files generated in out/api_surfaces
86 skipMetricsUpload bool
87 buildStartedTime int64 // For metrics-upload-only - manually specify a build-started time
Jihoon Kang2a929ad2023-06-08 19:02:07 +000088 buildFromSourceStub bool
Colin Cross8d411ff2023-12-07 10:31:24 -080089 ensureAllowlistIntegrity bool // For CI builds - make sure modules are mixed-built
Dan Willemsen1e704462016-08-21 15:17:17 -070090
91 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070092 katiArgs []string
93 ninjaArgs []string
94 katiSuffix string
95 targetDevice string
96 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +000097 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -070098
Dan Willemsen2bb82d02019-12-27 09:35:42 -080099 // Autodetected
100 totalRAM uint64
101
Dan Willemsene3336352020-01-02 19:10:38 -0800102 brokenDupRules bool
103 brokenUsesNetwork bool
104 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -0700105
106 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000107
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700108 // Set by multiproduct_kati
109 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700110
111 metricsUploader string
MarkDacekd06db5d2022-11-29 00:47:59 +0000112
Sam Delmerico98a73292023-02-21 11:50:29 -0500113 includeTags []string
114 sourceRootDirs []string
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900115
116 // Data source to write ninja weight list
117 ninjaWeightListSource NinjaWeightListSource
Dan Willemsen1e704462016-08-21 15:17:17 -0700118}
119
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900120type NinjaWeightListSource uint
121
122const (
123 // ninja doesn't use weight list.
124 NOT_USED NinjaWeightListSource = iota
125 // ninja uses weight list based on previous builds by ninja log
126 NINJA_LOG
127 // ninja thinks every task has the same weight.
128 EVENLY_DISTRIBUTED
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900129 // ninja uses an external custom weight list
130 EXTERNAL_FILE
Jeongik Chae114e602023-03-19 00:12:39 +0900131 // ninja uses a prioritized module list from Soong
132 HINT_FROM_SOONG
Jeongik Chaa87506f2023-06-01 23:16:41 +0900133 // If ninja log exists, use NINJA_LOG, if not, use HINT_FROM_SOONG instead.
134 // We can assume it is an incremental build if ninja log exists.
135 DEFAULT
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900136)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800137const srcDirFileCheck = "build/soong/root.bp"
138
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700139var buildFiles = []string{"Android.mk", "Android.bp"}
140
Patrice Arruda13848222019-04-22 17:12:02 -0700141type BuildAction uint
142
143const (
144 // Builds all of the modules and their dependencies of a specified directory, relative to the root
145 // directory of the source tree.
146 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
147
148 // Builds all of the modules and their dependencies of a list of specified directories. All specified
149 // directories are relative to the root directory of the source tree.
150 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700151
152 // Build a list of specified modules. If none was specified, simply build the whole source tree.
153 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700154)
155
156// checkTopDir validates that the current directory is at the root directory of the source tree.
157func checkTopDir(ctx Context) {
158 if _, err := os.Stat(srcDirFileCheck); err != nil {
159 if os.IsNotExist(err) {
160 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
161 }
162 ctx.Fatalln("Error verifying tree state:", err)
163 }
164}
165
MarkDacek7901e582023-01-09 19:48:01 +0000166func loadEnvConfig(ctx Context, config *configImpl, bc string) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500167 if bc == "" {
168 return nil
169 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500170
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500171 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500172 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500173 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500174 envConfigDir,
175 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500176 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500177 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
178 envVarsJSON, err := ioutil.ReadFile(cfgFile)
179 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500180 continue
181 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500182 ctx.Verbosef("Loading config file %v\n", cfgFile)
183 var envVars map[string]map[string]string
184 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
185 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
186 continue
187 }
188 for k, v := range envVars["env"] {
189 if os.Getenv(k) != "" {
190 continue
191 }
192 config.environ.Set(k, v)
193 }
194 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
195 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500196 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500197
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500198 return nil
199}
200
Dan Willemsen1e704462016-08-21 15:17:17 -0700201func NewConfig(ctx Context, args ...string) Config {
202 ret := &configImpl{
Jeongik Chaf2ecf762023-05-19 14:03:45 +0900203 environ: OsEnvironment(),
204 sandboxConfig: &SandboxConfig{},
Jeongik Chaa87506f2023-06-01 23:16:41 +0900205 ninjaWeightListSource: DEFAULT,
Dan Willemsen1e704462016-08-21 15:17:17 -0700206 }
207
Colin Cross106d6ef2023-10-24 10:34:56 -0700208 // Skip soong tests by default on Linux
209 if runtime.GOOS == "linux" {
210 ret.skipSoongTests = true
211 }
212
Patrice Arruda90109172020-07-28 18:07:27 +0000213 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700214 ret.parallel = runtime.NumCPU() + 2
215 ret.keepGoing = 1
216
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800217 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700218 ret.parseArgs(ctx, args)
Jeongik Chae114e602023-03-19 00:12:39 +0900219
220 if ret.ninjaWeightListSource == HINT_FROM_SOONG {
Jeongik Chaa87506f2023-06-01 23:16:41 +0900221 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "always")
222 } else if ret.ninjaWeightListSource == DEFAULT {
223 defaultNinjaWeightListSource := NINJA_LOG
224 if _, err := os.Stat(filepath.Join(ret.OutDir(), ninjaLogFileName)); errors.Is(err, os.ErrNotExist) {
225 ctx.Verboseln("$OUT/.ninja_log doesn't exist, use HINT_FROM_SOONG instead")
226 defaultNinjaWeightListSource = HINT_FROM_SOONG
227 } else {
228 ctx.Verboseln("$OUT/.ninja_log exist, use NINJA_LOG")
229 }
230 ret.ninjaWeightListSource = defaultNinjaWeightListSource
231 // soong_build generates ninja hint depending on ninja log existence.
232 // Set it "depend" to avoid soong re-run due to env variable change.
233 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "depend")
Jeongik Chae114e602023-03-19 00:12:39 +0900234 }
Jeongik Chaa87506f2023-06-01 23:16:41 +0900235
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800236 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700237 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
238 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
239 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800240 outDir := "out"
241 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
242 if wd, err := os.Getwd(); err != nil {
243 ctx.Fatalln("Failed to get working directory:", err)
244 } else {
245 outDir = filepath.Join(baseDir, filepath.Base(wd))
246 }
247 }
248 ret.environ.Set("OUT_DIR", outDir)
249 }
250
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500251 // loadEnvConfig needs to know what the OUT_DIR is, so it should
252 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000253 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
254
255 if bc != "" {
Kousik Kumarc8818332023-01-16 16:33:05 +0000256 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000257 ctx.Fatalln("Failed to parse env config files: %v", err)
258 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +0000259 if !ret.canSupportRBE() {
260 // Explicitly set USE_RBE env variable to false when we cannot run
261 // an RBE build to avoid ninja local execution pool issues.
262 ret.environ.Set("USE_RBE", "false")
263 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500264 }
265
Dan Willemsen2d31a442018-10-20 21:33:41 -0700266 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
267 ret.distDir = filepath.Clean(distDir)
268 } else {
269 ret.distDir = filepath.Join(ret.OutDir(), "dist")
270 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700271
Spandan Das05063612021-06-25 01:39:04 +0000272 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
273 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
274 }
275
Dan Willemsen1e704462016-08-21 15:17:17 -0700276 ret.environ.Unset(
277 // We're already using it
278 "USE_SOONG_UI",
279
280 // We should never use GOROOT/GOPATH from the shell environment
281 "GOROOT",
282 "GOPATH",
283
284 // These should only come from Soong, not the environment.
285 "CLANG",
286 "CLANG_CXX",
287 "CCC_CC",
288 "CCC_CXX",
289
290 // Used by the goma compiler wrapper, but should only be set by
291 // gomacc
292 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800293
294 // We handle this above
295 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700296
Dan Willemsen2d31a442018-10-20 21:33:41 -0700297 // This is handled above too, and set for individual commands later
298 "DIST_DIR",
299
Dan Willemsen68a09852017-04-18 13:56:57 -0700300 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000301 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700302 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700303 "DISPLAY",
304 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000305 "JAVAC",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700306 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700307 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700308
309 // Drop make flags
310 "MAKEFLAGS",
311 "MAKELEVEL",
312 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700313
314 // Set in envsetup.sh, reset in makefiles
315 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700316
317 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
318 "ANDROID_BUILD_TOP",
319 "ANDROID_HOST_OUT",
320 "ANDROID_PRODUCT_OUT",
321 "ANDROID_HOST_OUT_TESTCASES",
322 "ANDROID_TARGET_OUT_TESTCASES",
323 "ANDROID_TOOLCHAIN",
324 "ANDROID_TOOLCHAIN_2ND_ARCH",
325 "ANDROID_DEV_SCRIPTS",
326 "ANDROID_EMULATOR_PREBUILTS",
327 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700328 )
329
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400330 if ret.UseGoma() || ret.ForceUseGoma() {
331 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
332 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400333 }
334
Dan Willemsen1e704462016-08-21 15:17:17 -0700335 // Tell python not to spam the source tree with .pyc files.
336 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
337
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400338 tmpDir := absPath(ctx, ret.TempDir())
339 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800340
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700341 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
342 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
343 "llvm-binutils-stable/llvm-symbolizer")
344 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
345
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800346 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700347 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800348
Yu Liu6e13b402021-07-27 14:29:06 -0700349 srcDir := absPath(ctx, ".")
350 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700351 ctx.Println("You are building in a directory whose absolute path contains a space character:")
352 ctx.Println()
353 ctx.Printf("%q\n", srcDir)
354 ctx.Println()
355 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700356 }
357
Yu Liu6e13b402021-07-27 14:29:06 -0700358 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
359
Dan Willemsendb8457c2017-05-12 16:38:17 -0700360 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700361 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
362 ctx.Println()
363 ctx.Printf("%q\n", outDir)
364 ctx.Println()
365 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700366 }
367
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000368 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700369 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
370 ctx.Println()
371 ctx.Printf("%q\n", distDir)
372 ctx.Println()
373 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700374 }
375
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700376 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000377 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800378 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Sorin Basca0760c892023-11-29 19:13:55 +0000379 java21Home := filepath.Join("prebuilts/jdk/jdk21", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700380 javaHome := func() string {
381 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
382 return override
383 }
Sorin Basca0760c892023-11-29 19:13:55 +0000384 if ret.environ.IsEnvTrue("EXPERIMENTAL_USE_OPENJDK21_TOOLCHAIN") {
385 return java21Home
386 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000387 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
388 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN is no longer supported. An OpenJDK 11 toolchain is now the global default.")
Pete Gillin1f52e932019-10-09 17:10:08 +0100389 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000390 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
391 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
392 }
393 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700394 }()
395 absJavaHome := absPath(ctx, javaHome)
396
Dan Willemsened869522018-01-08 14:58:46 -0800397 ret.configureLocale(ctx)
398
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700399 newPath := []string{filepath.Join(absJavaHome, "bin")}
400 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
401 newPath = append(newPath, path)
402 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100403
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700404 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
405 ret.environ.Set("JAVA_HOME", absJavaHome)
406 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000407 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700408 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
409
Colin Crossfe5ed4d2023-07-28 09:27:23 -0700410 // b/286885495, https://bugzilla.redhat.com/show_bug.cgi?id=2227130: some versions of Fedora include patches
411 // to unzip to enable zipbomb detection that incorrectly handle zip64 and data descriptors and fail on large
412 // zip files produced by soong_zip. Disable zipbomb detection.
413 ret.environ.Set("UNZIP_DISABLE_ZIPBOMB_DETECTION", "TRUE")
414
LaMont Jones52a72432023-03-09 18:19:35 +0000415 if ret.MultitreeBuild() {
416 ret.environ.Set("MULTITREE_BUILD", "true")
417 }
418
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800419 outDir := ret.OutDir()
420 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800421 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800422 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800423 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800424 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800425 }
Colin Cross28f527c2019-11-26 16:19:04 -0800426
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800427 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
428
Cole Faust583dfb42023-09-28 13:56:30 -0700429 if _, ok := ret.environ.Get("BUILD_USERNAME"); !ok {
430 username := "unknown"
431 if u, err := user.Current(); err == nil {
432 username = u.Username
433 } else {
434 ctx.Println("Failed to get current user:", err)
435 }
436 ret.environ.Set("BUILD_USERNAME", username)
437 }
438
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400439 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400440 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400441 ret.environ.Set(k, v)
442 }
443 }
444
Patrice Arruda96850362020-08-11 20:41:11 +0000445 c := Config{ret}
446 storeConfigMetrics(ctx, c)
447 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700448}
449
Patrice Arruda13848222019-04-22 17:12:02 -0700450// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
451// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700452func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
453 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700454}
455
LaMont Jones9a912862023-11-06 22:11:08 +0000456// Prepare for getting make variables. For them to be accurate, we need to have
457// obtained PRODUCT_RELEASE_CONFIG_MAPS.
458//
459// Returns:
460//
461// Whether config should be called again.
462//
463// TODO: when converting product config to a declarative language, make sure
464// that PRODUCT_RELEASE_CONFIG_MAPS is properly handled as a separate step in
465// that process.
466func SetProductReleaseConfigMaps(ctx Context, config Config) bool {
467 ctx.BeginTrace(metrics.RunKati, "SetProductReleaseConfigMaps")
468 defer ctx.EndTrace()
469
470 if config.SkipConfig() {
471 // This duplicates the logic from Build to skip product config
472 // if the user has explicitly said to.
473 return false
474 }
475
476 releaseConfigVars := []string{
477 "PRODUCT_RELEASE_CONFIG_MAPS",
478 }
479
480 origValue, _ := config.environ.Get("PRODUCT_RELEASE_CONFIG_MAPS")
481 // Get the PRODUCT_RELEASE_CONFIG_MAPS for this product, to avoid polluting the environment
482 // when we run product config to get the rest of the make vars.
483 releaseMapVars, err := dumpMakeVars(ctx, config, nil, releaseConfigVars, false, "")
484 if err != nil {
485 ctx.Fatalln("Error getting PRODUCT_RELEASE_CONFIG_MAPS:", err)
486 }
487 productReleaseConfigMaps := releaseMapVars["PRODUCT_RELEASE_CONFIG_MAPS"]
488 os.Setenv("PRODUCT_RELEASE_CONFIG_MAPS", productReleaseConfigMaps)
489 return origValue != productReleaseConfigMaps
490}
491
Patrice Arruda96850362020-08-11 20:41:11 +0000492// storeConfigMetrics selects a set of configuration information and store in
493// the metrics system for further analysis.
494func storeConfigMetrics(ctx Context, config Config) {
495 if ctx.Metrics == nil {
496 return
497 }
498
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400499 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000500
501 s := &smpb.SystemResourceInfo{
502 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
503 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
504 }
505 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000506}
507
Jeongik Cha8d63d562023-03-17 03:52:13 +0900508func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900509 switch s {
510 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900511 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900512 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900513 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900514 case EXTERNAL_FILE:
515 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900516 case HINT_FROM_SOONG:
517 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900518 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900519 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900520 }
521}
522
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400523func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700524 c := &smpb.BuildConfig{
Colin Cross8d411ff2023-12-07 10:31:24 -0800525 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
526 UseGoma: proto.Bool(config.UseGoma()),
527 UseRbe: proto.Bool(config.UseRBE()),
528 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400529 }
Yu Liue737a992021-10-04 13:21:41 -0700530 c.Targets = append(c.Targets, config.arguments...)
531
532 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400533}
534
Patrice Arruda13848222019-04-22 17:12:02 -0700535// getConfigArgs processes the command arguments based on the build action and creates a set of new
536// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700537func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700538 // The next block of code verifies that the current directory is the root directory of the source
539 // tree. It then finds the relative path of dir based on the root directory of the source tree
540 // and verify that dir is inside of the source tree.
541 checkTopDir(ctx)
542 topDir, err := os.Getwd()
543 if err != nil {
544 ctx.Fatalf("Error retrieving top directory: %v", err)
545 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700546 dir, err = filepath.EvalSymlinks(dir)
547 if err != nil {
548 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
549 }
Patrice Arruda13848222019-04-22 17:12:02 -0700550 dir, err = filepath.Abs(dir)
551 if err != nil {
552 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
553 }
554 relDir, err := filepath.Rel(topDir, dir)
555 if err != nil {
556 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
557 }
558 // If there are ".." in the path, it's not in the source tree.
559 if strings.Contains(relDir, "..") {
560 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
561 }
562
563 configArgs := args[:]
564
565 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
566 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
567 targetNamePrefix := "MODULES-IN-"
568 if inList("GET-INSTALL-PATH", configArgs) {
569 targetNamePrefix = "GET-INSTALL-PATH-IN-"
570 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
571 }
572
Patrice Arruda13848222019-04-22 17:12:02 -0700573 var targets []string
574
575 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700576 case BUILD_MODULES:
577 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700578 case BUILD_MODULES_IN_A_DIRECTORY:
579 // If dir is the root source tree, all the modules are built of the source tree are built so
580 // no need to find the build file.
581 if topDir == dir {
582 break
583 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700584
Patrice Arruda13848222019-04-22 17:12:02 -0700585 buildFile := findBuildFile(ctx, relDir)
586 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700587 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700588 }
Patrice Arruda13848222019-04-22 17:12:02 -0700589 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
590 case BUILD_MODULES_IN_DIRECTORIES:
591 newConfigArgs, dirs := splitArgs(configArgs)
592 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700593 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700594 }
595
596 // Tidy only override all other specified targets.
597 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
598 if tidyOnly == "true" || tidyOnly == "1" {
599 configArgs = append(configArgs, "tidy_only")
600 } else {
601 configArgs = append(configArgs, targets...)
602 }
603
604 return configArgs
605}
606
607// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
608func convertToTarget(dir string, targetNamePrefix string) string {
609 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
610}
611
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700612// hasBuildFile returns true if dir contains an Android build file.
613func hasBuildFile(ctx Context, dir string) bool {
614 for _, buildFile := range buildFiles {
615 _, err := os.Stat(filepath.Join(dir, buildFile))
616 if err == nil {
617 return true
618 }
619 if !os.IsNotExist(err) {
620 ctx.Fatalf("Error retrieving the build file stats: %v", err)
621 }
622 }
623 return false
624}
625
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700626// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
627// in the current and any sub directory of dir. If a build file is not found, traverse the path
628// up by one directory and repeat again until either a build file is found or reached to the root
629// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
630// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700631func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700632 // If the string is empty or ".", assume it is top directory of the source tree.
633 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700634 return ""
635 }
636
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700637 found := false
638 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
639 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
640 if err != nil {
641 return err
642 }
643 if found {
644 return filepath.SkipDir
645 }
646 if info.IsDir() {
647 return nil
648 }
649 for _, buildFile := range buildFiles {
650 if info.Name() == buildFile {
651 found = true
652 return filepath.SkipDir
653 }
654 }
655 return nil
656 })
657 if err != nil {
658 ctx.Fatalf("Error finding Android build file: %v", err)
659 }
660
661 if found {
662 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700663 }
664 }
665
666 return ""
667}
668
669// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
670func splitArgs(args []string) (newArgs []string, dirs []string) {
671 specialArgs := map[string]bool{
672 "showcommands": true,
673 "snod": true,
674 "dist": true,
675 "checkbuild": true,
676 }
677
678 newArgs = []string{}
679 dirs = []string{}
680
681 for _, arg := range args {
682 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
683 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
684 newArgs = append(newArgs, arg)
685 continue
686 }
687
688 if _, ok := specialArgs[arg]; ok {
689 newArgs = append(newArgs, arg)
690 continue
691 }
692
693 dirs = append(dirs, arg)
694 }
695
696 return newArgs, dirs
697}
698
699// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
700// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
701// source root tree where the build action command was invoked. Each directory is validated if the
702// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700703func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700704 for _, dir := range dirs {
705 // The directory may have specified specific modules to build. ":" is the separator to separate
706 // the directory and the list of modules.
707 s := strings.Split(dir, ":")
708 l := len(s)
709 if l > 2 { // more than one ":" was specified.
710 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
711 }
712
713 dir = filepath.Join(relDir, s[0])
714 if _, err := os.Stat(dir); err != nil {
715 ctx.Fatalf("couldn't find directory %s", dir)
716 }
717
718 // Verify that if there are any targets specified after ":". Each target is separated by ",".
719 var newTargets []string
720 if l == 2 && s[1] != "" {
721 newTargets = strings.Split(s[1], ",")
722 if inList("", newTargets) {
723 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
724 }
725 }
726
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700727 // If there are specified targets to build in dir, an android build file must exist for the one
728 // shot build. For the non-targets case, find the appropriate build file and build all the
729 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700730 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700731 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700732 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
733 }
734 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700735 buildFile := findBuildFile(ctx, dir)
736 if buildFile == "" {
737 ctx.Fatalf("Build file not found for %s directory", dir)
738 }
739 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700740 }
741
Patrice Arruda13848222019-04-22 17:12:02 -0700742 targets = append(targets, newTargets...)
743 }
744
Dan Willemsence41e942019-07-29 23:39:30 -0700745 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700746}
747
Dan Willemsen9b587492017-07-10 22:13:00 -0700748func (c *configImpl) parseArgs(ctx Context, args []string) {
749 for i := 0; i < len(args); i++ {
750 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100751 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700752 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200753 } else if arg == "--empty-ninja-file" {
754 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100755 } else if arg == "--skip-ninja" {
756 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700757 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700758 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
759 // but it does run a Kati ninja file if the .kati_enabled marker file was created
760 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000761 c.skipConfig = true
762 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100763 } else if arg == "--soong-only" {
764 c.skipKati = true
765 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200766 } else if arg == "--config-only" {
767 c.skipKati = true
768 c.skipKatiNinja = true
769 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700770 } else if arg == "--skip-config" {
771 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700772 } else if arg == "--skip-soong-tests" {
773 c.skipSoongTests = true
Colin Cross106d6ef2023-10-24 10:34:56 -0700774 } else if arg == "--no-skip-soong-tests" {
775 c.skipSoongTests = false
MarkDacekd0e7cd32022-12-02 22:22:40 +0000776 } else if arg == "--skip-metrics-upload" {
777 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500778 } else if arg == "--mk-metrics" {
779 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000780 } else if arg == "--multitree-build" {
781 c.multitreeBuild = true
Spandan Das394aa322022-11-03 17:02:10 +0000782 } else if arg == "--search-api-dir" {
783 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900784 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
785 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
786 if source == "ninja_log" {
787 c.ninjaWeightListSource = NINJA_LOG
788 } else if source == "evenly_distributed" {
789 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
790 } else if source == "not_used" {
791 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900792 } else if source == "soong" {
793 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900794 } else if strings.HasPrefix(source, "file,") {
795 c.ninjaWeightListSource = EXTERNAL_FILE
796 filePath := strings.TrimPrefix(source, "file,")
797 err := validateNinjaWeightList(filePath)
798 if err != nil {
799 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
800 }
801 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
802 if err != nil {
803 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
804 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900805 } else {
806 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
807 }
Jihoon Kang2a929ad2023-06-08 19:02:07 +0000808 } else if arg == "--build-from-source-stub" {
809 c.buildFromSourceStub = true
MarkDacekb96561e2022-12-02 04:34:43 +0000810 } else if strings.HasPrefix(arg, "--build-command=") {
811 buildCmd := strings.TrimPrefix(arg, "--build-command=")
812 // remove quotations
813 buildCmd = strings.TrimPrefix(buildCmd, "\"")
814 buildCmd = strings.TrimSuffix(buildCmd, "\"")
815 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacek6614d9c2022-12-07 21:57:38 +0000816 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
817 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
818 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
819 if err == nil {
820 c.buildStartedTime = val
821 } else {
822 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
823 }
MarkDacekf47e1422023-04-19 16:47:36 +0000824 } else if arg == "--ensure-allowlist-integrity" {
825 c.ensureAllowlistIntegrity = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700826 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700827 parseArgNum := func(def int) int {
828 if len(arg) > 2 {
829 p, err := strconv.ParseUint(arg[2:], 10, 31)
830 if err != nil {
831 ctx.Fatalf("Failed to parse %q: %v", arg, err)
832 }
833 return int(p)
834 } else if i+1 < len(args) {
835 p, err := strconv.ParseUint(args[i+1], 10, 31)
836 if err == nil {
837 i++
838 return int(p)
839 }
840 }
841 return def
842 }
843
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700844 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700845 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700846 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700847 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700848 } else {
849 ctx.Fatalln("Unknown option:", arg)
850 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700851 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700852 if k == "OUT_DIR" {
853 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
854 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700855 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700856 } else if arg == "dist" {
857 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200858 } else if arg == "json-module-graph" {
859 c.jsonModuleGraph = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200860 } else if arg == "queryview" {
861 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200862 } else if arg == "soong_docs" {
863 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700864 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700865 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800866 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700867 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700868 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700869 }
870 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700871}
872
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900873func validateNinjaWeightList(weightListFilePath string) (err error) {
874 data, err := os.ReadFile(weightListFilePath)
875 if err != nil {
876 return
877 }
878 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
879 for _, line := range lines {
880 fields := strings.Split(line, ",")
881 if len(fields) != 2 {
882 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
883 }
884 _, err = strconv.Atoi(fields[1])
885 if err != nil {
886 return
887 }
888 }
889 return
890}
891
Dan Willemsened869522018-01-08 14:58:46 -0800892func (c *configImpl) configureLocale(ctx Context) {
893 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
894 output, err := cmd.Output()
895
896 var locales []string
897 if err == nil {
898 locales = strings.Split(string(output), "\n")
899 } else {
900 // If we're unable to list the locales, let's assume en_US.UTF-8
901 locales = []string{"en_US.UTF-8"}
902 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
903 }
904
905 // gettext uses LANGUAGE, which is passed directly through
906
907 // For LANG and LC_*, only preserve the evaluated version of
908 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800909 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800910 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800911 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800912 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800913 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800914 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800915 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800916 }
917
918 c.environ.UnsetWithPrefix("LC_")
919
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800920 if userLang != "" {
921 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800922 }
923
924 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
925 // for others)
926 if inList("C.UTF-8", locales) {
927 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500928 } else if inList("C.utf8", locales) {
929 // These normalize to the same thing
930 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800931 } else if inList("en_US.UTF-8", locales) {
932 c.environ.Set("LANG", "en_US.UTF-8")
933 } else if inList("en_US.utf8", locales) {
934 // These normalize to the same thing
935 c.environ.Set("LANG", "en_US.UTF-8")
936 } else {
937 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
938 }
939}
940
Dan Willemsen1e704462016-08-21 15:17:17 -0700941func (c *configImpl) Environment() *Environment {
942 return c.environ
943}
944
945func (c *configImpl) Arguments() []string {
946 return c.arguments
947}
948
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200949func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200950 if len(c.Arguments()) > 0 {
951 // Explicit targets requested that are not special targets like b2pbuild
952 // or the JSON module graph
953 return true
954 }
955
Colin Cross8d411ff2023-12-07 10:31:24 -0800956 if !c.JsonModuleGraph() && !c.Queryview() && !c.SoongDocs() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200957 // Command line was empty, the default Ninja target is built
958 return true
959 }
960
Colin Cross8d411ff2023-12-07 10:31:24 -0800961 if c.Dist() {
Liz Kammer88677422021-12-15 15:03:19 -0500962 return true
963 }
964
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200965 // build.ninja doesn't need to be generated
966 return false
967}
968
Dan Willemsen1e704462016-08-21 15:17:17 -0700969func (c *configImpl) OutDir() string {
970 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700971 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700972 }
973 return "out"
974}
975
Dan Willemsen8a073a82017-02-04 17:30:44 -0800976func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400977 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000978}
979
980func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700981 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800982}
983
Dan Willemsen1e704462016-08-21 15:17:17 -0700984func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000985 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700986 return c.arguments
987 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700988 return c.ninjaArgs
989}
990
991func (c *configImpl) SoongOutDir() string {
992 return filepath.Join(c.OutDir(), "soong")
993}
994
Spandan Das394aa322022-11-03 17:02:10 +0000995func (c *configImpl) ApiSurfacesOutDir() string {
996 return filepath.Join(c.OutDir(), "api_surfaces")
997}
998
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200999func (c *configImpl) PrebuiltOS() string {
1000 switch runtime.GOOS {
1001 case "linux":
1002 return "linux-x86"
1003 case "darwin":
1004 return "darwin-x86"
1005 default:
1006 panic("Unknown GOOS")
1007 }
1008}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001009
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001010func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001011 if c.SkipKatiNinja() {
1012 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1013 } else {
1014 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1015 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001016}
1017
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001018func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001019 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001020}
1021
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001022func (c *configImpl) UsedEnvFile(tag string) string {
Kiyoung Kimeaa55a82023-06-05 16:56:49 +09001023 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1024 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+v+"."+tag)
1025 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001026 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1027}
1028
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001029func (c *configImpl) SoongDocsHtml() string {
1030 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1031}
1032
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001033func (c *configImpl) QueryviewMarkerFile() string {
1034 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1035}
1036
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001037func (c *configImpl) ModuleGraphFile() string {
1038 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1039}
1040
kgui67007242022-01-25 13:50:25 +08001041func (c *configImpl) ModuleActionsFile() string {
1042 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1043}
1044
Jeff Gastonefc1b412017-03-29 17:29:06 -07001045func (c *configImpl) TempDir() string {
1046 return shared.TempDirForOutDir(c.SoongOutDir())
1047}
1048
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001049func (c *configImpl) FileListDir() string {
1050 return filepath.Join(c.OutDir(), ".module_paths")
1051}
1052
Dan Willemsen1e704462016-08-21 15:17:17 -07001053func (c *configImpl) KatiSuffix() string {
1054 if c.katiSuffix != "" {
1055 return c.katiSuffix
1056 }
1057 panic("SetKatiSuffix has not been called")
1058}
1059
Colin Cross37193492017-11-16 17:55:00 -08001060// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1061// user is interested in additional checks at the expense of build time.
1062func (c *configImpl) Checkbuild() bool {
1063 return c.checkbuild
1064}
1065
Dan Willemsen8a073a82017-02-04 17:30:44 -08001066func (c *configImpl) Dist() bool {
1067 return c.dist
1068}
1069
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001070func (c *configImpl) JsonModuleGraph() bool {
1071 return c.jsonModuleGraph
1072}
1073
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001074func (c *configImpl) Queryview() bool {
1075 return c.queryview
1076}
1077
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001078func (c *configImpl) SoongDocs() bool {
1079 return c.soongDocs
1080}
1081
Dan Willemsen1e704462016-08-21 15:17:17 -07001082func (c *configImpl) IsVerbose() bool {
1083 return c.verbose
1084}
1085
LaMont Jones52a72432023-03-09 18:19:35 +00001086func (c *configImpl) MultitreeBuild() bool {
1087 return c.multitreeBuild
1088}
1089
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001090func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1091 return c.ninjaWeightListSource
1092}
1093
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001094func (c *configImpl) SkipKati() bool {
1095 return c.skipKati
1096}
1097
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001098func (c *configImpl) SkipKatiNinja() bool {
1099 return c.skipKatiNinja
1100}
1101
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001102func (c *configImpl) SkipSoong() bool {
1103 return c.skipSoong
1104}
1105
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001106func (c *configImpl) SkipNinja() bool {
1107 return c.skipNinja
1108}
1109
Anton Hansson5a7861a2021-06-04 10:09:01 +01001110func (c *configImpl) SetSkipNinja(v bool) {
1111 c.skipNinja = v
1112}
1113
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001114func (c *configImpl) SkipConfig() bool {
1115 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001116}
1117
Jihoon Kang1bff0342023-01-17 20:40:22 +00001118func (c *configImpl) BuildFromTextStub() bool {
Jihoon Kang2a929ad2023-06-08 19:02:07 +00001119 return !c.buildFromSourceStub
Jihoon Kang1bff0342023-01-17 20:40:22 +00001120}
1121
Dan Willemsen1e704462016-08-21 15:17:17 -07001122func (c *configImpl) TargetProduct() string {
1123 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1124 return v
1125 }
1126 panic("TARGET_PRODUCT is not defined")
1127}
1128
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001129func (c *configImpl) TargetProductOrErr() (string, error) {
1130 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1131 return v, nil
1132 }
1133 return "", fmt.Errorf("TARGET_PRODUCT is not defined")
1134}
1135
Dan Willemsen02781d52017-05-12 19:28:13 -07001136func (c *configImpl) TargetDevice() string {
1137 return c.targetDevice
1138}
1139
1140func (c *configImpl) SetTargetDevice(device string) {
1141 c.targetDevice = device
1142}
1143
1144func (c *configImpl) TargetBuildVariant() string {
1145 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1146 return v
1147 }
1148 panic("TARGET_BUILD_VARIANT is not defined")
1149}
1150
Dan Willemsen1e704462016-08-21 15:17:17 -07001151func (c *configImpl) KatiArgs() []string {
1152 return c.katiArgs
1153}
1154
1155func (c *configImpl) Parallel() int {
1156 return c.parallel
1157}
1158
Sam Delmerico98a73292023-02-21 11:50:29 -05001159func (c *configImpl) GetSourceRootDirs() []string {
1160 return c.sourceRootDirs
1161}
1162
1163func (c *configImpl) SetSourceRootDirs(i []string) {
1164 c.sourceRootDirs = i
1165}
1166
Spandan Dasc5763832022-11-08 18:42:16 +00001167func (c *configImpl) GetIncludeTags() []string {
1168 return c.includeTags
1169}
1170
1171func (c *configImpl) SetIncludeTags(i []string) {
1172 c.includeTags = i
1173}
1174
MarkDacek6614d9c2022-12-07 21:57:38 +00001175func (c *configImpl) GetLogsPrefix() string {
1176 return c.logsPrefix
1177}
1178
1179func (c *configImpl) SetLogsPrefix(prefix string) {
1180 c.logsPrefix = prefix
1181}
1182
Colin Cross8b8bec32019-11-15 13:18:43 -08001183func (c *configImpl) HighmemParallel() int {
1184 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1185 return i
1186 }
1187
1188 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1189 parallel := c.Parallel()
1190 if c.UseRemoteBuild() {
1191 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1192 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1193 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1194 // Return 1/16th of the size of the local pool, rounding up.
1195 return (parallel + 15) / 16
1196 } else if c.totalRAM == 0 {
1197 // Couldn't detect the total RAM, don't restrict highmem processes.
1198 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001199 } else if c.totalRAM <= 16*1024*1024*1024 {
1200 // Less than 16GB of ram, restrict to 1 highmem processes
1201 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001202 } else if c.totalRAM <= 32*1024*1024*1024 {
1203 // Less than 32GB of ram, restrict to 2 highmem processes
1204 return 2
1205 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1206 // If less than 8GB total RAM per process, reduce the number of highmem processes
1207 return p
1208 }
1209 // No restriction on highmem processes
1210 return parallel
1211}
1212
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001213func (c *configImpl) TotalRAM() uint64 {
1214 return c.totalRAM
1215}
1216
Kousik Kumarec478642020-09-21 13:39:24 -04001217// ForceUseGoma determines whether we should override Goma deprecation
1218// and use Goma for the current build or not.
1219func (c *configImpl) ForceUseGoma() bool {
1220 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1221 v = strings.TrimSpace(v)
1222 if v != "" && v != "false" {
1223 return true
1224 }
1225 }
1226 return false
1227}
1228
Dan Willemsen1e704462016-08-21 15:17:17 -07001229func (c *configImpl) UseGoma() bool {
1230 if v, ok := c.environ.Get("USE_GOMA"); ok {
1231 v = strings.TrimSpace(v)
1232 if v != "" && v != "false" {
1233 return true
1234 }
1235 }
1236 return false
1237}
1238
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001239func (c *configImpl) StartGoma() bool {
1240 if !c.UseGoma() {
1241 return false
1242 }
1243
1244 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1245 v = strings.TrimSpace(v)
1246 if v != "" && v != "false" {
1247 return false
1248 }
1249 }
1250 return true
1251}
1252
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001253func (c *configImpl) canSupportRBE() bool {
1254 // Do not use RBE with prod credentials in scenarios when stubby doesn't exist, since
1255 // its unlikely that we will be able to obtain necessary creds without stubby.
1256 authType, _ := c.rbeAuth()
1257 if !c.StubbyExists() && strings.Contains(authType, "use_google_prod_creds") {
1258 return false
1259 }
1260 return true
1261}
1262
Ramy Medhatbbf25672019-07-17 12:30:04 +00001263func (c *configImpl) UseRBE() bool {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001264 // These alternate modes of running Soong do not use RBE / reclient.
Colin Cross8d411ff2023-12-07 10:31:24 -08001265 if c.Queryview() || c.JsonModuleGraph() {
Jingwen Chend7ccde12023-06-28 07:19:26 +00001266 return false
1267 }
1268
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001269 if !c.canSupportRBE() {
Kousik Kumar67ad4342023-06-06 15:09:27 -04001270 return false
1271 }
Kousik Kumar6d1e3482023-07-24 03:44:16 +00001272
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001273 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001274 v = strings.TrimSpace(v)
1275 if v != "" && v != "false" {
1276 return true
1277 }
1278 }
1279 return false
1280}
1281
1282func (c *configImpl) StartRBE() bool {
1283 if !c.UseRBE() {
1284 return false
1285 }
1286
1287 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1288 v = strings.TrimSpace(v)
1289 if v != "" && v != "false" {
1290 return false
1291 }
1292 }
1293 return true
1294}
1295
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001296func (c *configImpl) rbeProxyLogsDir() string {
1297 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001298 if v, ok := c.environ.Get(f); ok {
1299 return v
1300 }
1301 }
Ramy Medhatbc061762023-10-10 18:36:59 +00001302 return c.rbeTmpDir()
1303}
1304
1305func (c *configImpl) rbeDownloadTmpDir() string {
Cole Faust06ea5312023-10-18 17:38:40 -07001306 for _, f := range []string{"RBE_download_tmp_dir", "FLAG_download_tmp_dir"} {
Ramy Medhatbc061762023-10-10 18:36:59 +00001307 if v, ok := c.environ.Get(f); ok {
1308 return v
1309 }
1310 }
1311 return c.rbeTmpDir()
1312}
1313
1314func (c *configImpl) rbeTmpDir() string {
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001315 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1316 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001317}
1318
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001319func (c *configImpl) rbeCacheDir() string {
1320 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1321 if v, ok := c.environ.Get(f); ok {
1322 return v
1323 }
1324 }
1325 return shared.JoinPath(c.SoongOutDir(), "rbe")
1326}
1327
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001328func (c *configImpl) shouldCleanupRBELogsDir() bool {
1329 // Perform a log directory cleanup only when the log directory
1330 // is auto created by the build rather than user-specified.
1331 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1332 if _, ok := c.environ.Get(f); ok {
1333 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001334 }
1335 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001336 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001337}
1338
1339func (c *configImpl) rbeExecRoot() string {
1340 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1341 if v, ok := c.environ.Get(f); ok {
1342 return v
1343 }
1344 }
1345 wd, err := os.Getwd()
1346 if err != nil {
1347 return ""
1348 }
1349 return wd
1350}
1351
1352func (c *configImpl) rbeDir() string {
1353 if v, ok := c.environ.Get("RBE_DIR"); ok {
1354 return v
1355 }
1356 return "prebuilts/remoteexecution-client/live/"
1357}
1358
1359func (c *configImpl) rbeReproxy() string {
1360 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1361 if v, ok := c.environ.Get(f); ok {
1362 return v
1363 }
1364 }
1365 return filepath.Join(c.rbeDir(), "reproxy")
1366}
1367
1368func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001369 credFlags := []string{
1370 "use_application_default_credentials",
1371 "use_gce_credentials",
1372 "credential_file",
1373 "use_google_prod_creds",
1374 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001375 for _, cf := range credFlags {
1376 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1377 if v, ok := c.environ.Get(f); ok {
1378 v = strings.TrimSpace(v)
1379 if v != "" && v != "false" && v != "0" {
1380 return "RBE_" + cf, v
1381 }
1382 }
1383 }
1384 }
1385 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001386}
1387
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001388func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1389 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1390 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1391
1392 name := filepath.Join(dir, base)
1393 if len(name) < maxNameLen {
1394 return name, nil
1395 }
1396
1397 name = filepath.Join("/tmp", base)
1398 if len(name) < maxNameLen {
1399 return name, nil
1400 }
1401
1402 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1403}
1404
Kousik Kumar7bc78192022-04-27 14:52:56 -04001405// IsGooglerEnvironment returns true if the current build is running
1406// on a Google developer machine and false otherwise.
1407func (c *configImpl) IsGooglerEnvironment() bool {
1408 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1409 if v, ok := c.environ.Get(cf); ok {
1410 return v == "googler"
1411 }
1412 return false
1413}
1414
1415// GoogleProdCredsExist determine whether credentials exist on the
1416// Googler machine to use remote execution.
1417func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001418 if googleProdCredsExistCache {
1419 return googleProdCredsExistCache
1420 }
andusyu0b3dc032023-06-21 17:29:32 -04001421 if _, err := exec.Command("/usr/bin/gcertstatus", "-nocheck_ssh").Output(); err != nil {
Kousik Kumar7bc78192022-04-27 14:52:56 -04001422 return false
1423 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001424 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001425 return true
1426}
1427
1428// UseRemoteBuild indicates whether to use a remote build acceleration system
1429// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001430func (c *configImpl) UseRemoteBuild() bool {
1431 return c.UseGoma() || c.UseRBE()
1432}
1433
Kousik Kumar7bc78192022-04-27 14:52:56 -04001434// StubbyExists checks whether the stubby binary exists on the machine running
1435// the build.
1436func (c *configImpl) StubbyExists() bool {
1437 if _, err := exec.LookPath("stubby"); err != nil {
1438 return false
1439 }
1440 return true
1441}
1442
Dan Willemsen1e704462016-08-21 15:17:17 -07001443// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001444// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001445// still limited by Parallel()
1446func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001447 if !c.UseRemoteBuild() {
1448 return 0
1449 }
1450 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1451 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001452 }
1453 return 500
1454}
1455
1456func (c *configImpl) SetKatiArgs(args []string) {
1457 c.katiArgs = args
1458}
1459
1460func (c *configImpl) SetNinjaArgs(args []string) {
1461 c.ninjaArgs = args
1462}
1463
1464func (c *configImpl) SetKatiSuffix(suffix string) {
1465 c.katiSuffix = suffix
1466}
1467
Dan Willemsene0879fc2017-08-04 15:06:27 -07001468func (c *configImpl) LastKatiSuffixFile() string {
1469 return filepath.Join(c.OutDir(), "last_kati_suffix")
1470}
1471
1472func (c *configImpl) HasKatiSuffix() bool {
1473 return c.katiSuffix != ""
1474}
1475
Dan Willemsen1e704462016-08-21 15:17:17 -07001476func (c *configImpl) KatiEnvFile() string {
1477 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1478}
1479
Dan Willemsen29971232018-09-26 14:58:30 -07001480func (c *configImpl) KatiBuildNinjaFile() string {
1481 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001482}
1483
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001484func (c *configImpl) KatiPackageNinjaFile() string {
1485 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1486}
1487
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001488func (c *configImpl) SoongVarsFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001489 targetProduct, err := c.TargetProductOrErr()
1490 if err != nil {
1491 return filepath.Join(c.SoongOutDir(), "soong.variables")
1492 } else {
1493 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+".variables")
1494 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001495}
1496
Dan Willemsen1e704462016-08-21 15:17:17 -07001497func (c *configImpl) SoongNinjaFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001498 targetProduct, err := c.TargetProductOrErr()
1499 if err != nil {
1500 return filepath.Join(c.SoongOutDir(), "build.ninja")
1501 } else {
1502 return filepath.Join(c.SoongOutDir(), "build."+targetProduct+".ninja")
1503 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001504}
1505
1506func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001507 if c.katiSuffix == "" {
1508 return filepath.Join(c.OutDir(), "combined.ninja")
1509 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001510 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1511}
1512
1513func (c *configImpl) SoongAndroidMk() string {
1514 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1515}
1516
1517func (c *configImpl) SoongMakeVarsMk() string {
1518 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1519}
1520
Colin Crossaa9a2732023-10-27 10:54:27 -07001521func (c *configImpl) SoongBuildMetrics() string {
Colin Crossb67b0612023-10-31 10:02:45 -07001522 return filepath.Join(c.LogsDir(), "soong_build_metrics.pb")
Colin Crossaa9a2732023-10-27 10:54:27 -07001523}
1524
Dan Willemsenf052f782017-05-18 15:29:04 -07001525func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001526 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001527}
1528
Dan Willemsen02781d52017-05-12 19:28:13 -07001529func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001530 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1531}
1532
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001533func (c *configImpl) KatiPackageMkDir() string {
1534 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1535}
1536
Dan Willemsenf052f782017-05-18 15:29:04 -07001537func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001538 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001539}
1540
1541func (c *configImpl) HostOut() string {
1542 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1543}
1544
1545// This probably needs to be multi-valued, so not exporting it for now
1546func (c *configImpl) hostCrossOut() string {
1547 if runtime.GOOS == "linux" {
1548 return filepath.Join(c.hostOutRoot(), "windows-x86")
1549 } else {
1550 return ""
1551 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001552}
1553
Dan Willemsen1e704462016-08-21 15:17:17 -07001554func (c *configImpl) HostPrebuiltTag() string {
1555 if runtime.GOOS == "linux" {
1556 return "linux-x86"
1557 } else if runtime.GOOS == "darwin" {
1558 return "darwin-x86"
1559 } else {
1560 panic("Unsupported OS")
1561 }
1562}
Dan Willemsenf173d592017-04-27 14:28:00 -07001563
Dan Willemsen8122bd52017-10-12 20:20:41 -07001564func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001565 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1566 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001567 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1568 if _, err := os.Stat(asan); err == nil {
1569 return asan
1570 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001571 }
1572 }
1573 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1574}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001575
1576func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1577 c.brokenDupRules = val
1578}
1579
1580func (c *configImpl) BuildBrokenDupRules() bool {
1581 return c.brokenDupRules
1582}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001583
Dan Willemsen25e6f092019-04-09 10:22:43 -07001584func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1585 c.brokenUsesNetwork = val
1586}
1587
1588func (c *configImpl) BuildBrokenUsesNetwork() bool {
1589 return c.brokenUsesNetwork
1590}
1591
Dan Willemsene3336352020-01-02 19:10:38 -08001592func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1593 c.brokenNinjaEnvVars = val
1594}
1595
1596func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1597 return c.brokenNinjaEnvVars
1598}
1599
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001600func (c *configImpl) SetTargetDeviceDir(dir string) {
1601 c.targetDeviceDir = dir
1602}
1603
1604func (c *configImpl) TargetDeviceDir() string {
1605 return c.targetDeviceDir
1606}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001607
Patrice Arruda219eef32020-06-01 17:29:30 +00001608func (c *configImpl) BuildDateTime() string {
1609 return c.buildDateTime
1610}
1611
1612func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001613 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001614}
Patrice Arruda83842d72020-12-08 19:42:08 +00001615
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001616// LogsDir returns the absolute path to the logs directory where build log and
1617// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001618// directory. If the argument dist is specified, the logs directory
1619// is <dist_dir>/logs.
1620func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001621 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001622 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001623 // 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 -05001624 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001625 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001626 absDir, err := filepath.Abs(dir)
1627 if err != nil {
1628 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1629 os.Exit(1)
1630 }
1631 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001632}
1633
Chris Parsons53f68ae2022-03-03 12:01:40 -05001634// MkFileMetrics returns the file path for make-related metrics.
1635func (c *configImpl) MkMetrics() string {
1636 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1637}
1638
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001639func (c *configImpl) SetEmptyNinjaFile(v bool) {
1640 c.emptyNinjaFile = v
1641}
1642
1643func (c *configImpl) EmptyNinjaFile() bool {
1644 return c.emptyNinjaFile
1645}
Yu Liu6e13b402021-07-27 14:29:06 -07001646
MarkDacekd0e7cd32022-12-02 22:22:40 +00001647func (c *configImpl) SkipMetricsUpload() bool {
1648 return c.skipMetricsUpload
1649}
1650
MarkDacekf47e1422023-04-19 16:47:36 +00001651func (c *configImpl) EnsureAllowlistIntegrity() bool {
1652 return c.ensureAllowlistIntegrity
1653}
1654
MarkDacek6614d9c2022-12-07 21:57:38 +00001655// Returns a Time object if one was passed via a command-line flag.
1656// Otherwise returns the passed default.
1657func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1658 if c.buildStartedTime == 0 {
1659 return defaultTime
1660 }
1661 return time.UnixMilli(c.buildStartedTime)
1662}
1663
Yu Liu6e13b402021-07-27 14:29:06 -07001664func GetMetricsUploader(topDir string, env *Environment) string {
1665 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1666 metricsUploader := filepath.Join(topDir, p)
1667 if _, err := os.Stat(metricsUploader); err == nil {
1668 return metricsUploader
1669 }
1670 }
1671
1672 return ""
1673}