blob: e6427723d207a284296ededd62a912c518dfd92e [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 Kumard93c67f2023-05-30 20:23:57 +000018 "context"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050019 "encoding/json"
Jeongik Chaa87506f2023-06-01 23:16:41 +090020 "errors"
Ramy Medhat0fc67eb2020-08-12 01:26:23 -040021 "fmt"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050022 "io/ioutil"
Kousik Kumar4c180ad2022-05-27 07:48:37 -040023 "math/rand"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080024 "os"
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050025 "os/exec"
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"
Kousik Kumarec478642020-09-21 13:39:24 -040034
Dan Willemsen4591b642021-05-24 14:24:12 -070035 "google.golang.org/protobuf/proto"
Patrice Arruda96850362020-08-11 20:41:11 +000036
37 smpb "android/soong/ui/metrics/metrics_proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070038)
39
Kousik Kumar3ff037e2022-01-25 22:11:01 -050040const (
Chris Parsons53f68ae2022-03-03 12:01:40 -050041 envConfigDir = "vendor/google/tools/soong_config"
42 jsonSuffix = "json"
Kousik Kumard93c67f2023-05-30 20:23:57 +000043
44 configFetcher = "vendor/google/tools/soong/expconfigfetcher"
Kousik Kumara3a2af62023-06-06 17:29:11 -040045 envConfigFetchTimeout = 20 * time.Second
Kousik Kumar3ff037e2022-01-25 22:11:01 -050046)
47
Kousik Kumar4c180ad2022-05-27 07:48:37 -040048var (
Kevin Dagostino096ab2f2023-03-03 19:47:17 +000049 rbeRandPrefix int
50 googleProdCredsExistCache bool
Kousik Kumar4c180ad2022-05-27 07:48:37 -040051)
52
53func init() {
54 rand.Seed(time.Now().UnixNano())
55 rbeRandPrefix = rand.Intn(1000)
56}
57
Dan Willemsen1e704462016-08-21 15:17:17 -070058type Config struct{ *configImpl }
59
60type configImpl struct {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020061 // Some targets that are implemented in soong_build
62 // (bp2build, json-module-graph) are not here and have their own bits below.
Colin Cross28f527c2019-11-26 16:19:04 -080063 arguments []string
64 goma bool
65 environ *Environment
66 distDir string
67 buildDateTime string
MarkDacek6614d9c2022-12-07 21:57:38 +000068 logsPrefix string
Dan Willemsen1e704462016-08-21 15:17:17 -070069
70 // From the arguments
MarkDacekf47e1422023-04-19 16:47:36 +000071 parallel int
72 keepGoing int
73 verbose bool
74 checkbuild bool
75 dist bool
76 jsonModuleGraph bool
77 apiBp2build bool // Generate BUILD files for Soong modules that contribute APIs
78 bp2build bool
79 queryview bool
80 reportMkMetrics bool // Collect and report mk2bp migration progress metrics.
81 soongDocs bool
82 multitreeBuild bool // This is a multitree build.
83 skipConfig bool
84 skipKati bool
85 skipKatiNinja bool
86 skipSoong bool
87 skipNinja bool
88 skipSoongTests bool
89 searchApiDir bool // Scan the Android.bp files generated in out/api_surfaces
90 skipMetricsUpload bool
91 buildStartedTime int64 // For metrics-upload-only - manually specify a build-started time
92 buildFromTextStub bool
MarkDacek396491e2023-06-14 19:41:18 +000093 ensureAllowlistIntegrity bool // For CI builds - make sure modules are mixed-built
94 bazelExitCode int32 // For b runs - necessary for updating NonZeroExit
95 besId string // For b runs, to identify the BuildEventService logs
Dan Willemsen1e704462016-08-21 15:17:17 -070096
97 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070098 katiArgs []string
99 ninjaArgs []string
100 katiSuffix string
101 targetDevice string
102 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +0000103 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -0700104
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800105 // Autodetected
106 totalRAM uint64
107
Dan Willemsene3336352020-01-02 19:10:38 -0800108 brokenDupRules bool
109 brokenUsesNetwork bool
110 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -0700111
112 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000113
MarkDacekb78465d2022-10-18 20:10:16 +0000114 bazelProdMode bool
MarkDacekb78465d2022-10-18 20:10:16 +0000115 bazelStagingMode bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000116
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700117 // Set by multiproduct_kati
118 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700119
120 metricsUploader string
MarkDacekd06db5d2022-11-29 00:47:59 +0000121
122 bazelForceEnabledModules string
Spandan Dasc5763832022-11-08 18:42:16 +0000123
Sam Delmerico98a73292023-02-21 11:50:29 -0500124 includeTags []string
125 sourceRootDirs []string
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900126
127 // Data source to write ninja weight list
128 ninjaWeightListSource NinjaWeightListSource
Dan Willemsen1e704462016-08-21 15:17:17 -0700129}
130
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900131type NinjaWeightListSource uint
132
133const (
134 // ninja doesn't use weight list.
135 NOT_USED NinjaWeightListSource = iota
136 // ninja uses weight list based on previous builds by ninja log
137 NINJA_LOG
138 // ninja thinks every task has the same weight.
139 EVENLY_DISTRIBUTED
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900140 // ninja uses an external custom weight list
141 EXTERNAL_FILE
Jeongik Chae114e602023-03-19 00:12:39 +0900142 // ninja uses a prioritized module list from Soong
143 HINT_FROM_SOONG
Jeongik Chaa87506f2023-06-01 23:16:41 +0900144 // If ninja log exists, use NINJA_LOG, if not, use HINT_FROM_SOONG instead.
145 // We can assume it is an incremental build if ninja log exists.
146 DEFAULT
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900147)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800148const srcDirFileCheck = "build/soong/root.bp"
149
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700150var buildFiles = []string{"Android.mk", "Android.bp"}
151
Patrice Arruda13848222019-04-22 17:12:02 -0700152type BuildAction uint
153
154const (
155 // Builds all of the modules and their dependencies of a specified directory, relative to the root
156 // directory of the source tree.
157 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
158
159 // Builds all of the modules and their dependencies of a list of specified directories. All specified
160 // directories are relative to the root directory of the source tree.
161 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700162
163 // Build a list of specified modules. If none was specified, simply build the whole source tree.
164 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700165)
166
167// checkTopDir validates that the current directory is at the root directory of the source tree.
168func checkTopDir(ctx Context) {
169 if _, err := os.Stat(srcDirFileCheck); err != nil {
170 if os.IsNotExist(err) {
171 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
172 }
173 ctx.Fatalln("Error verifying tree state:", err)
174 }
175}
176
Kousik Kumard93c67f2023-05-30 20:23:57 +0000177// fetchEnvConfig optionally fetches a configuration file that can then subsequently be
178// loaded into Soong environment to control certain aspects of build behavior (e.g., enabling RBE).
179// If a configuration file already exists on disk, the fetch is run in the background
180// so as to NOT block the rest of the build execution.
181func fetchEnvConfig(ctx Context, config *configImpl, envConfigName string) error {
182 configName := envConfigName + "." + jsonSuffix
183 expConfigFetcher := &smpb.ExpConfigFetcher{Filename: &configName}
184 defer func() {
185 ctx.Metrics.ExpConfigFetcher(expConfigFetcher)
186 }()
187 if !config.GoogleProdCredsExist() {
188 status := smpb.ExpConfigFetcher_MISSING_GCERT
189 expConfigFetcher.Status = &status
190 return nil
191 }
192
193 s, err := os.Stat(configFetcher)
194 if err != nil {
195 if os.IsNotExist(err) {
196 return nil
197 }
198 return err
199 }
200 if s.Mode()&0111 == 0 {
201 status := smpb.ExpConfigFetcher_ERROR
202 expConfigFetcher.Status = &status
203 return fmt.Errorf("configuration fetcher binary %v is not executable: %v", configFetcher, s.Mode())
204 }
205
206 configExists := false
207 outConfigFilePath := filepath.Join(config.OutDir(), configName)
208 if _, err := os.Stat(outConfigFilePath); err == nil {
209 configExists = true
210 }
211
212 tCtx, cancel := context.WithTimeout(ctx, envConfigFetchTimeout)
213 fetchStart := time.Now()
214 cmd := exec.CommandContext(tCtx, configFetcher, "-output_config_dir", config.OutDir(),
215 "-output_config_name", configName)
216 if err := cmd.Start(); err != nil {
217 status := smpb.ExpConfigFetcher_ERROR
218 expConfigFetcher.Status = &status
219 return err
220 }
221
222 fetchCfg := func() error {
223 if err := cmd.Wait(); err != nil {
224 status := smpb.ExpConfigFetcher_ERROR
225 expConfigFetcher.Status = &status
226 return err
227 }
228 fetchEnd := time.Now()
229 expConfigFetcher.Micros = proto.Uint64(uint64(fetchEnd.Sub(fetchStart).Microseconds()))
230 expConfigFetcher.Filename = proto.String(outConfigFilePath)
231
232 if _, err := os.Stat(outConfigFilePath); err != nil {
233 status := smpb.ExpConfigFetcher_NO_CONFIG
234 expConfigFetcher.Status = &status
235 return err
236 }
237 status := smpb.ExpConfigFetcher_CONFIG
238 expConfigFetcher.Status = &status
239 return nil
240 }
241
242 // If a config file does not exist, wait for the config file to be fetched. Otherwise
243 // fetch the config file in the background and return immediately.
244 if !configExists {
245 defer cancel()
246 return fetchCfg()
247 }
248
249 go func() {
250 defer cancel()
251 if err := fetchCfg(); err != nil {
252 ctx.Verbosef("Failed to fetch config file %v: %v\n", configName, err)
253 }
254 }()
255 return nil
256}
257
MarkDacek7901e582023-01-09 19:48:01 +0000258func loadEnvConfig(ctx Context, config *configImpl, bc string) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500259 if bc == "" {
260 return nil
261 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500262
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500263 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500264 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500265 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500266 envConfigDir,
267 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500268 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500269 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
270 envVarsJSON, err := ioutil.ReadFile(cfgFile)
271 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500272 continue
273 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500274 ctx.Verbosef("Loading config file %v\n", cfgFile)
275 var envVars map[string]map[string]string
276 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
277 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
278 continue
279 }
280 for k, v := range envVars["env"] {
281 if os.Getenv(k) != "" {
282 continue
283 }
284 config.environ.Set(k, v)
285 }
286 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
287 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500288 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500289
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500290 return nil
291}
292
Chris Parsonsb6e96902022-10-31 20:08:45 -0400293func defaultBazelProdMode(cfg *configImpl) bool {
MarkDacekd06db5d2022-11-29 00:47:59 +0000294 // Environment flag to disable Bazel for users which experience
Chris Parsonsb6e96902022-10-31 20:08:45 -0400295 // broken bazel-handled builds, or significant performance regressions.
296 if cfg.IsBazelMixedBuildForceDisabled() {
297 return false
298 }
299 // Darwin-host builds are currently untested with Bazel.
300 if runtime.GOOS == "darwin" {
301 return false
302 }
Chris Parsons035e03a2022-11-01 14:25:45 -0400303 return true
Chris Parsonsb6e96902022-10-31 20:08:45 -0400304}
305
MarkDacekd33c2fd2023-05-04 20:40:04 +0000306func UploadOnlyConfig(ctx Context, args ...string) Config {
MarkDacek6614d9c2022-12-07 21:57:38 +0000307 ret := &configImpl{
308 environ: OsEnvironment(),
309 sandboxConfig: &SandboxConfig{},
310 }
MarkDacekd33c2fd2023-05-04 20:40:04 +0000311 ret.parseArgs(ctx, args)
MarkDacek7901e582023-01-09 19:48:01 +0000312 srcDir := absPath(ctx, ".")
313 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
314 if err := loadEnvConfig(ctx, ret, bc); err != nil {
315 ctx.Fatalln("Failed to parse env config files: %v", err)
316 }
317 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
MarkDacek6614d9c2022-12-07 21:57:38 +0000318 return Config{ret}
319}
320
Dan Willemsen1e704462016-08-21 15:17:17 -0700321func NewConfig(ctx Context, args ...string) Config {
322 ret := &configImpl{
Jeongik Chaf2ecf762023-05-19 14:03:45 +0900323 environ: OsEnvironment(),
324 sandboxConfig: &SandboxConfig{},
Jeongik Chaa87506f2023-06-01 23:16:41 +0900325 ninjaWeightListSource: DEFAULT,
Dan Willemsen1e704462016-08-21 15:17:17 -0700326 }
327
Patrice Arruda90109172020-07-28 18:07:27 +0000328 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700329 ret.parallel = runtime.NumCPU() + 2
330 ret.keepGoing = 1
331
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800332 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700333 ret.parseArgs(ctx, args)
Jeongik Chae114e602023-03-19 00:12:39 +0900334
335 if ret.ninjaWeightListSource == HINT_FROM_SOONG {
Jeongik Chaa87506f2023-06-01 23:16:41 +0900336 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "always")
337 } else if ret.ninjaWeightListSource == DEFAULT {
338 defaultNinjaWeightListSource := NINJA_LOG
339 if _, err := os.Stat(filepath.Join(ret.OutDir(), ninjaLogFileName)); errors.Is(err, os.ErrNotExist) {
340 ctx.Verboseln("$OUT/.ninja_log doesn't exist, use HINT_FROM_SOONG instead")
341 defaultNinjaWeightListSource = HINT_FROM_SOONG
342 } else {
343 ctx.Verboseln("$OUT/.ninja_log exist, use NINJA_LOG")
344 }
345 ret.ninjaWeightListSource = defaultNinjaWeightListSource
346 // soong_build generates ninja hint depending on ninja log existence.
347 // Set it "depend" to avoid soong re-run due to env variable change.
348 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "depend")
Jeongik Chae114e602023-03-19 00:12:39 +0900349 }
Jeongik Chaa87506f2023-06-01 23:16:41 +0900350
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800351 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700352 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
353 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
354 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800355 outDir := "out"
356 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
357 if wd, err := os.Getwd(); err != nil {
358 ctx.Fatalln("Failed to get working directory:", err)
359 } else {
360 outDir = filepath.Join(baseDir, filepath.Base(wd))
361 }
362 }
363 ret.environ.Set("OUT_DIR", outDir)
364 }
365
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500366 // loadEnvConfig needs to know what the OUT_DIR is, so it should
367 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000368 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
369
370 if bc != "" {
Kousik Kumard93c67f2023-05-30 20:23:57 +0000371 if err := fetchEnvConfig(ctx, ret, bc); err != nil {
372 ctx.Verbosef("Failed to fetch config file: %v\n", err)
373 }
Kousik Kumarc8818332023-01-16 16:33:05 +0000374 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000375 ctx.Fatalln("Failed to parse env config files: %v", err)
376 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500377 }
378
Dan Willemsen2d31a442018-10-20 21:33:41 -0700379 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
380 ret.distDir = filepath.Clean(distDir)
381 } else {
382 ret.distDir = filepath.Join(ret.OutDir(), "dist")
383 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700384
Spandan Das05063612021-06-25 01:39:04 +0000385 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
386 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
387 }
388
Dan Willemsen1e704462016-08-21 15:17:17 -0700389 ret.environ.Unset(
390 // We're already using it
391 "USE_SOONG_UI",
392
393 // We should never use GOROOT/GOPATH from the shell environment
394 "GOROOT",
395 "GOPATH",
396
397 // These should only come from Soong, not the environment.
398 "CLANG",
399 "CLANG_CXX",
400 "CCC_CC",
401 "CCC_CXX",
402
403 // Used by the goma compiler wrapper, but should only be set by
404 // gomacc
405 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800406
407 // We handle this above
408 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700409
Dan Willemsen2d31a442018-10-20 21:33:41 -0700410 // This is handled above too, and set for individual commands later
411 "DIST_DIR",
412
Dan Willemsen68a09852017-04-18 13:56:57 -0700413 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000414 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700415 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700416 "DISPLAY",
417 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000418 "JAVAC",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700419 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700420 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700421
422 // Drop make flags
423 "MAKEFLAGS",
424 "MAKELEVEL",
425 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700426
427 // Set in envsetup.sh, reset in makefiles
428 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700429
430 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
431 "ANDROID_BUILD_TOP",
432 "ANDROID_HOST_OUT",
433 "ANDROID_PRODUCT_OUT",
434 "ANDROID_HOST_OUT_TESTCASES",
435 "ANDROID_TARGET_OUT_TESTCASES",
436 "ANDROID_TOOLCHAIN",
437 "ANDROID_TOOLCHAIN_2ND_ARCH",
438 "ANDROID_DEV_SCRIPTS",
439 "ANDROID_EMULATOR_PREBUILTS",
440 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700441 )
442
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400443 if ret.UseGoma() || ret.ForceUseGoma() {
444 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
445 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400446 }
447
Dan Willemsen1e704462016-08-21 15:17:17 -0700448 // Tell python not to spam the source tree with .pyc files.
449 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
450
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400451 tmpDir := absPath(ctx, ret.TempDir())
452 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800453
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700454 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
455 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
456 "llvm-binutils-stable/llvm-symbolizer")
457 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
458
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800459 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700460 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800461
Yu Liu6e13b402021-07-27 14:29:06 -0700462 srcDir := absPath(ctx, ".")
463 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700464 ctx.Println("You are building in a directory whose absolute path contains a space character:")
465 ctx.Println()
466 ctx.Printf("%q\n", srcDir)
467 ctx.Println()
468 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700469 }
470
Yu Liu6e13b402021-07-27 14:29:06 -0700471 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
472
Dan Willemsendb8457c2017-05-12 16:38:17 -0700473 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700474 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
475 ctx.Println()
476 ctx.Printf("%q\n", outDir)
477 ctx.Println()
478 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700479 }
480
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000481 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700482 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
483 ctx.Println()
484 ctx.Printf("%q\n", distDir)
485 ctx.Println()
486 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700487 }
488
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700489 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000490 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
491 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100492 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800493 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700494 javaHome := func() string {
495 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
496 return override
497 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000498 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
499 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 +0100500 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000501 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
502 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
503 }
504 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700505 }()
506 absJavaHome := absPath(ctx, javaHome)
507
Dan Willemsened869522018-01-08 14:58:46 -0800508 ret.configureLocale(ctx)
509
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700510 newPath := []string{filepath.Join(absJavaHome, "bin")}
511 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
512 newPath = append(newPath, path)
513 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100514
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700515 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
516 ret.environ.Set("JAVA_HOME", absJavaHome)
517 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000518 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
519 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100520 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700521 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
522
LaMont Jones52a72432023-03-09 18:19:35 +0000523 if ret.MultitreeBuild() {
524 ret.environ.Set("MULTITREE_BUILD", "true")
525 }
526
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800527 outDir := ret.OutDir()
528 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800529 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800530 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800531 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800532 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800533 }
Colin Cross28f527c2019-11-26 16:19:04 -0800534
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800535 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
536
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400537 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400538 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400539 ret.environ.Set(k, v)
540 }
541 }
542
Jihoon Kang1bff0342023-01-17 20:40:22 +0000543 if ret.BuildFromTextStub() {
544 // TODO(b/271443071): support hidden api check for from-text stub build
545 ret.environ.Set("UNSAFE_DISABLE_HIDDENAPI_FLAGS", "true")
546 }
547
Patrice Arruda83842d72020-12-08 19:42:08 +0000548 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800549 if err := os.RemoveAll(bpd); err != nil {
550 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
551 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000552
Patrice Arruda96850362020-08-11 20:41:11 +0000553 c := Config{ret}
554 storeConfigMetrics(ctx, c)
555 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700556}
557
Patrice Arruda13848222019-04-22 17:12:02 -0700558// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
559// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700560func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
561 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700562}
563
Patrice Arruda96850362020-08-11 20:41:11 +0000564// storeConfigMetrics selects a set of configuration information and store in
565// the metrics system for further analysis.
566func storeConfigMetrics(ctx Context, config Config) {
567 if ctx.Metrics == nil {
568 return
569 }
570
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400571 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000572
573 s := &smpb.SystemResourceInfo{
574 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
575 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
576 }
577 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000578}
579
Jeongik Cha8d63d562023-03-17 03:52:13 +0900580func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900581 switch s {
582 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900583 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900584 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900585 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900586 case EXTERNAL_FILE:
587 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900588 case HINT_FROM_SOONG:
589 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900590 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900591 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900592 }
593}
594
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400595func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700596 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400597 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
598 UseGoma: proto.Bool(config.UseGoma()),
599 UseRbe: proto.Bool(config.UseRBE()),
600 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
601 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900602 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400603 }
Yu Liue737a992021-10-04 13:21:41 -0700604 c.Targets = append(c.Targets, config.arguments...)
605
606 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400607}
608
Patrice Arruda13848222019-04-22 17:12:02 -0700609// getConfigArgs processes the command arguments based on the build action and creates a set of new
610// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700611func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700612 // The next block of code verifies that the current directory is the root directory of the source
613 // tree. It then finds the relative path of dir based on the root directory of the source tree
614 // and verify that dir is inside of the source tree.
615 checkTopDir(ctx)
616 topDir, err := os.Getwd()
617 if err != nil {
618 ctx.Fatalf("Error retrieving top directory: %v", err)
619 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700620 dir, err = filepath.EvalSymlinks(dir)
621 if err != nil {
622 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
623 }
Patrice Arruda13848222019-04-22 17:12:02 -0700624 dir, err = filepath.Abs(dir)
625 if err != nil {
626 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
627 }
628 relDir, err := filepath.Rel(topDir, dir)
629 if err != nil {
630 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
631 }
632 // If there are ".." in the path, it's not in the source tree.
633 if strings.Contains(relDir, "..") {
634 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
635 }
636
637 configArgs := args[:]
638
639 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
640 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
641 targetNamePrefix := "MODULES-IN-"
642 if inList("GET-INSTALL-PATH", configArgs) {
643 targetNamePrefix = "GET-INSTALL-PATH-IN-"
644 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
645 }
646
Patrice Arruda13848222019-04-22 17:12:02 -0700647 var targets []string
648
649 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700650 case BUILD_MODULES:
651 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700652 case BUILD_MODULES_IN_A_DIRECTORY:
653 // If dir is the root source tree, all the modules are built of the source tree are built so
654 // no need to find the build file.
655 if topDir == dir {
656 break
657 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700658
Patrice Arruda13848222019-04-22 17:12:02 -0700659 buildFile := findBuildFile(ctx, relDir)
660 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700661 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700662 }
Patrice Arruda13848222019-04-22 17:12:02 -0700663 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
664 case BUILD_MODULES_IN_DIRECTORIES:
665 newConfigArgs, dirs := splitArgs(configArgs)
666 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700667 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700668 }
669
670 // Tidy only override all other specified targets.
671 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
672 if tidyOnly == "true" || tidyOnly == "1" {
673 configArgs = append(configArgs, "tidy_only")
674 } else {
675 configArgs = append(configArgs, targets...)
676 }
677
678 return configArgs
679}
680
681// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
682func convertToTarget(dir string, targetNamePrefix string) string {
683 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
684}
685
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700686// hasBuildFile returns true if dir contains an Android build file.
687func hasBuildFile(ctx Context, dir string) bool {
688 for _, buildFile := range buildFiles {
689 _, err := os.Stat(filepath.Join(dir, buildFile))
690 if err == nil {
691 return true
692 }
693 if !os.IsNotExist(err) {
694 ctx.Fatalf("Error retrieving the build file stats: %v", err)
695 }
696 }
697 return false
698}
699
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700700// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
701// in the current and any sub directory of dir. If a build file is not found, traverse the path
702// up by one directory and repeat again until either a build file is found or reached to the root
703// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
704// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700705func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700706 // If the string is empty or ".", assume it is top directory of the source tree.
707 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700708 return ""
709 }
710
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700711 found := false
712 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
713 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
714 if err != nil {
715 return err
716 }
717 if found {
718 return filepath.SkipDir
719 }
720 if info.IsDir() {
721 return nil
722 }
723 for _, buildFile := range buildFiles {
724 if info.Name() == buildFile {
725 found = true
726 return filepath.SkipDir
727 }
728 }
729 return nil
730 })
731 if err != nil {
732 ctx.Fatalf("Error finding Android build file: %v", err)
733 }
734
735 if found {
736 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700737 }
738 }
739
740 return ""
741}
742
743// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
744func splitArgs(args []string) (newArgs []string, dirs []string) {
745 specialArgs := map[string]bool{
746 "showcommands": true,
747 "snod": true,
748 "dist": true,
749 "checkbuild": true,
750 }
751
752 newArgs = []string{}
753 dirs = []string{}
754
755 for _, arg := range args {
756 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
757 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
758 newArgs = append(newArgs, arg)
759 continue
760 }
761
762 if _, ok := specialArgs[arg]; ok {
763 newArgs = append(newArgs, arg)
764 continue
765 }
766
767 dirs = append(dirs, arg)
768 }
769
770 return newArgs, dirs
771}
772
773// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
774// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
775// source root tree where the build action command was invoked. Each directory is validated if the
776// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700777func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700778 for _, dir := range dirs {
779 // The directory may have specified specific modules to build. ":" is the separator to separate
780 // the directory and the list of modules.
781 s := strings.Split(dir, ":")
782 l := len(s)
783 if l > 2 { // more than one ":" was specified.
784 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
785 }
786
787 dir = filepath.Join(relDir, s[0])
788 if _, err := os.Stat(dir); err != nil {
789 ctx.Fatalf("couldn't find directory %s", dir)
790 }
791
792 // Verify that if there are any targets specified after ":". Each target is separated by ",".
793 var newTargets []string
794 if l == 2 && s[1] != "" {
795 newTargets = strings.Split(s[1], ",")
796 if inList("", newTargets) {
797 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
798 }
799 }
800
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700801 // If there are specified targets to build in dir, an android build file must exist for the one
802 // shot build. For the non-targets case, find the appropriate build file and build all the
803 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700804 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700805 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700806 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
807 }
808 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700809 buildFile := findBuildFile(ctx, dir)
810 if buildFile == "" {
811 ctx.Fatalf("Build file not found for %s directory", dir)
812 }
813 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700814 }
815
Patrice Arruda13848222019-04-22 17:12:02 -0700816 targets = append(targets, newTargets...)
817 }
818
Dan Willemsence41e942019-07-29 23:39:30 -0700819 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700820}
821
Dan Willemsen9b587492017-07-10 22:13:00 -0700822func (c *configImpl) parseArgs(ctx Context, args []string) {
823 for i := 0; i < len(args); i++ {
824 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100825 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700826 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200827 } else if arg == "--empty-ninja-file" {
828 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100829 } else if arg == "--skip-ninja" {
830 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700831 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700832 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
833 // but it does run a Kati ninja file if the .kati_enabled marker file was created
834 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000835 c.skipConfig = true
836 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100837 } else if arg == "--soong-only" {
838 c.skipKati = true
839 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200840 } else if arg == "--config-only" {
841 c.skipKati = true
842 c.skipKatiNinja = true
843 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700844 } else if arg == "--skip-config" {
845 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700846 } else if arg == "--skip-soong-tests" {
847 c.skipSoongTests = true
MarkDacekd0e7cd32022-12-02 22:22:40 +0000848 } else if arg == "--skip-metrics-upload" {
849 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500850 } else if arg == "--mk-metrics" {
851 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000852 } else if arg == "--multitree-build" {
853 c.multitreeBuild = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400854 } else if arg == "--bazel-mode" {
855 c.bazelProdMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000856 } else if arg == "--bazel-mode-staging" {
857 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000858 } else if arg == "--search-api-dir" {
859 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900860 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
861 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
862 if source == "ninja_log" {
863 c.ninjaWeightListSource = NINJA_LOG
864 } else if source == "evenly_distributed" {
865 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
866 } else if source == "not_used" {
867 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900868 } else if source == "soong" {
869 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900870 } else if strings.HasPrefix(source, "file,") {
871 c.ninjaWeightListSource = EXTERNAL_FILE
872 filePath := strings.TrimPrefix(source, "file,")
873 err := validateNinjaWeightList(filePath)
874 if err != nil {
875 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
876 }
877 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
878 if err != nil {
879 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
880 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900881 } else {
882 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
883 }
Jihoon Kang1bff0342023-01-17 20:40:22 +0000884 } else if arg == "--build-from-text-stub" {
885 c.buildFromTextStub = true
MarkDacekb96561e2022-12-02 04:34:43 +0000886 } else if strings.HasPrefix(arg, "--build-command=") {
887 buildCmd := strings.TrimPrefix(arg, "--build-command=")
888 // remove quotations
889 buildCmd = strings.TrimPrefix(buildCmd, "\"")
890 buildCmd = strings.TrimSuffix(buildCmd, "\"")
891 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000892 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
893 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
MarkDacek6614d9c2022-12-07 21:57:38 +0000894 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
895 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
896 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
897 if err == nil {
898 c.buildStartedTime = val
899 } else {
900 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
901 }
MarkDacekf47e1422023-04-19 16:47:36 +0000902 } else if arg == "--ensure-allowlist-integrity" {
903 c.ensureAllowlistIntegrity = true
MarkDacekd33c2fd2023-05-04 20:40:04 +0000904 } else if strings.HasPrefix(arg, "--bazel-exit-code=") {
905 bazelExitCodeStr := strings.TrimPrefix(arg, "--bazel-exit-code=")
906 val, err := strconv.Atoi(bazelExitCodeStr)
907 if err == nil {
908 c.bazelExitCode = int32(val)
909 } else {
910 ctx.Fatalf("Error parsing bazel-exit-code", err)
911 }
MarkDacek396491e2023-06-14 19:41:18 +0000912 } else if strings.HasPrefix(arg, "--bes-id=") {
913 c.besId = strings.TrimPrefix(arg, "--bes-id=")
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700914 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700915 parseArgNum := func(def int) int {
916 if len(arg) > 2 {
917 p, err := strconv.ParseUint(arg[2:], 10, 31)
918 if err != nil {
919 ctx.Fatalf("Failed to parse %q: %v", arg, err)
920 }
921 return int(p)
922 } else if i+1 < len(args) {
923 p, err := strconv.ParseUint(args[i+1], 10, 31)
924 if err == nil {
925 i++
926 return int(p)
927 }
928 }
929 return def
930 }
931
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700932 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700933 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700934 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700935 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700936 } else {
937 ctx.Fatalln("Unknown option:", arg)
938 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700939 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700940 if k == "OUT_DIR" {
941 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
942 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700943 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700944 } else if arg == "dist" {
945 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200946 } else if arg == "json-module-graph" {
947 c.jsonModuleGraph = true
948 } else if arg == "bp2build" {
949 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000950 } else if arg == "api_bp2build" {
951 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200952 } else if arg == "queryview" {
953 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200954 } else if arg == "soong_docs" {
955 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700956 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700957 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800958 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700959 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700960 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700961 }
962 }
Chris Parsons21f80272023-06-15 04:02:28 +0000963 if (!c.bazelProdMode) && (!c.bazelStagingMode) {
Chris Parsonsb6e96902022-10-31 20:08:45 -0400964 c.bazelProdMode = defaultBazelProdMode(c)
965 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700966}
967
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900968func validateNinjaWeightList(weightListFilePath string) (err error) {
969 data, err := os.ReadFile(weightListFilePath)
970 if err != nil {
971 return
972 }
973 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
974 for _, line := range lines {
975 fields := strings.Split(line, ",")
976 if len(fields) != 2 {
977 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
978 }
979 _, err = strconv.Atoi(fields[1])
980 if err != nil {
981 return
982 }
983 }
984 return
985}
986
Dan Willemsened869522018-01-08 14:58:46 -0800987func (c *configImpl) configureLocale(ctx Context) {
988 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
989 output, err := cmd.Output()
990
991 var locales []string
992 if err == nil {
993 locales = strings.Split(string(output), "\n")
994 } else {
995 // If we're unable to list the locales, let's assume en_US.UTF-8
996 locales = []string{"en_US.UTF-8"}
997 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
998 }
999
1000 // gettext uses LANGUAGE, which is passed directly through
1001
1002 // For LANG and LC_*, only preserve the evaluated version of
1003 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001004 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -08001005 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001006 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -08001007 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001008 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -08001009 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001010 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -08001011 }
1012
1013 c.environ.UnsetWithPrefix("LC_")
1014
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001015 if userLang != "" {
1016 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -08001017 }
1018
1019 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
1020 // for others)
1021 if inList("C.UTF-8", locales) {
1022 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -05001023 } else if inList("C.utf8", locales) {
1024 // These normalize to the same thing
1025 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -08001026 } else if inList("en_US.UTF-8", locales) {
1027 c.environ.Set("LANG", "en_US.UTF-8")
1028 } else if inList("en_US.utf8", locales) {
1029 // These normalize to the same thing
1030 c.environ.Set("LANG", "en_US.UTF-8")
1031 } else {
1032 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
1033 }
1034}
1035
Dan Willemsen1e704462016-08-21 15:17:17 -07001036func (c *configImpl) Environment() *Environment {
1037 return c.environ
1038}
1039
1040func (c *configImpl) Arguments() []string {
1041 return c.arguments
1042}
1043
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001044func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001045 if len(c.Arguments()) > 0 {
1046 // Explicit targets requested that are not special targets like b2pbuild
1047 // or the JSON module graph
1048 return true
1049 }
1050
Spandan Das5af0bd32022-09-28 20:43:08 +00001051 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001052 // Command line was empty, the default Ninja target is built
1053 return true
1054 }
1055
Liz Kammer88677422021-12-15 15:03:19 -05001056 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
1057 if c.Dist() && !c.Bp2Build() {
1058 return true
1059 }
1060
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001061 // build.ninja doesn't need to be generated
1062 return false
1063}
1064
Dan Willemsen1e704462016-08-21 15:17:17 -07001065func (c *configImpl) OutDir() string {
1066 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -07001067 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -07001068 }
1069 return "out"
1070}
1071
Dan Willemsen8a073a82017-02-04 17:30:44 -08001072func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -04001073 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001074}
1075
1076func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -07001077 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -08001078}
1079
Dan Willemsen1e704462016-08-21 15:17:17 -07001080func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001081 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001082 return c.arguments
1083 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001084 return c.ninjaArgs
1085}
1086
Jingwen Chen7c6089a2020-11-02 02:56:20 -05001087func (c *configImpl) BazelOutDir() string {
1088 return filepath.Join(c.OutDir(), "bazel")
1089}
1090
Liz Kammer2af5ea82022-11-11 14:21:03 -05001091func (c *configImpl) bazelOutputBase() string {
1092 return filepath.Join(c.BazelOutDir(), "output")
1093}
1094
Dan Willemsen1e704462016-08-21 15:17:17 -07001095func (c *configImpl) SoongOutDir() string {
1096 return filepath.Join(c.OutDir(), "soong")
1097}
1098
Spandan Das394aa322022-11-03 17:02:10 +00001099func (c *configImpl) ApiSurfacesOutDir() string {
1100 return filepath.Join(c.OutDir(), "api_surfaces")
1101}
1102
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001103func (c *configImpl) PrebuiltOS() string {
1104 switch runtime.GOOS {
1105 case "linux":
1106 return "linux-x86"
1107 case "darwin":
1108 return "darwin-x86"
1109 default:
1110 panic("Unknown GOOS")
1111 }
1112}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001113
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001114func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001115 if c.SkipKatiNinja() {
1116 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1117 } else {
1118 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1119 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001120}
1121
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001122func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001123 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001124}
1125
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001126func (c *configImpl) UsedEnvFile(tag string) string {
Kiyoung Kimeaa55a82023-06-05 16:56:49 +09001127 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1128 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+v+"."+tag)
1129 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001130 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1131}
1132
Lukacs T. Berkic541cd22022-10-26 07:26:50 +00001133func (c *configImpl) Bp2BuildFilesMarkerFile() string {
1134 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
1135}
1136
1137func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001138 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +02001139}
1140
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001141func (c *configImpl) SoongDocsHtml() string {
1142 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1143}
1144
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001145func (c *configImpl) QueryviewMarkerFile() string {
1146 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1147}
1148
Spandan Das5af0bd32022-09-28 20:43:08 +00001149func (c *configImpl) ApiBp2buildMarkerFile() string {
1150 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
1151}
1152
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001153func (c *configImpl) ModuleGraphFile() string {
1154 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1155}
1156
kgui67007242022-01-25 13:50:25 +08001157func (c *configImpl) ModuleActionsFile() string {
1158 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1159}
1160
Jeff Gastonefc1b412017-03-29 17:29:06 -07001161func (c *configImpl) TempDir() string {
1162 return shared.TempDirForOutDir(c.SoongOutDir())
1163}
1164
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001165func (c *configImpl) FileListDir() string {
1166 return filepath.Join(c.OutDir(), ".module_paths")
1167}
1168
Dan Willemsen1e704462016-08-21 15:17:17 -07001169func (c *configImpl) KatiSuffix() string {
1170 if c.katiSuffix != "" {
1171 return c.katiSuffix
1172 }
1173 panic("SetKatiSuffix has not been called")
1174}
1175
Colin Cross37193492017-11-16 17:55:00 -08001176// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1177// user is interested in additional checks at the expense of build time.
1178func (c *configImpl) Checkbuild() bool {
1179 return c.checkbuild
1180}
1181
Dan Willemsen8a073a82017-02-04 17:30:44 -08001182func (c *configImpl) Dist() bool {
1183 return c.dist
1184}
1185
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001186func (c *configImpl) JsonModuleGraph() bool {
1187 return c.jsonModuleGraph
1188}
1189
1190func (c *configImpl) Bp2Build() bool {
1191 return c.bp2build
1192}
1193
Spandan Das5af0bd32022-09-28 20:43:08 +00001194func (c *configImpl) ApiBp2build() bool {
1195 return c.apiBp2build
1196}
1197
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001198func (c *configImpl) Queryview() bool {
1199 return c.queryview
1200}
1201
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001202func (c *configImpl) SoongDocs() bool {
1203 return c.soongDocs
1204}
1205
Dan Willemsen1e704462016-08-21 15:17:17 -07001206func (c *configImpl) IsVerbose() bool {
1207 return c.verbose
1208}
1209
LaMont Jones52a72432023-03-09 18:19:35 +00001210func (c *configImpl) MultitreeBuild() bool {
1211 return c.multitreeBuild
1212}
1213
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001214func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1215 return c.ninjaWeightListSource
1216}
1217
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001218func (c *configImpl) SkipKati() bool {
1219 return c.skipKati
1220}
1221
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001222func (c *configImpl) SkipKatiNinja() bool {
1223 return c.skipKatiNinja
1224}
1225
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001226func (c *configImpl) SkipSoong() bool {
1227 return c.skipSoong
1228}
1229
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001230func (c *configImpl) SkipNinja() bool {
1231 return c.skipNinja
1232}
1233
Anton Hansson5a7861a2021-06-04 10:09:01 +01001234func (c *configImpl) SetSkipNinja(v bool) {
1235 c.skipNinja = v
1236}
1237
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001238func (c *configImpl) SkipConfig() bool {
1239 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001240}
1241
Jihoon Kang1bff0342023-01-17 20:40:22 +00001242func (c *configImpl) BuildFromTextStub() bool {
1243 return c.buildFromTextStub
1244}
1245
Dan Willemsen1e704462016-08-21 15:17:17 -07001246func (c *configImpl) TargetProduct() string {
1247 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1248 return v
1249 }
1250 panic("TARGET_PRODUCT is not defined")
1251}
1252
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001253func (c *configImpl) TargetProductOrErr() (string, error) {
1254 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1255 return v, nil
1256 }
1257 return "", fmt.Errorf("TARGET_PRODUCT is not defined")
1258}
1259
Dan Willemsen02781d52017-05-12 19:28:13 -07001260func (c *configImpl) TargetDevice() string {
1261 return c.targetDevice
1262}
1263
1264func (c *configImpl) SetTargetDevice(device string) {
1265 c.targetDevice = device
1266}
1267
1268func (c *configImpl) TargetBuildVariant() string {
1269 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1270 return v
1271 }
1272 panic("TARGET_BUILD_VARIANT is not defined")
1273}
1274
Dan Willemsen1e704462016-08-21 15:17:17 -07001275func (c *configImpl) KatiArgs() []string {
1276 return c.katiArgs
1277}
1278
1279func (c *configImpl) Parallel() int {
1280 return c.parallel
1281}
1282
Sam Delmerico98a73292023-02-21 11:50:29 -05001283func (c *configImpl) GetSourceRootDirs() []string {
1284 return c.sourceRootDirs
1285}
1286
1287func (c *configImpl) SetSourceRootDirs(i []string) {
1288 c.sourceRootDirs = i
1289}
1290
Spandan Dasc5763832022-11-08 18:42:16 +00001291func (c *configImpl) GetIncludeTags() []string {
1292 return c.includeTags
1293}
1294
1295func (c *configImpl) SetIncludeTags(i []string) {
1296 c.includeTags = i
1297}
1298
MarkDacek6614d9c2022-12-07 21:57:38 +00001299func (c *configImpl) GetLogsPrefix() string {
1300 return c.logsPrefix
1301}
1302
1303func (c *configImpl) SetLogsPrefix(prefix string) {
1304 c.logsPrefix = prefix
1305}
1306
Colin Cross8b8bec32019-11-15 13:18:43 -08001307func (c *configImpl) HighmemParallel() int {
1308 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1309 return i
1310 }
1311
1312 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1313 parallel := c.Parallel()
1314 if c.UseRemoteBuild() {
1315 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1316 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1317 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1318 // Return 1/16th of the size of the local pool, rounding up.
1319 return (parallel + 15) / 16
1320 } else if c.totalRAM == 0 {
1321 // Couldn't detect the total RAM, don't restrict highmem processes.
1322 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001323 } else if c.totalRAM <= 16*1024*1024*1024 {
1324 // Less than 16GB of ram, restrict to 1 highmem processes
1325 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001326 } else if c.totalRAM <= 32*1024*1024*1024 {
1327 // Less than 32GB of ram, restrict to 2 highmem processes
1328 return 2
1329 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1330 // If less than 8GB total RAM per process, reduce the number of highmem processes
1331 return p
1332 }
1333 // No restriction on highmem processes
1334 return parallel
1335}
1336
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001337func (c *configImpl) TotalRAM() uint64 {
1338 return c.totalRAM
1339}
1340
Kousik Kumarec478642020-09-21 13:39:24 -04001341// ForceUseGoma determines whether we should override Goma deprecation
1342// and use Goma for the current build or not.
1343func (c *configImpl) ForceUseGoma() bool {
1344 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1345 v = strings.TrimSpace(v)
1346 if v != "" && v != "false" {
1347 return true
1348 }
1349 }
1350 return false
1351}
1352
Dan Willemsen1e704462016-08-21 15:17:17 -07001353func (c *configImpl) UseGoma() bool {
1354 if v, ok := c.environ.Get("USE_GOMA"); ok {
1355 v = strings.TrimSpace(v)
1356 if v != "" && v != "false" {
1357 return true
1358 }
1359 }
1360 return false
1361}
1362
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001363func (c *configImpl) StartGoma() bool {
1364 if !c.UseGoma() {
1365 return false
1366 }
1367
1368 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1369 v = strings.TrimSpace(v)
1370 if v != "" && v != "false" {
1371 return false
1372 }
1373 }
1374 return true
1375}
1376
Ramy Medhatbbf25672019-07-17 12:30:04 +00001377func (c *configImpl) UseRBE() bool {
Kousik Kumar67ad4342023-06-06 15:09:27 -04001378 authType, _ := c.rbeAuth()
1379 // Do not use RBE with prod credentials in scenarios when stubby doesn't exist, since
1380 // its unlikely that we will be able to obtain necessary creds without stubby.
1381 if !c.StubbyExists() && strings.Contains(authType, "use_google_prod_creds"){
1382 return false
1383 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001384 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001385 v = strings.TrimSpace(v)
1386 if v != "" && v != "false" {
1387 return true
1388 }
1389 }
1390 return false
1391}
1392
Chris Parsonsef615e52022-08-18 22:04:11 -04001393func (c *configImpl) BazelBuildEnabled() bool {
Chris Parsons21f80272023-06-15 04:02:28 +00001394 return c.bazelProdMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001395}
1396
Ramy Medhatbbf25672019-07-17 12:30:04 +00001397func (c *configImpl) StartRBE() bool {
1398 if !c.UseRBE() {
1399 return false
1400 }
1401
1402 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1403 v = strings.TrimSpace(v)
1404 if v != "" && v != "false" {
1405 return false
1406 }
1407 }
1408 return true
1409}
1410
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001411func (c *configImpl) rbeProxyLogsDir() string {
1412 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001413 if v, ok := c.environ.Get(f); ok {
1414 return v
1415 }
1416 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001417 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1418 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001419}
1420
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001421func (c *configImpl) rbeCacheDir() string {
1422 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1423 if v, ok := c.environ.Get(f); ok {
1424 return v
1425 }
1426 }
1427 return shared.JoinPath(c.SoongOutDir(), "rbe")
1428}
1429
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001430func (c *configImpl) shouldCleanupRBELogsDir() bool {
1431 // Perform a log directory cleanup only when the log directory
1432 // is auto created by the build rather than user-specified.
1433 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1434 if _, ok := c.environ.Get(f); ok {
1435 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001436 }
1437 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001438 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001439}
1440
1441func (c *configImpl) rbeExecRoot() string {
1442 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1443 if v, ok := c.environ.Get(f); ok {
1444 return v
1445 }
1446 }
1447 wd, err := os.Getwd()
1448 if err != nil {
1449 return ""
1450 }
1451 return wd
1452}
1453
1454func (c *configImpl) rbeDir() string {
1455 if v, ok := c.environ.Get("RBE_DIR"); ok {
1456 return v
1457 }
1458 return "prebuilts/remoteexecution-client/live/"
1459}
1460
1461func (c *configImpl) rbeReproxy() string {
1462 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1463 if v, ok := c.environ.Get(f); ok {
1464 return v
1465 }
1466 }
1467 return filepath.Join(c.rbeDir(), "reproxy")
1468}
1469
1470func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001471 credFlags := []string{
1472 "use_application_default_credentials",
1473 "use_gce_credentials",
1474 "credential_file",
1475 "use_google_prod_creds",
1476 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001477 for _, cf := range credFlags {
1478 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1479 if v, ok := c.environ.Get(f); ok {
1480 v = strings.TrimSpace(v)
1481 if v != "" && v != "false" && v != "0" {
1482 return "RBE_" + cf, v
1483 }
1484 }
1485 }
1486 }
1487 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001488}
1489
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001490func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1491 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1492 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1493
1494 name := filepath.Join(dir, base)
1495 if len(name) < maxNameLen {
1496 return name, nil
1497 }
1498
1499 name = filepath.Join("/tmp", base)
1500 if len(name) < maxNameLen {
1501 return name, nil
1502 }
1503
1504 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1505}
1506
Kousik Kumar7bc78192022-04-27 14:52:56 -04001507// IsGooglerEnvironment returns true if the current build is running
1508// on a Google developer machine and false otherwise.
1509func (c *configImpl) IsGooglerEnvironment() bool {
1510 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1511 if v, ok := c.environ.Get(cf); ok {
1512 return v == "googler"
1513 }
1514 return false
1515}
1516
1517// GoogleProdCredsExist determine whether credentials exist on the
1518// Googler machine to use remote execution.
1519func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001520 if googleProdCredsExistCache {
1521 return googleProdCredsExistCache
1522 }
andusyu0b3dc032023-06-21 17:29:32 -04001523 if _, err := exec.Command("/usr/bin/gcertstatus", "-nocheck_ssh").Output(); err != nil {
Kousik Kumar7bc78192022-04-27 14:52:56 -04001524 return false
1525 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001526 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001527 return true
1528}
1529
1530// UseRemoteBuild indicates whether to use a remote build acceleration system
1531// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001532func (c *configImpl) UseRemoteBuild() bool {
1533 return c.UseGoma() || c.UseRBE()
1534}
1535
Kousik Kumar7bc78192022-04-27 14:52:56 -04001536// StubbyExists checks whether the stubby binary exists on the machine running
1537// the build.
1538func (c *configImpl) StubbyExists() bool {
1539 if _, err := exec.LookPath("stubby"); err != nil {
1540 return false
1541 }
1542 return true
1543}
1544
Dan Willemsen1e704462016-08-21 15:17:17 -07001545// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001546// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001547// still limited by Parallel()
1548func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001549 if !c.UseRemoteBuild() {
1550 return 0
1551 }
1552 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1553 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001554 }
1555 return 500
1556}
1557
1558func (c *configImpl) SetKatiArgs(args []string) {
1559 c.katiArgs = args
1560}
1561
1562func (c *configImpl) SetNinjaArgs(args []string) {
1563 c.ninjaArgs = args
1564}
1565
1566func (c *configImpl) SetKatiSuffix(suffix string) {
1567 c.katiSuffix = suffix
1568}
1569
Dan Willemsene0879fc2017-08-04 15:06:27 -07001570func (c *configImpl) LastKatiSuffixFile() string {
1571 return filepath.Join(c.OutDir(), "last_kati_suffix")
1572}
1573
1574func (c *configImpl) HasKatiSuffix() bool {
1575 return c.katiSuffix != ""
1576}
1577
Dan Willemsen1e704462016-08-21 15:17:17 -07001578func (c *configImpl) KatiEnvFile() string {
1579 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1580}
1581
Dan Willemsen29971232018-09-26 14:58:30 -07001582func (c *configImpl) KatiBuildNinjaFile() string {
1583 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001584}
1585
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001586func (c *configImpl) KatiPackageNinjaFile() string {
1587 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1588}
1589
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001590func (c *configImpl) SoongVarsFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001591 targetProduct, err := c.TargetProductOrErr()
1592 if err != nil {
1593 return filepath.Join(c.SoongOutDir(), "soong.variables")
1594 } else {
1595 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+".variables")
1596 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001597}
1598
Dan Willemsen1e704462016-08-21 15:17:17 -07001599func (c *configImpl) SoongNinjaFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001600 targetProduct, err := c.TargetProductOrErr()
1601 if err != nil {
1602 return filepath.Join(c.SoongOutDir(), "build.ninja")
1603 } else {
1604 return filepath.Join(c.SoongOutDir(), "build."+targetProduct+".ninja")
1605 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001606}
1607
1608func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001609 if c.katiSuffix == "" {
1610 return filepath.Join(c.OutDir(), "combined.ninja")
1611 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001612 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1613}
1614
1615func (c *configImpl) SoongAndroidMk() string {
1616 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1617}
1618
1619func (c *configImpl) SoongMakeVarsMk() string {
1620 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1621}
1622
Dan Willemsenf052f782017-05-18 15:29:04 -07001623func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001624 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001625}
1626
Dan Willemsen02781d52017-05-12 19:28:13 -07001627func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001628 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1629}
1630
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001631func (c *configImpl) KatiPackageMkDir() string {
1632 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1633}
1634
Dan Willemsenf052f782017-05-18 15:29:04 -07001635func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001636 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001637}
1638
1639func (c *configImpl) HostOut() string {
1640 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1641}
1642
1643// This probably needs to be multi-valued, so not exporting it for now
1644func (c *configImpl) hostCrossOut() string {
1645 if runtime.GOOS == "linux" {
1646 return filepath.Join(c.hostOutRoot(), "windows-x86")
1647 } else {
1648 return ""
1649 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001650}
1651
Dan Willemsen1e704462016-08-21 15:17:17 -07001652func (c *configImpl) HostPrebuiltTag() string {
1653 if runtime.GOOS == "linux" {
1654 return "linux-x86"
1655 } else if runtime.GOOS == "darwin" {
1656 return "darwin-x86"
1657 } else {
1658 panic("Unsupported OS")
1659 }
1660}
Dan Willemsenf173d592017-04-27 14:28:00 -07001661
Dan Willemsen8122bd52017-10-12 20:20:41 -07001662func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001663 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1664 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001665 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1666 if _, err := os.Stat(asan); err == nil {
1667 return asan
1668 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001669 }
1670 }
1671 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1672}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001673
1674func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1675 c.brokenDupRules = val
1676}
1677
1678func (c *configImpl) BuildBrokenDupRules() bool {
1679 return c.brokenDupRules
1680}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001681
Dan Willemsen25e6f092019-04-09 10:22:43 -07001682func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1683 c.brokenUsesNetwork = val
1684}
1685
1686func (c *configImpl) BuildBrokenUsesNetwork() bool {
1687 return c.brokenUsesNetwork
1688}
1689
Dan Willemsene3336352020-01-02 19:10:38 -08001690func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1691 c.brokenNinjaEnvVars = val
1692}
1693
1694func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1695 return c.brokenNinjaEnvVars
1696}
1697
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001698func (c *configImpl) SetTargetDeviceDir(dir string) {
1699 c.targetDeviceDir = dir
1700}
1701
1702func (c *configImpl) TargetDeviceDir() string {
1703 return c.targetDeviceDir
1704}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001705
Patrice Arruda219eef32020-06-01 17:29:30 +00001706func (c *configImpl) BuildDateTime() string {
1707 return c.buildDateTime
1708}
1709
1710func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001711 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001712}
Patrice Arruda83842d72020-12-08 19:42:08 +00001713
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001714// LogsDir returns the absolute path to the logs directory where build log and
1715// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001716// directory. If the argument dist is specified, the logs directory
1717// is <dist_dir>/logs.
1718func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001719 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001720 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001721 // 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 -05001722 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001723 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001724 absDir, err := filepath.Abs(dir)
1725 if err != nil {
1726 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1727 os.Exit(1)
1728 }
1729 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001730}
1731
1732// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1733// where the bazel profiles are located.
1734func (c *configImpl) BazelMetricsDir() string {
1735 return filepath.Join(c.LogsDir(), "bazel_metrics")
1736}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001737
Chris Parsons53f68ae2022-03-03 12:01:40 -05001738// MkFileMetrics returns the file path for make-related metrics.
1739func (c *configImpl) MkMetrics() string {
1740 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1741}
1742
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001743func (c *configImpl) SetEmptyNinjaFile(v bool) {
1744 c.emptyNinjaFile = v
1745}
1746
1747func (c *configImpl) EmptyNinjaFile() bool {
1748 return c.emptyNinjaFile
1749}
Yu Liu6e13b402021-07-27 14:29:06 -07001750
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001751func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1752 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1753}
1754
Chris Parsons9402ca82023-02-23 17:28:06 -05001755func (c *configImpl) IsPersistentBazelEnabled() bool {
1756 return c.Environment().IsEnvTrue("USE_PERSISTENT_BAZEL")
1757}
1758
Chris Parsonsc83398f2023-05-31 18:41:41 +00001759// GetBazeliskBazelVersion returns the Bazel version to use for this build,
1760// or the empty string if the current canonical prod Bazel should be used.
1761// This environment variable should only be set to debug the build system.
1762// The Bazel version, if set, will be passed to Bazelisk, and Bazelisk will
1763// handle downloading and invoking the correct Bazel binary.
1764func (c *configImpl) GetBazeliskBazelVersion() string {
1765 value, _ := c.Environment().Get("USE_BAZEL_VERSION")
1766 return value
1767}
1768
MarkDacekd06db5d2022-11-29 00:47:59 +00001769func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1770 return c.bazelForceEnabledModules
1771}
1772
MarkDacekd0e7cd32022-12-02 22:22:40 +00001773func (c *configImpl) SkipMetricsUpload() bool {
1774 return c.skipMetricsUpload
1775}
1776
MarkDacekf47e1422023-04-19 16:47:36 +00001777func (c *configImpl) EnsureAllowlistIntegrity() bool {
1778 return c.ensureAllowlistIntegrity
1779}
1780
MarkDacek6614d9c2022-12-07 21:57:38 +00001781// Returns a Time object if one was passed via a command-line flag.
1782// Otherwise returns the passed default.
1783func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1784 if c.buildStartedTime == 0 {
1785 return defaultTime
1786 }
1787 return time.UnixMilli(c.buildStartedTime)
1788}
1789
MarkDacekd33c2fd2023-05-04 20:40:04 +00001790func (c *configImpl) BazelExitCode() int32 {
1791 return c.bazelExitCode
1792}
1793
Yu Liu6e13b402021-07-27 14:29:06 -07001794func GetMetricsUploader(topDir string, env *Environment) string {
1795 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1796 metricsUploader := filepath.Join(topDir, p)
1797 if _, err := os.Stat(metricsUploader); err == nil {
1798 return metricsUploader
1799 }
1800 }
1801
1802 return ""
1803}