blob: 45735ad66d1ca5b17dc992fff4c4e38f9225a3a6 [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"
Ramy Medhat0fc67eb2020-08-12 01:26:23 -040019 "fmt"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050020 "io/ioutil"
Kousik Kumar4c180ad2022-05-27 07:48:37 -040021 "math/rand"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080022 "os"
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050023 "os/exec"
Dan Willemsen1e704462016-08-21 15:17:17 -070024 "path/filepath"
25 "runtime"
26 "strconv"
27 "strings"
Kousik Kumar4c180ad2022-05-27 07:48:37 -040028 "syscall"
Nan Zhang2e6a4ff2018-02-14 13:27:26 -080029 "time"
Jeff Gastonefc1b412017-03-29 17:29:06 -070030
31 "android/soong/shared"
Kousik Kumarec478642020-09-21 13:39:24 -040032
Dan Willemsen4591b642021-05-24 14:24:12 -070033 "google.golang.org/protobuf/proto"
Patrice Arruda96850362020-08-11 20:41:11 +000034
35 smpb "android/soong/ui/metrics/metrics_proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070036)
37
Kousik Kumar3ff037e2022-01-25 22:11:01 -050038const (
Chris Parsons53f68ae2022-03-03 12:01:40 -050039 envConfigDir = "vendor/google/tools/soong_config"
40 jsonSuffix = "json"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050041)
42
Kousik Kumar4c180ad2022-05-27 07:48:37 -040043var (
Kevin Dagostino096ab2f2023-03-03 19:47:17 +000044 rbeRandPrefix int
45 googleProdCredsExistCache bool
Kousik Kumar4c180ad2022-05-27 07:48:37 -040046)
47
48func init() {
49 rand.Seed(time.Now().UnixNano())
50 rbeRandPrefix = rand.Intn(1000)
51}
52
Dan Willemsen1e704462016-08-21 15:17:17 -070053type Config struct{ *configImpl }
54
55type configImpl struct {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020056 // Some targets that are implemented in soong_build
57 // (bp2build, json-module-graph) are not here and have their own bits below.
Colin Cross28f527c2019-11-26 16:19:04 -080058 arguments []string
59 goma bool
60 environ *Environment
61 distDir string
62 buildDateTime string
MarkDacek6614d9c2022-12-07 21:57:38 +000063 logsPrefix string
Dan Willemsen1e704462016-08-21 15:17:17 -070064
65 // From the arguments
MarkDacekf47e1422023-04-19 16:47:36 +000066 parallel int
67 keepGoing int
68 verbose bool
69 checkbuild bool
70 dist bool
71 jsonModuleGraph bool
72 apiBp2build bool // Generate BUILD files for Soong modules that contribute APIs
73 bp2build bool
74 queryview bool
75 reportMkMetrics bool // Collect and report mk2bp migration progress metrics.
76 soongDocs bool
77 multitreeBuild bool // This is a multitree build.
78 skipConfig bool
79 skipKati bool
80 skipKatiNinja bool
81 skipSoong bool
82 skipNinja bool
83 skipSoongTests bool
84 searchApiDir bool // Scan the Android.bp files generated in out/api_surfaces
85 skipMetricsUpload bool
86 buildStartedTime int64 // For metrics-upload-only - manually specify a build-started time
87 buildFromTextStub bool
MarkDacekd33c2fd2023-05-04 20:40:04 +000088 ensureAllowlistIntegrity bool // For CI builds - make sure modules are mixed-built
89 bazelExitCode int32 // For b-runs - necessary for updating NonZeroExit
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
MarkDacekb78465d2022-10-18 20:10:16 +0000108 bazelProdMode bool
109 bazelDevMode bool
110 bazelStagingMode bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000111
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700112 // Set by multiproduct_kati
113 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700114
115 metricsUploader string
MarkDacekd06db5d2022-11-29 00:47:59 +0000116
117 bazelForceEnabledModules string
Spandan Dasc5763832022-11-08 18:42:16 +0000118
Sam Delmerico98a73292023-02-21 11:50:29 -0500119 includeTags []string
120 sourceRootDirs []string
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900121
122 // Data source to write ninja weight list
123 ninjaWeightListSource NinjaWeightListSource
Dan Willemsen1e704462016-08-21 15:17:17 -0700124}
125
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900126type NinjaWeightListSource uint
127
128const (
129 // ninja doesn't use weight list.
130 NOT_USED NinjaWeightListSource = iota
131 // ninja uses weight list based on previous builds by ninja log
132 NINJA_LOG
133 // ninja thinks every task has the same weight.
134 EVENLY_DISTRIBUTED
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900135 // ninja uses an external custom weight list
136 EXTERNAL_FILE
Jeongik Chae114e602023-03-19 00:12:39 +0900137 // ninja uses a prioritized module list from Soong
138 HINT_FROM_SOONG
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900139)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800140const srcDirFileCheck = "build/soong/root.bp"
141
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700142var buildFiles = []string{"Android.mk", "Android.bp"}
143
Patrice Arruda13848222019-04-22 17:12:02 -0700144type BuildAction uint
145
146const (
147 // Builds all of the modules and their dependencies of a specified directory, relative to the root
148 // directory of the source tree.
149 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
150
151 // Builds all of the modules and their dependencies of a list of specified directories. All specified
152 // directories are relative to the root directory of the source tree.
153 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700154
155 // Build a list of specified modules. If none was specified, simply build the whole source tree.
156 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700157)
158
159// checkTopDir validates that the current directory is at the root directory of the source tree.
160func checkTopDir(ctx Context) {
161 if _, err := os.Stat(srcDirFileCheck); err != nil {
162 if os.IsNotExist(err) {
163 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
164 }
165 ctx.Fatalln("Error verifying tree state:", err)
166 }
167}
168
MarkDacek7901e582023-01-09 19:48:01 +0000169func loadEnvConfig(ctx Context, config *configImpl, bc string) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500170 if bc == "" {
171 return nil
172 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500173
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500174 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500175 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500176 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500177 envConfigDir,
178 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500179 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500180 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
181 envVarsJSON, err := ioutil.ReadFile(cfgFile)
182 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500183 continue
184 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500185 ctx.Verbosef("Loading config file %v\n", cfgFile)
186 var envVars map[string]map[string]string
187 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
188 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
189 continue
190 }
191 for k, v := range envVars["env"] {
192 if os.Getenv(k) != "" {
193 continue
194 }
195 config.environ.Set(k, v)
196 }
197 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
198 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500199 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500200
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500201 return nil
202}
203
Chris Parsonsb6e96902022-10-31 20:08:45 -0400204func defaultBazelProdMode(cfg *configImpl) bool {
MarkDacekd06db5d2022-11-29 00:47:59 +0000205 // Environment flag to disable Bazel for users which experience
Chris Parsonsb6e96902022-10-31 20:08:45 -0400206 // broken bazel-handled builds, or significant performance regressions.
207 if cfg.IsBazelMixedBuildForceDisabled() {
208 return false
209 }
210 // Darwin-host builds are currently untested with Bazel.
211 if runtime.GOOS == "darwin" {
212 return false
213 }
Chris Parsons035e03a2022-11-01 14:25:45 -0400214 return true
Chris Parsonsb6e96902022-10-31 20:08:45 -0400215}
216
MarkDacekd33c2fd2023-05-04 20:40:04 +0000217func UploadOnlyConfig(ctx Context, args ...string) Config {
MarkDacek6614d9c2022-12-07 21:57:38 +0000218 ret := &configImpl{
219 environ: OsEnvironment(),
220 sandboxConfig: &SandboxConfig{},
221 }
MarkDacekd33c2fd2023-05-04 20:40:04 +0000222 ret.parseArgs(ctx, args)
MarkDacek7901e582023-01-09 19:48:01 +0000223 srcDir := absPath(ctx, ".")
224 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
225 if err := loadEnvConfig(ctx, ret, bc); err != nil {
226 ctx.Fatalln("Failed to parse env config files: %v", err)
227 }
228 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
MarkDacek6614d9c2022-12-07 21:57:38 +0000229 return Config{ret}
230}
231
Dan Willemsen1e704462016-08-21 15:17:17 -0700232func NewConfig(ctx Context, args ...string) Config {
233 ret := &configImpl{
Chris Parsonsfddeaff2023-05-17 21:53:34 +0000234 environ: OsEnvironment(),
235 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700236 }
237
Patrice Arruda90109172020-07-28 18:07:27 +0000238 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700239 ret.parallel = runtime.NumCPU() + 2
240 ret.keepGoing = 1
241
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800242 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700243 ret.parseArgs(ctx, args)
Jeongik Chae114e602023-03-19 00:12:39 +0900244
245 if ret.ninjaWeightListSource == HINT_FROM_SOONG {
246 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "true")
247 }
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800248 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700249 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
250 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
251 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800252 outDir := "out"
253 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
254 if wd, err := os.Getwd(); err != nil {
255 ctx.Fatalln("Failed to get working directory:", err)
256 } else {
257 outDir = filepath.Join(baseDir, filepath.Base(wd))
258 }
259 }
260 ret.environ.Set("OUT_DIR", outDir)
261 }
262
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500263 // loadEnvConfig needs to know what the OUT_DIR is, so it should
264 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000265 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
266
267 if bc != "" {
Kousik Kumarc8818332023-01-16 16:33:05 +0000268 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000269 ctx.Fatalln("Failed to parse env config files: %v", err)
270 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500271 }
272
Dan Willemsen2d31a442018-10-20 21:33:41 -0700273 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
274 ret.distDir = filepath.Clean(distDir)
275 } else {
276 ret.distDir = filepath.Join(ret.OutDir(), "dist")
277 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700278
Spandan Das05063612021-06-25 01:39:04 +0000279 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
280 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
281 }
282
Dan Willemsen1e704462016-08-21 15:17:17 -0700283 ret.environ.Unset(
284 // We're already using it
285 "USE_SOONG_UI",
286
287 // We should never use GOROOT/GOPATH from the shell environment
288 "GOROOT",
289 "GOPATH",
290
291 // These should only come from Soong, not the environment.
292 "CLANG",
293 "CLANG_CXX",
294 "CCC_CC",
295 "CCC_CXX",
296
297 // Used by the goma compiler wrapper, but should only be set by
298 // gomacc
299 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800300
301 // We handle this above
302 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700303
Dan Willemsen2d31a442018-10-20 21:33:41 -0700304 // This is handled above too, and set for individual commands later
305 "DIST_DIR",
306
Dan Willemsen68a09852017-04-18 13:56:57 -0700307 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000308 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700309 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700310 "DISPLAY",
311 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000312 "JAVAC",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700313 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700314 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700315
316 // Drop make flags
317 "MAKEFLAGS",
318 "MAKELEVEL",
319 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700320
321 // Set in envsetup.sh, reset in makefiles
322 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700323
324 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
325 "ANDROID_BUILD_TOP",
326 "ANDROID_HOST_OUT",
327 "ANDROID_PRODUCT_OUT",
328 "ANDROID_HOST_OUT_TESTCASES",
329 "ANDROID_TARGET_OUT_TESTCASES",
330 "ANDROID_TOOLCHAIN",
331 "ANDROID_TOOLCHAIN_2ND_ARCH",
332 "ANDROID_DEV_SCRIPTS",
333 "ANDROID_EMULATOR_PREBUILTS",
334 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700335 )
336
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400337 if ret.UseGoma() || ret.ForceUseGoma() {
338 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
339 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400340 }
341
Dan Willemsen1e704462016-08-21 15:17:17 -0700342 // Tell python not to spam the source tree with .pyc files.
343 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
344
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400345 tmpDir := absPath(ctx, ret.TempDir())
346 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800347
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700348 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
349 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
350 "llvm-binutils-stable/llvm-symbolizer")
351 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
352
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800353 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700354 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800355
Yu Liu6e13b402021-07-27 14:29:06 -0700356 srcDir := absPath(ctx, ".")
357 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700358 ctx.Println("You are building in a directory whose absolute path contains a space character:")
359 ctx.Println()
360 ctx.Printf("%q\n", srcDir)
361 ctx.Println()
362 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700363 }
364
Yu Liu6e13b402021-07-27 14:29:06 -0700365 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
366
Dan Willemsendb8457c2017-05-12 16:38:17 -0700367 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700368 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
369 ctx.Println()
370 ctx.Printf("%q\n", outDir)
371 ctx.Println()
372 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700373 }
374
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000375 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700376 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
377 ctx.Println()
378 ctx.Printf("%q\n", distDir)
379 ctx.Println()
380 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700381 }
382
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700383 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000384 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
385 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100386 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800387 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700388 javaHome := func() string {
389 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
390 return override
391 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000392 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
393 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 +0100394 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000395 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
396 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
397 }
398 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700399 }()
400 absJavaHome := absPath(ctx, javaHome)
401
Dan Willemsened869522018-01-08 14:58:46 -0800402 ret.configureLocale(ctx)
403
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700404 newPath := []string{filepath.Join(absJavaHome, "bin")}
405 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
406 newPath = append(newPath, path)
407 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100408
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700409 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
410 ret.environ.Set("JAVA_HOME", absJavaHome)
411 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000412 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
413 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100414 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700415 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
416
LaMont Jones52a72432023-03-09 18:19:35 +0000417 if ret.MultitreeBuild() {
418 ret.environ.Set("MULTITREE_BUILD", "true")
419 }
420
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800421 outDir := ret.OutDir()
422 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800423 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800424 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800425 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800426 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800427 }
Colin Cross28f527c2019-11-26 16:19:04 -0800428
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800429 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
430
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400431 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400432 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400433 ret.environ.Set(k, v)
434 }
435 }
436
Jihoon Kang1bff0342023-01-17 20:40:22 +0000437 if ret.BuildFromTextStub() {
438 // TODO(b/271443071): support hidden api check for from-text stub build
439 ret.environ.Set("UNSAFE_DISABLE_HIDDENAPI_FLAGS", "true")
440 }
441
Patrice Arruda83842d72020-12-08 19:42:08 +0000442 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800443 if err := os.RemoveAll(bpd); err != nil {
444 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
445 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000446
Patrice Arruda96850362020-08-11 20:41:11 +0000447 c := Config{ret}
448 storeConfigMetrics(ctx, c)
449 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700450}
451
Patrice Arruda13848222019-04-22 17:12:02 -0700452// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
453// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700454func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
455 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700456}
457
Patrice Arruda96850362020-08-11 20:41:11 +0000458// storeConfigMetrics selects a set of configuration information and store in
459// the metrics system for further analysis.
460func storeConfigMetrics(ctx Context, config Config) {
461 if ctx.Metrics == nil {
462 return
463 }
464
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400465 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000466
467 s := &smpb.SystemResourceInfo{
468 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
469 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
470 }
471 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000472}
473
Jeongik Cha8d63d562023-03-17 03:52:13 +0900474func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900475 switch s {
476 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900477 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900478 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900479 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900480 case EXTERNAL_FILE:
481 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900482 case HINT_FROM_SOONG:
483 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900484 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900485 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900486 }
487}
488
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400489func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700490 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400491 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
492 UseGoma: proto.Bool(config.UseGoma()),
493 UseRbe: proto.Bool(config.UseRBE()),
494 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
495 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900496 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400497 }
Yu Liue737a992021-10-04 13:21:41 -0700498 c.Targets = append(c.Targets, config.arguments...)
499
500 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400501}
502
Patrice Arruda13848222019-04-22 17:12:02 -0700503// getConfigArgs processes the command arguments based on the build action and creates a set of new
504// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700505func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700506 // The next block of code verifies that the current directory is the root directory of the source
507 // tree. It then finds the relative path of dir based on the root directory of the source tree
508 // and verify that dir is inside of the source tree.
509 checkTopDir(ctx)
510 topDir, err := os.Getwd()
511 if err != nil {
512 ctx.Fatalf("Error retrieving top directory: %v", err)
513 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700514 dir, err = filepath.EvalSymlinks(dir)
515 if err != nil {
516 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
517 }
Patrice Arruda13848222019-04-22 17:12:02 -0700518 dir, err = filepath.Abs(dir)
519 if err != nil {
520 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
521 }
522 relDir, err := filepath.Rel(topDir, dir)
523 if err != nil {
524 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
525 }
526 // If there are ".." in the path, it's not in the source tree.
527 if strings.Contains(relDir, "..") {
528 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
529 }
530
531 configArgs := args[:]
532
533 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
534 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
535 targetNamePrefix := "MODULES-IN-"
536 if inList("GET-INSTALL-PATH", configArgs) {
537 targetNamePrefix = "GET-INSTALL-PATH-IN-"
538 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
539 }
540
Patrice Arruda13848222019-04-22 17:12:02 -0700541 var targets []string
542
543 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700544 case BUILD_MODULES:
545 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700546 case BUILD_MODULES_IN_A_DIRECTORY:
547 // If dir is the root source tree, all the modules are built of the source tree are built so
548 // no need to find the build file.
549 if topDir == dir {
550 break
551 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700552
Patrice Arruda13848222019-04-22 17:12:02 -0700553 buildFile := findBuildFile(ctx, relDir)
554 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700555 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700556 }
Patrice Arruda13848222019-04-22 17:12:02 -0700557 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
558 case BUILD_MODULES_IN_DIRECTORIES:
559 newConfigArgs, dirs := splitArgs(configArgs)
560 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700561 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700562 }
563
564 // Tidy only override all other specified targets.
565 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
566 if tidyOnly == "true" || tidyOnly == "1" {
567 configArgs = append(configArgs, "tidy_only")
568 } else {
569 configArgs = append(configArgs, targets...)
570 }
571
572 return configArgs
573}
574
575// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
576func convertToTarget(dir string, targetNamePrefix string) string {
577 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
578}
579
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700580// hasBuildFile returns true if dir contains an Android build file.
581func hasBuildFile(ctx Context, dir string) bool {
582 for _, buildFile := range buildFiles {
583 _, err := os.Stat(filepath.Join(dir, buildFile))
584 if err == nil {
585 return true
586 }
587 if !os.IsNotExist(err) {
588 ctx.Fatalf("Error retrieving the build file stats: %v", err)
589 }
590 }
591 return false
592}
593
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700594// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
595// in the current and any sub directory of dir. If a build file is not found, traverse the path
596// up by one directory and repeat again until either a build file is found or reached to the root
597// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
598// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700599func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700600 // If the string is empty or ".", assume it is top directory of the source tree.
601 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700602 return ""
603 }
604
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700605 found := false
606 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
607 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
608 if err != nil {
609 return err
610 }
611 if found {
612 return filepath.SkipDir
613 }
614 if info.IsDir() {
615 return nil
616 }
617 for _, buildFile := range buildFiles {
618 if info.Name() == buildFile {
619 found = true
620 return filepath.SkipDir
621 }
622 }
623 return nil
624 })
625 if err != nil {
626 ctx.Fatalf("Error finding Android build file: %v", err)
627 }
628
629 if found {
630 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700631 }
632 }
633
634 return ""
635}
636
637// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
638func splitArgs(args []string) (newArgs []string, dirs []string) {
639 specialArgs := map[string]bool{
640 "showcommands": true,
641 "snod": true,
642 "dist": true,
643 "checkbuild": true,
644 }
645
646 newArgs = []string{}
647 dirs = []string{}
648
649 for _, arg := range args {
650 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
651 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
652 newArgs = append(newArgs, arg)
653 continue
654 }
655
656 if _, ok := specialArgs[arg]; ok {
657 newArgs = append(newArgs, arg)
658 continue
659 }
660
661 dirs = append(dirs, arg)
662 }
663
664 return newArgs, dirs
665}
666
667// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
668// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
669// source root tree where the build action command was invoked. Each directory is validated if the
670// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700671func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700672 for _, dir := range dirs {
673 // The directory may have specified specific modules to build. ":" is the separator to separate
674 // the directory and the list of modules.
675 s := strings.Split(dir, ":")
676 l := len(s)
677 if l > 2 { // more than one ":" was specified.
678 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
679 }
680
681 dir = filepath.Join(relDir, s[0])
682 if _, err := os.Stat(dir); err != nil {
683 ctx.Fatalf("couldn't find directory %s", dir)
684 }
685
686 // Verify that if there are any targets specified after ":". Each target is separated by ",".
687 var newTargets []string
688 if l == 2 && s[1] != "" {
689 newTargets = strings.Split(s[1], ",")
690 if inList("", newTargets) {
691 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
692 }
693 }
694
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700695 // If there are specified targets to build in dir, an android build file must exist for the one
696 // shot build. For the non-targets case, find the appropriate build file and build all the
697 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700698 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700699 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700700 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
701 }
702 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700703 buildFile := findBuildFile(ctx, dir)
704 if buildFile == "" {
705 ctx.Fatalf("Build file not found for %s directory", dir)
706 }
707 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700708 }
709
Patrice Arruda13848222019-04-22 17:12:02 -0700710 targets = append(targets, newTargets...)
711 }
712
Dan Willemsence41e942019-07-29 23:39:30 -0700713 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700714}
715
Dan Willemsen9b587492017-07-10 22:13:00 -0700716func (c *configImpl) parseArgs(ctx Context, args []string) {
717 for i := 0; i < len(args); i++ {
718 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100719 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700720 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200721 } else if arg == "--empty-ninja-file" {
722 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100723 } else if arg == "--skip-ninja" {
724 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700725 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700726 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
727 // but it does run a Kati ninja file if the .kati_enabled marker file was created
728 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000729 c.skipConfig = true
730 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100731 } else if arg == "--soong-only" {
732 c.skipKati = true
733 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200734 } else if arg == "--config-only" {
735 c.skipKati = true
736 c.skipKatiNinja = true
737 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700738 } else if arg == "--skip-config" {
739 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700740 } else if arg == "--skip-soong-tests" {
741 c.skipSoongTests = true
MarkDacekd0e7cd32022-12-02 22:22:40 +0000742 } else if arg == "--skip-metrics-upload" {
743 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500744 } else if arg == "--mk-metrics" {
745 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000746 } else if arg == "--multitree-build" {
747 c.multitreeBuild = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400748 } else if arg == "--bazel-mode" {
749 c.bazelProdMode = true
750 } else if arg == "--bazel-mode-dev" {
751 c.bazelDevMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000752 } else if arg == "--bazel-mode-staging" {
753 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000754 } else if arg == "--search-api-dir" {
755 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900756 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
757 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
758 if source == "ninja_log" {
759 c.ninjaWeightListSource = NINJA_LOG
760 } else if source == "evenly_distributed" {
761 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
762 } else if source == "not_used" {
763 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900764 } else if source == "soong" {
765 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900766 } else if strings.HasPrefix(source, "file,") {
767 c.ninjaWeightListSource = EXTERNAL_FILE
768 filePath := strings.TrimPrefix(source, "file,")
769 err := validateNinjaWeightList(filePath)
770 if err != nil {
771 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
772 }
773 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
774 if err != nil {
775 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
776 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900777 } else {
778 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
779 }
Jihoon Kang1bff0342023-01-17 20:40:22 +0000780 } else if arg == "--build-from-text-stub" {
781 c.buildFromTextStub = true
MarkDacekb96561e2022-12-02 04:34:43 +0000782 } else if strings.HasPrefix(arg, "--build-command=") {
783 buildCmd := strings.TrimPrefix(arg, "--build-command=")
784 // remove quotations
785 buildCmd = strings.TrimPrefix(buildCmd, "\"")
786 buildCmd = strings.TrimSuffix(buildCmd, "\"")
787 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000788 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
789 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
MarkDacek6614d9c2022-12-07 21:57:38 +0000790 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
791 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
792 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
793 if err == nil {
794 c.buildStartedTime = val
795 } else {
796 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
797 }
MarkDacekf47e1422023-04-19 16:47:36 +0000798 } else if arg == "--ensure-allowlist-integrity" {
799 c.ensureAllowlistIntegrity = true
MarkDacekd33c2fd2023-05-04 20:40:04 +0000800 } else if strings.HasPrefix(arg, "--bazel-exit-code=") {
801 bazelExitCodeStr := strings.TrimPrefix(arg, "--bazel-exit-code=")
802 val, err := strconv.Atoi(bazelExitCodeStr)
803 if err == nil {
804 c.bazelExitCode = int32(val)
805 } else {
806 ctx.Fatalf("Error parsing bazel-exit-code", err)
807 }
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700808 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700809 parseArgNum := func(def int) int {
810 if len(arg) > 2 {
811 p, err := strconv.ParseUint(arg[2:], 10, 31)
812 if err != nil {
813 ctx.Fatalf("Failed to parse %q: %v", arg, err)
814 }
815 return int(p)
816 } else if i+1 < len(args) {
817 p, err := strconv.ParseUint(args[i+1], 10, 31)
818 if err == nil {
819 i++
820 return int(p)
821 }
822 }
823 return def
824 }
825
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700826 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700827 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700828 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700829 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700830 } else {
831 ctx.Fatalln("Unknown option:", arg)
832 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700833 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700834 if k == "OUT_DIR" {
835 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
836 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700837 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700838 } else if arg == "dist" {
839 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200840 } else if arg == "json-module-graph" {
841 c.jsonModuleGraph = true
842 } else if arg == "bp2build" {
843 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000844 } else if arg == "api_bp2build" {
845 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200846 } else if arg == "queryview" {
847 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200848 } else if arg == "soong_docs" {
849 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700850 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700851 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800852 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700853 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700854 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700855 }
856 }
Chris Parsonsb6e96902022-10-31 20:08:45 -0400857 if (!c.bazelProdMode) && (!c.bazelDevMode) && (!c.bazelStagingMode) {
858 c.bazelProdMode = defaultBazelProdMode(c)
859 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700860}
861
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900862func validateNinjaWeightList(weightListFilePath string) (err error) {
863 data, err := os.ReadFile(weightListFilePath)
864 if err != nil {
865 return
866 }
867 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
868 for _, line := range lines {
869 fields := strings.Split(line, ",")
870 if len(fields) != 2 {
871 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
872 }
873 _, err = strconv.Atoi(fields[1])
874 if err != nil {
875 return
876 }
877 }
878 return
879}
880
Dan Willemsened869522018-01-08 14:58:46 -0800881func (c *configImpl) configureLocale(ctx Context) {
882 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
883 output, err := cmd.Output()
884
885 var locales []string
886 if err == nil {
887 locales = strings.Split(string(output), "\n")
888 } else {
889 // If we're unable to list the locales, let's assume en_US.UTF-8
890 locales = []string{"en_US.UTF-8"}
891 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
892 }
893
894 // gettext uses LANGUAGE, which is passed directly through
895
896 // For LANG and LC_*, only preserve the evaluated version of
897 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800898 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800899 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800900 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800901 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800902 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800903 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800904 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800905 }
906
907 c.environ.UnsetWithPrefix("LC_")
908
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800909 if userLang != "" {
910 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800911 }
912
913 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
914 // for others)
915 if inList("C.UTF-8", locales) {
916 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500917 } else if inList("C.utf8", locales) {
918 // These normalize to the same thing
919 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800920 } else if inList("en_US.UTF-8", locales) {
921 c.environ.Set("LANG", "en_US.UTF-8")
922 } else if inList("en_US.utf8", locales) {
923 // These normalize to the same thing
924 c.environ.Set("LANG", "en_US.UTF-8")
925 } else {
926 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
927 }
928}
929
Dan Willemsen1e704462016-08-21 15:17:17 -0700930func (c *configImpl) Environment() *Environment {
931 return c.environ
932}
933
934func (c *configImpl) Arguments() []string {
935 return c.arguments
936}
937
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200938func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200939 if len(c.Arguments()) > 0 {
940 // Explicit targets requested that are not special targets like b2pbuild
941 // or the JSON module graph
942 return true
943 }
944
Spandan Das5af0bd32022-09-28 20:43:08 +0000945 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200946 // Command line was empty, the default Ninja target is built
947 return true
948 }
949
Liz Kammer88677422021-12-15 15:03:19 -0500950 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
951 if c.Dist() && !c.Bp2Build() {
952 return true
953 }
954
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200955 // build.ninja doesn't need to be generated
956 return false
957}
958
Dan Willemsen1e704462016-08-21 15:17:17 -0700959func (c *configImpl) OutDir() string {
960 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700961 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700962 }
963 return "out"
964}
965
Dan Willemsen8a073a82017-02-04 17:30:44 -0800966func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400967 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000968}
969
970func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700971 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800972}
973
Dan Willemsen1e704462016-08-21 15:17:17 -0700974func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000975 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700976 return c.arguments
977 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700978 return c.ninjaArgs
979}
980
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500981func (c *configImpl) BazelOutDir() string {
982 return filepath.Join(c.OutDir(), "bazel")
983}
984
Liz Kammer2af5ea82022-11-11 14:21:03 -0500985func (c *configImpl) bazelOutputBase() string {
986 return filepath.Join(c.BazelOutDir(), "output")
987}
988
Dan Willemsen1e704462016-08-21 15:17:17 -0700989func (c *configImpl) SoongOutDir() string {
990 return filepath.Join(c.OutDir(), "soong")
991}
992
Spandan Das394aa322022-11-03 17:02:10 +0000993func (c *configImpl) ApiSurfacesOutDir() string {
994 return filepath.Join(c.OutDir(), "api_surfaces")
995}
996
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200997func (c *configImpl) PrebuiltOS() string {
998 switch runtime.GOOS {
999 case "linux":
1000 return "linux-x86"
1001 case "darwin":
1002 return "darwin-x86"
1003 default:
1004 panic("Unknown GOOS")
1005 }
1006}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001007
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001008func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001009 if c.SkipKatiNinja() {
1010 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1011 } else {
1012 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1013 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001014}
1015
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001016func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001017 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001018}
1019
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001020func (c *configImpl) UsedEnvFile(tag string) string {
1021 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1022}
1023
Lukacs T. Berkic541cd22022-10-26 07:26:50 +00001024func (c *configImpl) Bp2BuildFilesMarkerFile() string {
1025 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
1026}
1027
1028func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001029 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +02001030}
1031
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001032func (c *configImpl) SoongDocsHtml() string {
1033 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1034}
1035
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001036func (c *configImpl) QueryviewMarkerFile() string {
1037 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1038}
1039
Spandan Das5af0bd32022-09-28 20:43:08 +00001040func (c *configImpl) ApiBp2buildMarkerFile() string {
1041 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
1042}
1043
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001044func (c *configImpl) ModuleGraphFile() string {
1045 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1046}
1047
kgui67007242022-01-25 13:50:25 +08001048func (c *configImpl) ModuleActionsFile() string {
1049 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1050}
1051
Jeff Gastonefc1b412017-03-29 17:29:06 -07001052func (c *configImpl) TempDir() string {
1053 return shared.TempDirForOutDir(c.SoongOutDir())
1054}
1055
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001056func (c *configImpl) FileListDir() string {
1057 return filepath.Join(c.OutDir(), ".module_paths")
1058}
1059
Dan Willemsen1e704462016-08-21 15:17:17 -07001060func (c *configImpl) KatiSuffix() string {
1061 if c.katiSuffix != "" {
1062 return c.katiSuffix
1063 }
1064 panic("SetKatiSuffix has not been called")
1065}
1066
Colin Cross37193492017-11-16 17:55:00 -08001067// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1068// user is interested in additional checks at the expense of build time.
1069func (c *configImpl) Checkbuild() bool {
1070 return c.checkbuild
1071}
1072
Dan Willemsen8a073a82017-02-04 17:30:44 -08001073func (c *configImpl) Dist() bool {
1074 return c.dist
1075}
1076
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001077func (c *configImpl) JsonModuleGraph() bool {
1078 return c.jsonModuleGraph
1079}
1080
1081func (c *configImpl) Bp2Build() bool {
1082 return c.bp2build
1083}
1084
Spandan Das5af0bd32022-09-28 20:43:08 +00001085func (c *configImpl) ApiBp2build() bool {
1086 return c.apiBp2build
1087}
1088
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001089func (c *configImpl) Queryview() bool {
1090 return c.queryview
1091}
1092
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001093func (c *configImpl) SoongDocs() bool {
1094 return c.soongDocs
1095}
1096
Dan Willemsen1e704462016-08-21 15:17:17 -07001097func (c *configImpl) IsVerbose() bool {
1098 return c.verbose
1099}
1100
LaMont Jones52a72432023-03-09 18:19:35 +00001101func (c *configImpl) MultitreeBuild() bool {
1102 return c.multitreeBuild
1103}
1104
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001105func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1106 return c.ninjaWeightListSource
1107}
1108
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001109func (c *configImpl) SkipKati() bool {
1110 return c.skipKati
1111}
1112
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001113func (c *configImpl) SkipKatiNinja() bool {
1114 return c.skipKatiNinja
1115}
1116
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001117func (c *configImpl) SkipSoong() bool {
1118 return c.skipSoong
1119}
1120
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001121func (c *configImpl) SkipNinja() bool {
1122 return c.skipNinja
1123}
1124
Anton Hansson5a7861a2021-06-04 10:09:01 +01001125func (c *configImpl) SetSkipNinja(v bool) {
1126 c.skipNinja = v
1127}
1128
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001129func (c *configImpl) SkipConfig() bool {
1130 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001131}
1132
Jihoon Kang1bff0342023-01-17 20:40:22 +00001133func (c *configImpl) BuildFromTextStub() bool {
1134 return c.buildFromTextStub
1135}
1136
Dan Willemsen1e704462016-08-21 15:17:17 -07001137func (c *configImpl) TargetProduct() string {
1138 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1139 return v
1140 }
1141 panic("TARGET_PRODUCT is not defined")
1142}
1143
Dan Willemsen02781d52017-05-12 19:28:13 -07001144func (c *configImpl) TargetDevice() string {
1145 return c.targetDevice
1146}
1147
1148func (c *configImpl) SetTargetDevice(device string) {
1149 c.targetDevice = device
1150}
1151
1152func (c *configImpl) TargetBuildVariant() string {
1153 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1154 return v
1155 }
1156 panic("TARGET_BUILD_VARIANT is not defined")
1157}
1158
Dan Willemsen1e704462016-08-21 15:17:17 -07001159func (c *configImpl) KatiArgs() []string {
1160 return c.katiArgs
1161}
1162
1163func (c *configImpl) Parallel() int {
1164 return c.parallel
1165}
1166
Sam Delmerico98a73292023-02-21 11:50:29 -05001167func (c *configImpl) GetSourceRootDirs() []string {
1168 return c.sourceRootDirs
1169}
1170
1171func (c *configImpl) SetSourceRootDirs(i []string) {
1172 c.sourceRootDirs = i
1173}
1174
Spandan Dasc5763832022-11-08 18:42:16 +00001175func (c *configImpl) GetIncludeTags() []string {
1176 return c.includeTags
1177}
1178
1179func (c *configImpl) SetIncludeTags(i []string) {
1180 c.includeTags = i
1181}
1182
MarkDacek6614d9c2022-12-07 21:57:38 +00001183func (c *configImpl) GetLogsPrefix() string {
1184 return c.logsPrefix
1185}
1186
1187func (c *configImpl) SetLogsPrefix(prefix string) {
1188 c.logsPrefix = prefix
1189}
1190
Colin Cross8b8bec32019-11-15 13:18:43 -08001191func (c *configImpl) HighmemParallel() int {
1192 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1193 return i
1194 }
1195
1196 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1197 parallel := c.Parallel()
1198 if c.UseRemoteBuild() {
1199 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1200 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1201 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1202 // Return 1/16th of the size of the local pool, rounding up.
1203 return (parallel + 15) / 16
1204 } else if c.totalRAM == 0 {
1205 // Couldn't detect the total RAM, don't restrict highmem processes.
1206 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001207 } else if c.totalRAM <= 16*1024*1024*1024 {
1208 // Less than 16GB of ram, restrict to 1 highmem processes
1209 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001210 } else if c.totalRAM <= 32*1024*1024*1024 {
1211 // Less than 32GB of ram, restrict to 2 highmem processes
1212 return 2
1213 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1214 // If less than 8GB total RAM per process, reduce the number of highmem processes
1215 return p
1216 }
1217 // No restriction on highmem processes
1218 return parallel
1219}
1220
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001221func (c *configImpl) TotalRAM() uint64 {
1222 return c.totalRAM
1223}
1224
Kousik Kumarec478642020-09-21 13:39:24 -04001225// ForceUseGoma determines whether we should override Goma deprecation
1226// and use Goma for the current build or not.
1227func (c *configImpl) ForceUseGoma() bool {
1228 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1229 v = strings.TrimSpace(v)
1230 if v != "" && v != "false" {
1231 return true
1232 }
1233 }
1234 return false
1235}
1236
Dan Willemsen1e704462016-08-21 15:17:17 -07001237func (c *configImpl) UseGoma() bool {
1238 if v, ok := c.environ.Get("USE_GOMA"); ok {
1239 v = strings.TrimSpace(v)
1240 if v != "" && v != "false" {
1241 return true
1242 }
1243 }
1244 return false
1245}
1246
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001247func (c *configImpl) StartGoma() bool {
1248 if !c.UseGoma() {
1249 return false
1250 }
1251
1252 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1253 v = strings.TrimSpace(v)
1254 if v != "" && v != "false" {
1255 return false
1256 }
1257 }
1258 return true
1259}
1260
Ramy Medhatbbf25672019-07-17 12:30:04 +00001261func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001262 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001263 v = strings.TrimSpace(v)
1264 if v != "" && v != "false" {
1265 return true
1266 }
1267 }
1268 return false
1269}
1270
Chris Parsonsef615e52022-08-18 22:04:11 -04001271func (c *configImpl) BazelBuildEnabled() bool {
MarkDacekb78465d2022-10-18 20:10:16 +00001272 return c.bazelProdMode || c.bazelDevMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001273}
1274
Ramy Medhatbbf25672019-07-17 12:30:04 +00001275func (c *configImpl) StartRBE() bool {
1276 if !c.UseRBE() {
1277 return false
1278 }
1279
1280 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1281 v = strings.TrimSpace(v)
1282 if v != "" && v != "false" {
1283 return false
1284 }
1285 }
1286 return true
1287}
1288
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001289func (c *configImpl) rbeProxyLogsDir() string {
1290 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001291 if v, ok := c.environ.Get(f); ok {
1292 return v
1293 }
1294 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001295 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1296 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001297}
1298
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001299func (c *configImpl) rbeCacheDir() string {
1300 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1301 if v, ok := c.environ.Get(f); ok {
1302 return v
1303 }
1304 }
1305 return shared.JoinPath(c.SoongOutDir(), "rbe")
1306}
1307
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001308func (c *configImpl) shouldCleanupRBELogsDir() bool {
1309 // Perform a log directory cleanup only when the log directory
1310 // is auto created by the build rather than user-specified.
1311 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1312 if _, ok := c.environ.Get(f); ok {
1313 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001314 }
1315 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001316 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001317}
1318
1319func (c *configImpl) rbeExecRoot() string {
1320 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1321 if v, ok := c.environ.Get(f); ok {
1322 return v
1323 }
1324 }
1325 wd, err := os.Getwd()
1326 if err != nil {
1327 return ""
1328 }
1329 return wd
1330}
1331
1332func (c *configImpl) rbeDir() string {
1333 if v, ok := c.environ.Get("RBE_DIR"); ok {
1334 return v
1335 }
1336 return "prebuilts/remoteexecution-client/live/"
1337}
1338
1339func (c *configImpl) rbeReproxy() string {
1340 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1341 if v, ok := c.environ.Get(f); ok {
1342 return v
1343 }
1344 }
1345 return filepath.Join(c.rbeDir(), "reproxy")
1346}
1347
1348func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001349 credFlags := []string{
1350 "use_application_default_credentials",
1351 "use_gce_credentials",
1352 "credential_file",
1353 "use_google_prod_creds",
1354 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001355 for _, cf := range credFlags {
1356 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1357 if v, ok := c.environ.Get(f); ok {
1358 v = strings.TrimSpace(v)
1359 if v != "" && v != "false" && v != "0" {
1360 return "RBE_" + cf, v
1361 }
1362 }
1363 }
1364 }
1365 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001366}
1367
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001368func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1369 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1370 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1371
1372 name := filepath.Join(dir, base)
1373 if len(name) < maxNameLen {
1374 return name, nil
1375 }
1376
1377 name = filepath.Join("/tmp", base)
1378 if len(name) < maxNameLen {
1379 return name, nil
1380 }
1381
1382 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1383}
1384
Kousik Kumar7bc78192022-04-27 14:52:56 -04001385// IsGooglerEnvironment returns true if the current build is running
1386// on a Google developer machine and false otherwise.
1387func (c *configImpl) IsGooglerEnvironment() bool {
1388 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1389 if v, ok := c.environ.Get(cf); ok {
1390 return v == "googler"
1391 }
1392 return false
1393}
1394
1395// GoogleProdCredsExist determine whether credentials exist on the
1396// Googler machine to use remote execution.
1397func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001398 if googleProdCredsExistCache {
1399 return googleProdCredsExistCache
1400 }
Kousik Kumar7bc78192022-04-27 14:52:56 -04001401 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1402 return false
1403 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001404 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001405 return true
1406}
1407
1408// UseRemoteBuild indicates whether to use a remote build acceleration system
1409// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001410func (c *configImpl) UseRemoteBuild() bool {
1411 return c.UseGoma() || c.UseRBE()
1412}
1413
Kousik Kumar7bc78192022-04-27 14:52:56 -04001414// StubbyExists checks whether the stubby binary exists on the machine running
1415// the build.
1416func (c *configImpl) StubbyExists() bool {
1417 if _, err := exec.LookPath("stubby"); err != nil {
1418 return false
1419 }
1420 return true
1421}
1422
Dan Willemsen1e704462016-08-21 15:17:17 -07001423// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001424// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001425// still limited by Parallel()
1426func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001427 if !c.UseRemoteBuild() {
1428 return 0
1429 }
1430 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1431 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001432 }
1433 return 500
1434}
1435
1436func (c *configImpl) SetKatiArgs(args []string) {
1437 c.katiArgs = args
1438}
1439
1440func (c *configImpl) SetNinjaArgs(args []string) {
1441 c.ninjaArgs = args
1442}
1443
1444func (c *configImpl) SetKatiSuffix(suffix string) {
1445 c.katiSuffix = suffix
1446}
1447
Dan Willemsene0879fc2017-08-04 15:06:27 -07001448func (c *configImpl) LastKatiSuffixFile() string {
1449 return filepath.Join(c.OutDir(), "last_kati_suffix")
1450}
1451
1452func (c *configImpl) HasKatiSuffix() bool {
1453 return c.katiSuffix != ""
1454}
1455
Dan Willemsen1e704462016-08-21 15:17:17 -07001456func (c *configImpl) KatiEnvFile() string {
1457 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1458}
1459
Dan Willemsen29971232018-09-26 14:58:30 -07001460func (c *configImpl) KatiBuildNinjaFile() string {
1461 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001462}
1463
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001464func (c *configImpl) KatiPackageNinjaFile() string {
1465 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1466}
1467
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001468func (c *configImpl) SoongVarsFile() string {
1469 return filepath.Join(c.SoongOutDir(), "soong.variables")
1470}
1471
Dan Willemsen1e704462016-08-21 15:17:17 -07001472func (c *configImpl) SoongNinjaFile() string {
1473 return filepath.Join(c.SoongOutDir(), "build.ninja")
1474}
1475
1476func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001477 if c.katiSuffix == "" {
1478 return filepath.Join(c.OutDir(), "combined.ninja")
1479 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001480 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1481}
1482
1483func (c *configImpl) SoongAndroidMk() string {
1484 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1485}
1486
1487func (c *configImpl) SoongMakeVarsMk() string {
1488 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1489}
1490
Dan Willemsenf052f782017-05-18 15:29:04 -07001491func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001492 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001493}
1494
Dan Willemsen02781d52017-05-12 19:28:13 -07001495func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001496 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1497}
1498
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001499func (c *configImpl) KatiPackageMkDir() string {
1500 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1501}
1502
Dan Willemsenf052f782017-05-18 15:29:04 -07001503func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001504 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001505}
1506
1507func (c *configImpl) HostOut() string {
1508 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1509}
1510
1511// This probably needs to be multi-valued, so not exporting it for now
1512func (c *configImpl) hostCrossOut() string {
1513 if runtime.GOOS == "linux" {
1514 return filepath.Join(c.hostOutRoot(), "windows-x86")
1515 } else {
1516 return ""
1517 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001518}
1519
Dan Willemsen1e704462016-08-21 15:17:17 -07001520func (c *configImpl) HostPrebuiltTag() string {
1521 if runtime.GOOS == "linux" {
1522 return "linux-x86"
1523 } else if runtime.GOOS == "darwin" {
1524 return "darwin-x86"
1525 } else {
1526 panic("Unsupported OS")
1527 }
1528}
Dan Willemsenf173d592017-04-27 14:28:00 -07001529
Dan Willemsen8122bd52017-10-12 20:20:41 -07001530func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001531 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1532 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001533 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1534 if _, err := os.Stat(asan); err == nil {
1535 return asan
1536 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001537 }
1538 }
1539 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1540}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001541
1542func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1543 c.brokenDupRules = val
1544}
1545
1546func (c *configImpl) BuildBrokenDupRules() bool {
1547 return c.brokenDupRules
1548}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001549
Dan Willemsen25e6f092019-04-09 10:22:43 -07001550func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1551 c.brokenUsesNetwork = val
1552}
1553
1554func (c *configImpl) BuildBrokenUsesNetwork() bool {
1555 return c.brokenUsesNetwork
1556}
1557
Dan Willemsene3336352020-01-02 19:10:38 -08001558func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1559 c.brokenNinjaEnvVars = val
1560}
1561
1562func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1563 return c.brokenNinjaEnvVars
1564}
1565
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001566func (c *configImpl) SetTargetDeviceDir(dir string) {
1567 c.targetDeviceDir = dir
1568}
1569
1570func (c *configImpl) TargetDeviceDir() string {
1571 return c.targetDeviceDir
1572}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001573
Patrice Arruda219eef32020-06-01 17:29:30 +00001574func (c *configImpl) BuildDateTime() string {
1575 return c.buildDateTime
1576}
1577
1578func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001579 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001580}
Patrice Arruda83842d72020-12-08 19:42:08 +00001581
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001582// LogsDir returns the absolute path to the logs directory where build log and
1583// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001584// directory. If the argument dist is specified, the logs directory
1585// is <dist_dir>/logs.
1586func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001587 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001588 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001589 // 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 -05001590 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001591 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001592 absDir, err := filepath.Abs(dir)
1593 if err != nil {
1594 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1595 os.Exit(1)
1596 }
1597 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001598}
1599
1600// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1601// where the bazel profiles are located.
1602func (c *configImpl) BazelMetricsDir() string {
1603 return filepath.Join(c.LogsDir(), "bazel_metrics")
1604}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001605
Chris Parsons53f68ae2022-03-03 12:01:40 -05001606// MkFileMetrics returns the file path for make-related metrics.
1607func (c *configImpl) MkMetrics() string {
1608 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1609}
1610
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001611func (c *configImpl) SetEmptyNinjaFile(v bool) {
1612 c.emptyNinjaFile = v
1613}
1614
1615func (c *configImpl) EmptyNinjaFile() bool {
1616 return c.emptyNinjaFile
1617}
Yu Liu6e13b402021-07-27 14:29:06 -07001618
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001619func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1620 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1621}
1622
Chris Parsons9402ca82023-02-23 17:28:06 -05001623func (c *configImpl) IsPersistentBazelEnabled() bool {
1624 return c.Environment().IsEnvTrue("USE_PERSISTENT_BAZEL")
1625}
1626
MarkDacekd06db5d2022-11-29 00:47:59 +00001627func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1628 return c.bazelForceEnabledModules
1629}
1630
MarkDacekd0e7cd32022-12-02 22:22:40 +00001631func (c *configImpl) SkipMetricsUpload() bool {
1632 return c.skipMetricsUpload
1633}
1634
MarkDacekf47e1422023-04-19 16:47:36 +00001635func (c *configImpl) EnsureAllowlistIntegrity() bool {
1636 return c.ensureAllowlistIntegrity
1637}
1638
MarkDacek6614d9c2022-12-07 21:57:38 +00001639// Returns a Time object if one was passed via a command-line flag.
1640// Otherwise returns the passed default.
1641func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1642 if c.buildStartedTime == 0 {
1643 return defaultTime
1644 }
1645 return time.UnixMilli(c.buildStartedTime)
1646}
1647
MarkDacekd33c2fd2023-05-04 20:40:04 +00001648func (c *configImpl) BazelExitCode() int32 {
1649 return c.bazelExitCode
1650}
1651
Yu Liu6e13b402021-07-27 14:29:06 -07001652func GetMetricsUploader(topDir string, env *Environment) string {
1653 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1654 metricsUploader := filepath.Join(topDir, p)
1655 if _, err := os.Stat(metricsUploader); err == nil {
1656 return metricsUploader
1657 }
1658 }
1659
1660 return ""
1661}