blob: d825754efd07599d344d3ca1f75d58d10aa8b8c4 [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
MarkDacekd33c2fd2023-05-04 20:40:04 +000093 ensureAllowlistIntegrity bool // For CI builds - make sure modules are mixed-built
94 bazelExitCode int32 // For b-runs - necessary for updating NonZeroExit
Dan Willemsen1e704462016-08-21 15:17:17 -070095
96 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070097 katiArgs []string
98 ninjaArgs []string
99 katiSuffix string
100 targetDevice string
101 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +0000102 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -0700103
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800104 // Autodetected
105 totalRAM uint64
106
Dan Willemsene3336352020-01-02 19:10:38 -0800107 brokenDupRules bool
108 brokenUsesNetwork bool
109 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -0700110
111 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000112
MarkDacekb78465d2022-10-18 20:10:16 +0000113 bazelProdMode bool
MarkDacekb78465d2022-10-18 20:10:16 +0000114 bazelStagingMode bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000115
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700116 // Set by multiproduct_kati
117 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700118
119 metricsUploader string
MarkDacekd06db5d2022-11-29 00:47:59 +0000120
121 bazelForceEnabledModules string
Spandan Dasc5763832022-11-08 18:42:16 +0000122
Sam Delmerico98a73292023-02-21 11:50:29 -0500123 includeTags []string
124 sourceRootDirs []string
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900125
126 // Data source to write ninja weight list
127 ninjaWeightListSource NinjaWeightListSource
Dan Willemsen1e704462016-08-21 15:17:17 -0700128}
129
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900130type NinjaWeightListSource uint
131
132const (
133 // ninja doesn't use weight list.
134 NOT_USED NinjaWeightListSource = iota
135 // ninja uses weight list based on previous builds by ninja log
136 NINJA_LOG
137 // ninja thinks every task has the same weight.
138 EVENLY_DISTRIBUTED
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900139 // ninja uses an external custom weight list
140 EXTERNAL_FILE
Jeongik Chae114e602023-03-19 00:12:39 +0900141 // ninja uses a prioritized module list from Soong
142 HINT_FROM_SOONG
Jeongik Chaa87506f2023-06-01 23:16:41 +0900143 // If ninja log exists, use NINJA_LOG, if not, use HINT_FROM_SOONG instead.
144 // We can assume it is an incremental build if ninja log exists.
145 DEFAULT
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900146)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800147const srcDirFileCheck = "build/soong/root.bp"
148
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700149var buildFiles = []string{"Android.mk", "Android.bp"}
150
Patrice Arruda13848222019-04-22 17:12:02 -0700151type BuildAction uint
152
153const (
154 // Builds all of the modules and their dependencies of a specified directory, relative to the root
155 // directory of the source tree.
156 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
157
158 // Builds all of the modules and their dependencies of a list of specified directories. All specified
159 // directories are relative to the root directory of the source tree.
160 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700161
162 // Build a list of specified modules. If none was specified, simply build the whole source tree.
163 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700164)
165
166// checkTopDir validates that the current directory is at the root directory of the source tree.
167func checkTopDir(ctx Context) {
168 if _, err := os.Stat(srcDirFileCheck); err != nil {
169 if os.IsNotExist(err) {
170 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
171 }
172 ctx.Fatalln("Error verifying tree state:", err)
173 }
174}
175
Kousik Kumard93c67f2023-05-30 20:23:57 +0000176// fetchEnvConfig optionally fetches a configuration file that can then subsequently be
177// loaded into Soong environment to control certain aspects of build behavior (e.g., enabling RBE).
178// If a configuration file already exists on disk, the fetch is run in the background
179// so as to NOT block the rest of the build execution.
180func fetchEnvConfig(ctx Context, config *configImpl, envConfigName string) error {
181 configName := envConfigName + "." + jsonSuffix
182 expConfigFetcher := &smpb.ExpConfigFetcher{Filename: &configName}
183 defer func() {
184 ctx.Metrics.ExpConfigFetcher(expConfigFetcher)
185 }()
186 if !config.GoogleProdCredsExist() {
187 status := smpb.ExpConfigFetcher_MISSING_GCERT
188 expConfigFetcher.Status = &status
189 return nil
190 }
191
192 s, err := os.Stat(configFetcher)
193 if err != nil {
194 if os.IsNotExist(err) {
195 return nil
196 }
197 return err
198 }
199 if s.Mode()&0111 == 0 {
200 status := smpb.ExpConfigFetcher_ERROR
201 expConfigFetcher.Status = &status
202 return fmt.Errorf("configuration fetcher binary %v is not executable: %v", configFetcher, s.Mode())
203 }
204
205 configExists := false
206 outConfigFilePath := filepath.Join(config.OutDir(), configName)
207 if _, err := os.Stat(outConfigFilePath); err == nil {
208 configExists = true
209 }
210
211 tCtx, cancel := context.WithTimeout(ctx, envConfigFetchTimeout)
212 fetchStart := time.Now()
213 cmd := exec.CommandContext(tCtx, configFetcher, "-output_config_dir", config.OutDir(),
214 "-output_config_name", configName)
215 if err := cmd.Start(); err != nil {
216 status := smpb.ExpConfigFetcher_ERROR
217 expConfigFetcher.Status = &status
218 return err
219 }
220
221 fetchCfg := func() error {
222 if err := cmd.Wait(); err != nil {
223 status := smpb.ExpConfigFetcher_ERROR
224 expConfigFetcher.Status = &status
225 return err
226 }
227 fetchEnd := time.Now()
228 expConfigFetcher.Micros = proto.Uint64(uint64(fetchEnd.Sub(fetchStart).Microseconds()))
229 expConfigFetcher.Filename = proto.String(outConfigFilePath)
230
231 if _, err := os.Stat(outConfigFilePath); err != nil {
232 status := smpb.ExpConfigFetcher_NO_CONFIG
233 expConfigFetcher.Status = &status
234 return err
235 }
236 status := smpb.ExpConfigFetcher_CONFIG
237 expConfigFetcher.Status = &status
238 return nil
239 }
240
241 // If a config file does not exist, wait for the config file to be fetched. Otherwise
242 // fetch the config file in the background and return immediately.
243 if !configExists {
244 defer cancel()
245 return fetchCfg()
246 }
247
248 go func() {
249 defer cancel()
250 if err := fetchCfg(); err != nil {
251 ctx.Verbosef("Failed to fetch config file %v: %v\n", configName, err)
252 }
253 }()
254 return nil
255}
256
MarkDacek7901e582023-01-09 19:48:01 +0000257func loadEnvConfig(ctx Context, config *configImpl, bc string) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500258 if bc == "" {
259 return nil
260 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500261
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500262 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500263 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500264 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500265 envConfigDir,
266 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500267 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500268 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
269 envVarsJSON, err := ioutil.ReadFile(cfgFile)
270 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500271 continue
272 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500273 ctx.Verbosef("Loading config file %v\n", cfgFile)
274 var envVars map[string]map[string]string
275 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
276 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
277 continue
278 }
279 for k, v := range envVars["env"] {
280 if os.Getenv(k) != "" {
281 continue
282 }
283 config.environ.Set(k, v)
284 }
285 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
286 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500287 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500288
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500289 return nil
290}
291
Chris Parsonsb6e96902022-10-31 20:08:45 -0400292func defaultBazelProdMode(cfg *configImpl) bool {
MarkDacekd06db5d2022-11-29 00:47:59 +0000293 // Environment flag to disable Bazel for users which experience
Chris Parsonsb6e96902022-10-31 20:08:45 -0400294 // broken bazel-handled builds, or significant performance regressions.
295 if cfg.IsBazelMixedBuildForceDisabled() {
296 return false
297 }
298 // Darwin-host builds are currently untested with Bazel.
299 if runtime.GOOS == "darwin" {
300 return false
301 }
Chris Parsons035e03a2022-11-01 14:25:45 -0400302 return true
Chris Parsonsb6e96902022-10-31 20:08:45 -0400303}
304
MarkDacekd33c2fd2023-05-04 20:40:04 +0000305func UploadOnlyConfig(ctx Context, args ...string) Config {
MarkDacek6614d9c2022-12-07 21:57:38 +0000306 ret := &configImpl{
307 environ: OsEnvironment(),
308 sandboxConfig: &SandboxConfig{},
309 }
MarkDacekd33c2fd2023-05-04 20:40:04 +0000310 ret.parseArgs(ctx, args)
MarkDacek7901e582023-01-09 19:48:01 +0000311 srcDir := absPath(ctx, ".")
312 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
313 if err := loadEnvConfig(ctx, ret, bc); err != nil {
314 ctx.Fatalln("Failed to parse env config files: %v", err)
315 }
316 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
MarkDacek6614d9c2022-12-07 21:57:38 +0000317 return Config{ret}
318}
319
Dan Willemsen1e704462016-08-21 15:17:17 -0700320func NewConfig(ctx Context, args ...string) Config {
321 ret := &configImpl{
Jeongik Chaf2ecf762023-05-19 14:03:45 +0900322 environ: OsEnvironment(),
323 sandboxConfig: &SandboxConfig{},
Jeongik Chaa87506f2023-06-01 23:16:41 +0900324 ninjaWeightListSource: DEFAULT,
Dan Willemsen1e704462016-08-21 15:17:17 -0700325 }
326
Patrice Arruda90109172020-07-28 18:07:27 +0000327 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700328 ret.parallel = runtime.NumCPU() + 2
329 ret.keepGoing = 1
330
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800331 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700332 ret.parseArgs(ctx, args)
Jeongik Chae114e602023-03-19 00:12:39 +0900333
334 if ret.ninjaWeightListSource == HINT_FROM_SOONG {
Jeongik Chaa87506f2023-06-01 23:16:41 +0900335 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "always")
336 } else if ret.ninjaWeightListSource == DEFAULT {
337 defaultNinjaWeightListSource := NINJA_LOG
338 if _, err := os.Stat(filepath.Join(ret.OutDir(), ninjaLogFileName)); errors.Is(err, os.ErrNotExist) {
339 ctx.Verboseln("$OUT/.ninja_log doesn't exist, use HINT_FROM_SOONG instead")
340 defaultNinjaWeightListSource = HINT_FROM_SOONG
341 } else {
342 ctx.Verboseln("$OUT/.ninja_log exist, use NINJA_LOG")
343 }
344 ret.ninjaWeightListSource = defaultNinjaWeightListSource
345 // soong_build generates ninja hint depending on ninja log existence.
346 // Set it "depend" to avoid soong re-run due to env variable change.
347 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "depend")
Jeongik Chae114e602023-03-19 00:12:39 +0900348 }
Jeongik Chaa87506f2023-06-01 23:16:41 +0900349
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800350 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700351 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
352 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
353 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800354 outDir := "out"
355 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
356 if wd, err := os.Getwd(); err != nil {
357 ctx.Fatalln("Failed to get working directory:", err)
358 } else {
359 outDir = filepath.Join(baseDir, filepath.Base(wd))
360 }
361 }
362 ret.environ.Set("OUT_DIR", outDir)
363 }
364
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500365 // loadEnvConfig needs to know what the OUT_DIR is, so it should
366 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000367 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
368
369 if bc != "" {
Kousik Kumard93c67f2023-05-30 20:23:57 +0000370 if err := fetchEnvConfig(ctx, ret, bc); err != nil {
371 ctx.Verbosef("Failed to fetch config file: %v\n", err)
372 }
Kousik Kumarc8818332023-01-16 16:33:05 +0000373 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000374 ctx.Fatalln("Failed to parse env config files: %v", err)
375 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500376 }
377
Dan Willemsen2d31a442018-10-20 21:33:41 -0700378 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
379 ret.distDir = filepath.Clean(distDir)
380 } else {
381 ret.distDir = filepath.Join(ret.OutDir(), "dist")
382 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700383
Spandan Das05063612021-06-25 01:39:04 +0000384 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
385 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
386 }
387
Dan Willemsen1e704462016-08-21 15:17:17 -0700388 ret.environ.Unset(
389 // We're already using it
390 "USE_SOONG_UI",
391
392 // We should never use GOROOT/GOPATH from the shell environment
393 "GOROOT",
394 "GOPATH",
395
396 // These should only come from Soong, not the environment.
397 "CLANG",
398 "CLANG_CXX",
399 "CCC_CC",
400 "CCC_CXX",
401
402 // Used by the goma compiler wrapper, but should only be set by
403 // gomacc
404 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800405
406 // We handle this above
407 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700408
Dan Willemsen2d31a442018-10-20 21:33:41 -0700409 // This is handled above too, and set for individual commands later
410 "DIST_DIR",
411
Dan Willemsen68a09852017-04-18 13:56:57 -0700412 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000413 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700414 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700415 "DISPLAY",
416 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000417 "JAVAC",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700418 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700419 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700420
421 // Drop make flags
422 "MAKEFLAGS",
423 "MAKELEVEL",
424 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700425
426 // Set in envsetup.sh, reset in makefiles
427 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700428
429 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
430 "ANDROID_BUILD_TOP",
431 "ANDROID_HOST_OUT",
432 "ANDROID_PRODUCT_OUT",
433 "ANDROID_HOST_OUT_TESTCASES",
434 "ANDROID_TARGET_OUT_TESTCASES",
435 "ANDROID_TOOLCHAIN",
436 "ANDROID_TOOLCHAIN_2ND_ARCH",
437 "ANDROID_DEV_SCRIPTS",
438 "ANDROID_EMULATOR_PREBUILTS",
439 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700440 )
441
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400442 if ret.UseGoma() || ret.ForceUseGoma() {
443 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
444 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400445 }
446
Dan Willemsen1e704462016-08-21 15:17:17 -0700447 // Tell python not to spam the source tree with .pyc files.
448 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
449
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400450 tmpDir := absPath(ctx, ret.TempDir())
451 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800452
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700453 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
454 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
455 "llvm-binutils-stable/llvm-symbolizer")
456 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
457
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800458 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700459 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800460
Yu Liu6e13b402021-07-27 14:29:06 -0700461 srcDir := absPath(ctx, ".")
462 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700463 ctx.Println("You are building in a directory whose absolute path contains a space character:")
464 ctx.Println()
465 ctx.Printf("%q\n", srcDir)
466 ctx.Println()
467 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700468 }
469
Yu Liu6e13b402021-07-27 14:29:06 -0700470 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
471
Dan Willemsendb8457c2017-05-12 16:38:17 -0700472 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700473 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
474 ctx.Println()
475 ctx.Printf("%q\n", outDir)
476 ctx.Println()
477 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700478 }
479
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000480 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700481 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
482 ctx.Println()
483 ctx.Printf("%q\n", distDir)
484 ctx.Println()
485 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700486 }
487
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700488 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000489 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
490 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100491 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800492 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700493 javaHome := func() string {
494 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
495 return override
496 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000497 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
498 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 +0100499 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000500 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
501 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
502 }
503 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700504 }()
505 absJavaHome := absPath(ctx, javaHome)
506
Dan Willemsened869522018-01-08 14:58:46 -0800507 ret.configureLocale(ctx)
508
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700509 newPath := []string{filepath.Join(absJavaHome, "bin")}
510 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
511 newPath = append(newPath, path)
512 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100513
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700514 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
515 ret.environ.Set("JAVA_HOME", absJavaHome)
516 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000517 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
518 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100519 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700520 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
521
LaMont Jones52a72432023-03-09 18:19:35 +0000522 if ret.MultitreeBuild() {
523 ret.environ.Set("MULTITREE_BUILD", "true")
524 }
525
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800526 outDir := ret.OutDir()
527 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800528 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800529 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800530 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800531 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800532 }
Colin Cross28f527c2019-11-26 16:19:04 -0800533
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800534 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
535
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400536 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400537 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400538 ret.environ.Set(k, v)
539 }
540 }
541
Jihoon Kang1bff0342023-01-17 20:40:22 +0000542 if ret.BuildFromTextStub() {
543 // TODO(b/271443071): support hidden api check for from-text stub build
544 ret.environ.Set("UNSAFE_DISABLE_HIDDENAPI_FLAGS", "true")
545 }
546
Patrice Arruda83842d72020-12-08 19:42:08 +0000547 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800548 if err := os.RemoveAll(bpd); err != nil {
549 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
550 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000551
Patrice Arruda96850362020-08-11 20:41:11 +0000552 c := Config{ret}
553 storeConfigMetrics(ctx, c)
554 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700555}
556
Patrice Arruda13848222019-04-22 17:12:02 -0700557// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
558// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700559func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
560 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700561}
562
Patrice Arruda96850362020-08-11 20:41:11 +0000563// storeConfigMetrics selects a set of configuration information and store in
564// the metrics system for further analysis.
565func storeConfigMetrics(ctx Context, config Config) {
566 if ctx.Metrics == nil {
567 return
568 }
569
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400570 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000571
572 s := &smpb.SystemResourceInfo{
573 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
574 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
575 }
576 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000577}
578
Jeongik Cha8d63d562023-03-17 03:52:13 +0900579func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900580 switch s {
581 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900582 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900583 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900584 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900585 case EXTERNAL_FILE:
586 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900587 case HINT_FROM_SOONG:
588 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900589 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900590 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900591 }
592}
593
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400594func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700595 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400596 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
597 UseGoma: proto.Bool(config.UseGoma()),
598 UseRbe: proto.Bool(config.UseRBE()),
599 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
600 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900601 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400602 }
Yu Liue737a992021-10-04 13:21:41 -0700603 c.Targets = append(c.Targets, config.arguments...)
604
605 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400606}
607
Patrice Arruda13848222019-04-22 17:12:02 -0700608// getConfigArgs processes the command arguments based on the build action and creates a set of new
609// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700610func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700611 // The next block of code verifies that the current directory is the root directory of the source
612 // tree. It then finds the relative path of dir based on the root directory of the source tree
613 // and verify that dir is inside of the source tree.
614 checkTopDir(ctx)
615 topDir, err := os.Getwd()
616 if err != nil {
617 ctx.Fatalf("Error retrieving top directory: %v", err)
618 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700619 dir, err = filepath.EvalSymlinks(dir)
620 if err != nil {
621 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
622 }
Patrice Arruda13848222019-04-22 17:12:02 -0700623 dir, err = filepath.Abs(dir)
624 if err != nil {
625 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
626 }
627 relDir, err := filepath.Rel(topDir, dir)
628 if err != nil {
629 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
630 }
631 // If there are ".." in the path, it's not in the source tree.
632 if strings.Contains(relDir, "..") {
633 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
634 }
635
636 configArgs := args[:]
637
638 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
639 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
640 targetNamePrefix := "MODULES-IN-"
641 if inList("GET-INSTALL-PATH", configArgs) {
642 targetNamePrefix = "GET-INSTALL-PATH-IN-"
643 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
644 }
645
Patrice Arruda13848222019-04-22 17:12:02 -0700646 var targets []string
647
648 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700649 case BUILD_MODULES:
650 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700651 case BUILD_MODULES_IN_A_DIRECTORY:
652 // If dir is the root source tree, all the modules are built of the source tree are built so
653 // no need to find the build file.
654 if topDir == dir {
655 break
656 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700657
Patrice Arruda13848222019-04-22 17:12:02 -0700658 buildFile := findBuildFile(ctx, relDir)
659 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700660 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700661 }
Patrice Arruda13848222019-04-22 17:12:02 -0700662 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
663 case BUILD_MODULES_IN_DIRECTORIES:
664 newConfigArgs, dirs := splitArgs(configArgs)
665 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700666 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700667 }
668
669 // Tidy only override all other specified targets.
670 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
671 if tidyOnly == "true" || tidyOnly == "1" {
672 configArgs = append(configArgs, "tidy_only")
673 } else {
674 configArgs = append(configArgs, targets...)
675 }
676
677 return configArgs
678}
679
680// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
681func convertToTarget(dir string, targetNamePrefix string) string {
682 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
683}
684
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700685// hasBuildFile returns true if dir contains an Android build file.
686func hasBuildFile(ctx Context, dir string) bool {
687 for _, buildFile := range buildFiles {
688 _, err := os.Stat(filepath.Join(dir, buildFile))
689 if err == nil {
690 return true
691 }
692 if !os.IsNotExist(err) {
693 ctx.Fatalf("Error retrieving the build file stats: %v", err)
694 }
695 }
696 return false
697}
698
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700699// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
700// in the current and any sub directory of dir. If a build file is not found, traverse the path
701// up by one directory and repeat again until either a build file is found or reached to the root
702// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
703// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700704func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700705 // If the string is empty or ".", assume it is top directory of the source tree.
706 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700707 return ""
708 }
709
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700710 found := false
711 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
712 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
713 if err != nil {
714 return err
715 }
716 if found {
717 return filepath.SkipDir
718 }
719 if info.IsDir() {
720 return nil
721 }
722 for _, buildFile := range buildFiles {
723 if info.Name() == buildFile {
724 found = true
725 return filepath.SkipDir
726 }
727 }
728 return nil
729 })
730 if err != nil {
731 ctx.Fatalf("Error finding Android build file: %v", err)
732 }
733
734 if found {
735 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700736 }
737 }
738
739 return ""
740}
741
742// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
743func splitArgs(args []string) (newArgs []string, dirs []string) {
744 specialArgs := map[string]bool{
745 "showcommands": true,
746 "snod": true,
747 "dist": true,
748 "checkbuild": true,
749 }
750
751 newArgs = []string{}
752 dirs = []string{}
753
754 for _, arg := range args {
755 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
756 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
757 newArgs = append(newArgs, arg)
758 continue
759 }
760
761 if _, ok := specialArgs[arg]; ok {
762 newArgs = append(newArgs, arg)
763 continue
764 }
765
766 dirs = append(dirs, arg)
767 }
768
769 return newArgs, dirs
770}
771
772// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
773// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
774// source root tree where the build action command was invoked. Each directory is validated if the
775// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700776func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700777 for _, dir := range dirs {
778 // The directory may have specified specific modules to build. ":" is the separator to separate
779 // the directory and the list of modules.
780 s := strings.Split(dir, ":")
781 l := len(s)
782 if l > 2 { // more than one ":" was specified.
783 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
784 }
785
786 dir = filepath.Join(relDir, s[0])
787 if _, err := os.Stat(dir); err != nil {
788 ctx.Fatalf("couldn't find directory %s", dir)
789 }
790
791 // Verify that if there are any targets specified after ":". Each target is separated by ",".
792 var newTargets []string
793 if l == 2 && s[1] != "" {
794 newTargets = strings.Split(s[1], ",")
795 if inList("", newTargets) {
796 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
797 }
798 }
799
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700800 // If there are specified targets to build in dir, an android build file must exist for the one
801 // shot build. For the non-targets case, find the appropriate build file and build all the
802 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700803 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700804 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700805 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
806 }
807 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700808 buildFile := findBuildFile(ctx, dir)
809 if buildFile == "" {
810 ctx.Fatalf("Build file not found for %s directory", dir)
811 }
812 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700813 }
814
Patrice Arruda13848222019-04-22 17:12:02 -0700815 targets = append(targets, newTargets...)
816 }
817
Dan Willemsence41e942019-07-29 23:39:30 -0700818 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700819}
820
Dan Willemsen9b587492017-07-10 22:13:00 -0700821func (c *configImpl) parseArgs(ctx Context, args []string) {
822 for i := 0; i < len(args); i++ {
823 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100824 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700825 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200826 } else if arg == "--empty-ninja-file" {
827 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100828 } else if arg == "--skip-ninja" {
829 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700830 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700831 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
832 // but it does run a Kati ninja file if the .kati_enabled marker file was created
833 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000834 c.skipConfig = true
835 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100836 } else if arg == "--soong-only" {
837 c.skipKati = true
838 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200839 } else if arg == "--config-only" {
840 c.skipKati = true
841 c.skipKatiNinja = true
842 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700843 } else if arg == "--skip-config" {
844 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700845 } else if arg == "--skip-soong-tests" {
846 c.skipSoongTests = true
MarkDacekd0e7cd32022-12-02 22:22:40 +0000847 } else if arg == "--skip-metrics-upload" {
848 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500849 } else if arg == "--mk-metrics" {
850 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000851 } else if arg == "--multitree-build" {
852 c.multitreeBuild = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400853 } else if arg == "--bazel-mode" {
854 c.bazelProdMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000855 } else if arg == "--bazel-mode-staging" {
856 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000857 } else if arg == "--search-api-dir" {
858 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900859 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
860 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
861 if source == "ninja_log" {
862 c.ninjaWeightListSource = NINJA_LOG
863 } else if source == "evenly_distributed" {
864 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
865 } else if source == "not_used" {
866 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900867 } else if source == "soong" {
868 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900869 } else if strings.HasPrefix(source, "file,") {
870 c.ninjaWeightListSource = EXTERNAL_FILE
871 filePath := strings.TrimPrefix(source, "file,")
872 err := validateNinjaWeightList(filePath)
873 if err != nil {
874 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
875 }
876 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
877 if err != nil {
878 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
879 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900880 } else {
881 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
882 }
Jihoon Kang1bff0342023-01-17 20:40:22 +0000883 } else if arg == "--build-from-text-stub" {
884 c.buildFromTextStub = true
MarkDacekb96561e2022-12-02 04:34:43 +0000885 } else if strings.HasPrefix(arg, "--build-command=") {
886 buildCmd := strings.TrimPrefix(arg, "--build-command=")
887 // remove quotations
888 buildCmd = strings.TrimPrefix(buildCmd, "\"")
889 buildCmd = strings.TrimSuffix(buildCmd, "\"")
890 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000891 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
892 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
MarkDacek6614d9c2022-12-07 21:57:38 +0000893 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
894 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
895 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
896 if err == nil {
897 c.buildStartedTime = val
898 } else {
899 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
900 }
MarkDacekf47e1422023-04-19 16:47:36 +0000901 } else if arg == "--ensure-allowlist-integrity" {
902 c.ensureAllowlistIntegrity = true
MarkDacekd33c2fd2023-05-04 20:40:04 +0000903 } else if strings.HasPrefix(arg, "--bazel-exit-code=") {
904 bazelExitCodeStr := strings.TrimPrefix(arg, "--bazel-exit-code=")
905 val, err := strconv.Atoi(bazelExitCodeStr)
906 if err == nil {
907 c.bazelExitCode = int32(val)
908 } else {
909 ctx.Fatalf("Error parsing bazel-exit-code", err)
910 }
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700911 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700912 parseArgNum := func(def int) int {
913 if len(arg) > 2 {
914 p, err := strconv.ParseUint(arg[2:], 10, 31)
915 if err != nil {
916 ctx.Fatalf("Failed to parse %q: %v", arg, err)
917 }
918 return int(p)
919 } else if i+1 < len(args) {
920 p, err := strconv.ParseUint(args[i+1], 10, 31)
921 if err == nil {
922 i++
923 return int(p)
924 }
925 }
926 return def
927 }
928
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700929 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700930 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700931 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700932 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700933 } else {
934 ctx.Fatalln("Unknown option:", arg)
935 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700936 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700937 if k == "OUT_DIR" {
938 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
939 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700940 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700941 } else if arg == "dist" {
942 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200943 } else if arg == "json-module-graph" {
944 c.jsonModuleGraph = true
945 } else if arg == "bp2build" {
946 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000947 } else if arg == "api_bp2build" {
948 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200949 } else if arg == "queryview" {
950 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200951 } else if arg == "soong_docs" {
952 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700953 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700954 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800955 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700956 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700957 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700958 }
959 }
Chris Parsons21f80272023-06-15 04:02:28 +0000960 if (!c.bazelProdMode) && (!c.bazelStagingMode) {
Chris Parsonsb6e96902022-10-31 20:08:45 -0400961 c.bazelProdMode = defaultBazelProdMode(c)
962 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700963}
964
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900965func validateNinjaWeightList(weightListFilePath string) (err error) {
966 data, err := os.ReadFile(weightListFilePath)
967 if err != nil {
968 return
969 }
970 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
971 for _, line := range lines {
972 fields := strings.Split(line, ",")
973 if len(fields) != 2 {
974 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
975 }
976 _, err = strconv.Atoi(fields[1])
977 if err != nil {
978 return
979 }
980 }
981 return
982}
983
Dan Willemsened869522018-01-08 14:58:46 -0800984func (c *configImpl) configureLocale(ctx Context) {
985 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
986 output, err := cmd.Output()
987
988 var locales []string
989 if err == nil {
990 locales = strings.Split(string(output), "\n")
991 } else {
992 // If we're unable to list the locales, let's assume en_US.UTF-8
993 locales = []string{"en_US.UTF-8"}
994 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
995 }
996
997 // gettext uses LANGUAGE, which is passed directly through
998
999 // For LANG and LC_*, only preserve the evaluated version of
1000 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001001 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -08001002 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001003 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -08001004 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001005 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -08001006 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001007 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -08001008 }
1009
1010 c.environ.UnsetWithPrefix("LC_")
1011
Jaewoong Jung18aefc12020-12-21 09:11:10 -08001012 if userLang != "" {
1013 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -08001014 }
1015
1016 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
1017 // for others)
1018 if inList("C.UTF-8", locales) {
1019 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -05001020 } else if inList("C.utf8", locales) {
1021 // These normalize to the same thing
1022 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -08001023 } else if inList("en_US.UTF-8", locales) {
1024 c.environ.Set("LANG", "en_US.UTF-8")
1025 } else if inList("en_US.utf8", locales) {
1026 // These normalize to the same thing
1027 c.environ.Set("LANG", "en_US.UTF-8")
1028 } else {
1029 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
1030 }
1031}
1032
Dan Willemsen1e704462016-08-21 15:17:17 -07001033func (c *configImpl) Environment() *Environment {
1034 return c.environ
1035}
1036
1037func (c *configImpl) Arguments() []string {
1038 return c.arguments
1039}
1040
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001041func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001042 if len(c.Arguments()) > 0 {
1043 // Explicit targets requested that are not special targets like b2pbuild
1044 // or the JSON module graph
1045 return true
1046 }
1047
Spandan Das5af0bd32022-09-28 20:43:08 +00001048 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001049 // Command line was empty, the default Ninja target is built
1050 return true
1051 }
1052
Liz Kammer88677422021-12-15 15:03:19 -05001053 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
1054 if c.Dist() && !c.Bp2Build() {
1055 return true
1056 }
1057
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001058 // build.ninja doesn't need to be generated
1059 return false
1060}
1061
Dan Willemsen1e704462016-08-21 15:17:17 -07001062func (c *configImpl) OutDir() string {
1063 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -07001064 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -07001065 }
1066 return "out"
1067}
1068
Dan Willemsen8a073a82017-02-04 17:30:44 -08001069func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -04001070 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001071}
1072
1073func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -07001074 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -08001075}
1076
Dan Willemsen1e704462016-08-21 15:17:17 -07001077func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001078 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001079 return c.arguments
1080 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001081 return c.ninjaArgs
1082}
1083
Jingwen Chen7c6089a2020-11-02 02:56:20 -05001084func (c *configImpl) BazelOutDir() string {
1085 return filepath.Join(c.OutDir(), "bazel")
1086}
1087
Liz Kammer2af5ea82022-11-11 14:21:03 -05001088func (c *configImpl) bazelOutputBase() string {
1089 return filepath.Join(c.BazelOutDir(), "output")
1090}
1091
Dan Willemsen1e704462016-08-21 15:17:17 -07001092func (c *configImpl) SoongOutDir() string {
1093 return filepath.Join(c.OutDir(), "soong")
1094}
1095
Spandan Das394aa322022-11-03 17:02:10 +00001096func (c *configImpl) ApiSurfacesOutDir() string {
1097 return filepath.Join(c.OutDir(), "api_surfaces")
1098}
1099
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001100func (c *configImpl) PrebuiltOS() string {
1101 switch runtime.GOOS {
1102 case "linux":
1103 return "linux-x86"
1104 case "darwin":
1105 return "darwin-x86"
1106 default:
1107 panic("Unknown GOOS")
1108 }
1109}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001110
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001111func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001112 if c.SkipKatiNinja() {
1113 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1114 } else {
1115 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1116 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001117}
1118
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001119func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001120 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001121}
1122
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001123func (c *configImpl) UsedEnvFile(tag string) string {
Kiyoung Kimeaa55a82023-06-05 16:56:49 +09001124 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1125 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+v+"."+tag)
1126 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001127 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1128}
1129
Lukacs T. Berkic541cd22022-10-26 07:26:50 +00001130func (c *configImpl) Bp2BuildFilesMarkerFile() string {
1131 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
1132}
1133
1134func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001135 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +02001136}
1137
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001138func (c *configImpl) SoongDocsHtml() string {
1139 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1140}
1141
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001142func (c *configImpl) QueryviewMarkerFile() string {
1143 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1144}
1145
Spandan Das5af0bd32022-09-28 20:43:08 +00001146func (c *configImpl) ApiBp2buildMarkerFile() string {
1147 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
1148}
1149
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001150func (c *configImpl) ModuleGraphFile() string {
1151 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1152}
1153
kgui67007242022-01-25 13:50:25 +08001154func (c *configImpl) ModuleActionsFile() string {
1155 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1156}
1157
Jeff Gastonefc1b412017-03-29 17:29:06 -07001158func (c *configImpl) TempDir() string {
1159 return shared.TempDirForOutDir(c.SoongOutDir())
1160}
1161
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001162func (c *configImpl) FileListDir() string {
1163 return filepath.Join(c.OutDir(), ".module_paths")
1164}
1165
Dan Willemsen1e704462016-08-21 15:17:17 -07001166func (c *configImpl) KatiSuffix() string {
1167 if c.katiSuffix != "" {
1168 return c.katiSuffix
1169 }
1170 panic("SetKatiSuffix has not been called")
1171}
1172
Colin Cross37193492017-11-16 17:55:00 -08001173// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1174// user is interested in additional checks at the expense of build time.
1175func (c *configImpl) Checkbuild() bool {
1176 return c.checkbuild
1177}
1178
Dan Willemsen8a073a82017-02-04 17:30:44 -08001179func (c *configImpl) Dist() bool {
1180 return c.dist
1181}
1182
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001183func (c *configImpl) JsonModuleGraph() bool {
1184 return c.jsonModuleGraph
1185}
1186
1187func (c *configImpl) Bp2Build() bool {
1188 return c.bp2build
1189}
1190
Spandan Das5af0bd32022-09-28 20:43:08 +00001191func (c *configImpl) ApiBp2build() bool {
1192 return c.apiBp2build
1193}
1194
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001195func (c *configImpl) Queryview() bool {
1196 return c.queryview
1197}
1198
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001199func (c *configImpl) SoongDocs() bool {
1200 return c.soongDocs
1201}
1202
Dan Willemsen1e704462016-08-21 15:17:17 -07001203func (c *configImpl) IsVerbose() bool {
1204 return c.verbose
1205}
1206
LaMont Jones52a72432023-03-09 18:19:35 +00001207func (c *configImpl) MultitreeBuild() bool {
1208 return c.multitreeBuild
1209}
1210
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001211func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1212 return c.ninjaWeightListSource
1213}
1214
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001215func (c *configImpl) SkipKati() bool {
1216 return c.skipKati
1217}
1218
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001219func (c *configImpl) SkipKatiNinja() bool {
1220 return c.skipKatiNinja
1221}
1222
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001223func (c *configImpl) SkipSoong() bool {
1224 return c.skipSoong
1225}
1226
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001227func (c *configImpl) SkipNinja() bool {
1228 return c.skipNinja
1229}
1230
Anton Hansson5a7861a2021-06-04 10:09:01 +01001231func (c *configImpl) SetSkipNinja(v bool) {
1232 c.skipNinja = v
1233}
1234
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001235func (c *configImpl) SkipConfig() bool {
1236 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001237}
1238
Jihoon Kang1bff0342023-01-17 20:40:22 +00001239func (c *configImpl) BuildFromTextStub() bool {
1240 return c.buildFromTextStub
1241}
1242
Dan Willemsen1e704462016-08-21 15:17:17 -07001243func (c *configImpl) TargetProduct() string {
1244 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1245 return v
1246 }
1247 panic("TARGET_PRODUCT is not defined")
1248}
1249
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001250func (c *configImpl) TargetProductOrErr() (string, error) {
1251 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1252 return v, nil
1253 }
1254 return "", fmt.Errorf("TARGET_PRODUCT is not defined")
1255}
1256
Dan Willemsen02781d52017-05-12 19:28:13 -07001257func (c *configImpl) TargetDevice() string {
1258 return c.targetDevice
1259}
1260
1261func (c *configImpl) SetTargetDevice(device string) {
1262 c.targetDevice = device
1263}
1264
1265func (c *configImpl) TargetBuildVariant() string {
1266 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1267 return v
1268 }
1269 panic("TARGET_BUILD_VARIANT is not defined")
1270}
1271
Dan Willemsen1e704462016-08-21 15:17:17 -07001272func (c *configImpl) KatiArgs() []string {
1273 return c.katiArgs
1274}
1275
1276func (c *configImpl) Parallel() int {
1277 return c.parallel
1278}
1279
Sam Delmerico98a73292023-02-21 11:50:29 -05001280func (c *configImpl) GetSourceRootDirs() []string {
1281 return c.sourceRootDirs
1282}
1283
1284func (c *configImpl) SetSourceRootDirs(i []string) {
1285 c.sourceRootDirs = i
1286}
1287
Spandan Dasc5763832022-11-08 18:42:16 +00001288func (c *configImpl) GetIncludeTags() []string {
1289 return c.includeTags
1290}
1291
1292func (c *configImpl) SetIncludeTags(i []string) {
1293 c.includeTags = i
1294}
1295
MarkDacek6614d9c2022-12-07 21:57:38 +00001296func (c *configImpl) GetLogsPrefix() string {
1297 return c.logsPrefix
1298}
1299
1300func (c *configImpl) SetLogsPrefix(prefix string) {
1301 c.logsPrefix = prefix
1302}
1303
Colin Cross8b8bec32019-11-15 13:18:43 -08001304func (c *configImpl) HighmemParallel() int {
1305 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1306 return i
1307 }
1308
1309 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1310 parallel := c.Parallel()
1311 if c.UseRemoteBuild() {
1312 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1313 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1314 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1315 // Return 1/16th of the size of the local pool, rounding up.
1316 return (parallel + 15) / 16
1317 } else if c.totalRAM == 0 {
1318 // Couldn't detect the total RAM, don't restrict highmem processes.
1319 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001320 } else if c.totalRAM <= 16*1024*1024*1024 {
1321 // Less than 16GB of ram, restrict to 1 highmem processes
1322 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001323 } else if c.totalRAM <= 32*1024*1024*1024 {
1324 // Less than 32GB of ram, restrict to 2 highmem processes
1325 return 2
1326 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1327 // If less than 8GB total RAM per process, reduce the number of highmem processes
1328 return p
1329 }
1330 // No restriction on highmem processes
1331 return parallel
1332}
1333
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001334func (c *configImpl) TotalRAM() uint64 {
1335 return c.totalRAM
1336}
1337
Kousik Kumarec478642020-09-21 13:39:24 -04001338// ForceUseGoma determines whether we should override Goma deprecation
1339// and use Goma for the current build or not.
1340func (c *configImpl) ForceUseGoma() bool {
1341 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1342 v = strings.TrimSpace(v)
1343 if v != "" && v != "false" {
1344 return true
1345 }
1346 }
1347 return false
1348}
1349
Dan Willemsen1e704462016-08-21 15:17:17 -07001350func (c *configImpl) UseGoma() bool {
1351 if v, ok := c.environ.Get("USE_GOMA"); ok {
1352 v = strings.TrimSpace(v)
1353 if v != "" && v != "false" {
1354 return true
1355 }
1356 }
1357 return false
1358}
1359
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001360func (c *configImpl) StartGoma() bool {
1361 if !c.UseGoma() {
1362 return false
1363 }
1364
1365 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1366 v = strings.TrimSpace(v)
1367 if v != "" && v != "false" {
1368 return false
1369 }
1370 }
1371 return true
1372}
1373
Ramy Medhatbbf25672019-07-17 12:30:04 +00001374func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001375 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001376 v = strings.TrimSpace(v)
1377 if v != "" && v != "false" {
1378 return true
1379 }
1380 }
1381 return false
1382}
1383
Chris Parsonsef615e52022-08-18 22:04:11 -04001384func (c *configImpl) BazelBuildEnabled() bool {
Chris Parsons21f80272023-06-15 04:02:28 +00001385 return c.bazelProdMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001386}
1387
Ramy Medhatbbf25672019-07-17 12:30:04 +00001388func (c *configImpl) StartRBE() bool {
1389 if !c.UseRBE() {
1390 return false
1391 }
1392
1393 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1394 v = strings.TrimSpace(v)
1395 if v != "" && v != "false" {
1396 return false
1397 }
1398 }
1399 return true
1400}
1401
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001402func (c *configImpl) rbeProxyLogsDir() string {
1403 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001404 if v, ok := c.environ.Get(f); ok {
1405 return v
1406 }
1407 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001408 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1409 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001410}
1411
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001412func (c *configImpl) rbeCacheDir() string {
1413 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1414 if v, ok := c.environ.Get(f); ok {
1415 return v
1416 }
1417 }
1418 return shared.JoinPath(c.SoongOutDir(), "rbe")
1419}
1420
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001421func (c *configImpl) shouldCleanupRBELogsDir() bool {
1422 // Perform a log directory cleanup only when the log directory
1423 // is auto created by the build rather than user-specified.
1424 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1425 if _, ok := c.environ.Get(f); ok {
1426 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001427 }
1428 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001429 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001430}
1431
1432func (c *configImpl) rbeExecRoot() string {
1433 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1434 if v, ok := c.environ.Get(f); ok {
1435 return v
1436 }
1437 }
1438 wd, err := os.Getwd()
1439 if err != nil {
1440 return ""
1441 }
1442 return wd
1443}
1444
1445func (c *configImpl) rbeDir() string {
1446 if v, ok := c.environ.Get("RBE_DIR"); ok {
1447 return v
1448 }
1449 return "prebuilts/remoteexecution-client/live/"
1450}
1451
1452func (c *configImpl) rbeReproxy() string {
1453 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1454 if v, ok := c.environ.Get(f); ok {
1455 return v
1456 }
1457 }
1458 return filepath.Join(c.rbeDir(), "reproxy")
1459}
1460
1461func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001462 credFlags := []string{
1463 "use_application_default_credentials",
1464 "use_gce_credentials",
1465 "credential_file",
1466 "use_google_prod_creds",
1467 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001468 for _, cf := range credFlags {
1469 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1470 if v, ok := c.environ.Get(f); ok {
1471 v = strings.TrimSpace(v)
1472 if v != "" && v != "false" && v != "0" {
1473 return "RBE_" + cf, v
1474 }
1475 }
1476 }
1477 }
1478 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001479}
1480
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001481func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1482 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1483 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1484
1485 name := filepath.Join(dir, base)
1486 if len(name) < maxNameLen {
1487 return name, nil
1488 }
1489
1490 name = filepath.Join("/tmp", base)
1491 if len(name) < maxNameLen {
1492 return name, nil
1493 }
1494
1495 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1496}
1497
Kousik Kumar7bc78192022-04-27 14:52:56 -04001498// IsGooglerEnvironment returns true if the current build is running
1499// on a Google developer machine and false otherwise.
1500func (c *configImpl) IsGooglerEnvironment() bool {
1501 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1502 if v, ok := c.environ.Get(cf); ok {
1503 return v == "googler"
1504 }
1505 return false
1506}
1507
1508// GoogleProdCredsExist determine whether credentials exist on the
1509// Googler machine to use remote execution.
1510func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001511 if googleProdCredsExistCache {
1512 return googleProdCredsExistCache
1513 }
Saagar Jhaf513b232023-05-26 00:17:55 +00001514 if _, err := exec.Command("/usr/bin/gcertstatus").Output(); err != nil {
Kousik Kumar7bc78192022-04-27 14:52:56 -04001515 return false
1516 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001517 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001518 return true
1519}
1520
1521// UseRemoteBuild indicates whether to use a remote build acceleration system
1522// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001523func (c *configImpl) UseRemoteBuild() bool {
1524 return c.UseGoma() || c.UseRBE()
1525}
1526
Kousik Kumar7bc78192022-04-27 14:52:56 -04001527// StubbyExists checks whether the stubby binary exists on the machine running
1528// the build.
1529func (c *configImpl) StubbyExists() bool {
1530 if _, err := exec.LookPath("stubby"); err != nil {
1531 return false
1532 }
1533 return true
1534}
1535
Dan Willemsen1e704462016-08-21 15:17:17 -07001536// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001537// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001538// still limited by Parallel()
1539func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001540 if !c.UseRemoteBuild() {
1541 return 0
1542 }
1543 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1544 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001545 }
1546 return 500
1547}
1548
1549func (c *configImpl) SetKatiArgs(args []string) {
1550 c.katiArgs = args
1551}
1552
1553func (c *configImpl) SetNinjaArgs(args []string) {
1554 c.ninjaArgs = args
1555}
1556
1557func (c *configImpl) SetKatiSuffix(suffix string) {
1558 c.katiSuffix = suffix
1559}
1560
Dan Willemsene0879fc2017-08-04 15:06:27 -07001561func (c *configImpl) LastKatiSuffixFile() string {
1562 return filepath.Join(c.OutDir(), "last_kati_suffix")
1563}
1564
1565func (c *configImpl) HasKatiSuffix() bool {
1566 return c.katiSuffix != ""
1567}
1568
Dan Willemsen1e704462016-08-21 15:17:17 -07001569func (c *configImpl) KatiEnvFile() string {
1570 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1571}
1572
Dan Willemsen29971232018-09-26 14:58:30 -07001573func (c *configImpl) KatiBuildNinjaFile() string {
1574 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001575}
1576
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001577func (c *configImpl) KatiPackageNinjaFile() string {
1578 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1579}
1580
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001581func (c *configImpl) SoongVarsFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001582 targetProduct, err := c.TargetProductOrErr()
1583 if err != nil {
1584 return filepath.Join(c.SoongOutDir(), "soong.variables")
1585 } else {
1586 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+".variables")
1587 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001588}
1589
Dan Willemsen1e704462016-08-21 15:17:17 -07001590func (c *configImpl) SoongNinjaFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001591 targetProduct, err := c.TargetProductOrErr()
1592 if err != nil {
1593 return filepath.Join(c.SoongOutDir(), "build.ninja")
1594 } else {
1595 return filepath.Join(c.SoongOutDir(), "build."+targetProduct+".ninja")
1596 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001597}
1598
1599func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001600 if c.katiSuffix == "" {
1601 return filepath.Join(c.OutDir(), "combined.ninja")
1602 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001603 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1604}
1605
1606func (c *configImpl) SoongAndroidMk() string {
1607 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1608}
1609
1610func (c *configImpl) SoongMakeVarsMk() string {
1611 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1612}
1613
Dan Willemsenf052f782017-05-18 15:29:04 -07001614func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001615 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001616}
1617
Dan Willemsen02781d52017-05-12 19:28:13 -07001618func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001619 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1620}
1621
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001622func (c *configImpl) KatiPackageMkDir() string {
1623 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1624}
1625
Dan Willemsenf052f782017-05-18 15:29:04 -07001626func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001627 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001628}
1629
1630func (c *configImpl) HostOut() string {
1631 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1632}
1633
1634// This probably needs to be multi-valued, so not exporting it for now
1635func (c *configImpl) hostCrossOut() string {
1636 if runtime.GOOS == "linux" {
1637 return filepath.Join(c.hostOutRoot(), "windows-x86")
1638 } else {
1639 return ""
1640 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001641}
1642
Dan Willemsen1e704462016-08-21 15:17:17 -07001643func (c *configImpl) HostPrebuiltTag() string {
1644 if runtime.GOOS == "linux" {
1645 return "linux-x86"
1646 } else if runtime.GOOS == "darwin" {
1647 return "darwin-x86"
1648 } else {
1649 panic("Unsupported OS")
1650 }
1651}
Dan Willemsenf173d592017-04-27 14:28:00 -07001652
Dan Willemsen8122bd52017-10-12 20:20:41 -07001653func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001654 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1655 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001656 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1657 if _, err := os.Stat(asan); err == nil {
1658 return asan
1659 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001660 }
1661 }
1662 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1663}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001664
1665func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1666 c.brokenDupRules = val
1667}
1668
1669func (c *configImpl) BuildBrokenDupRules() bool {
1670 return c.brokenDupRules
1671}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001672
Dan Willemsen25e6f092019-04-09 10:22:43 -07001673func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1674 c.brokenUsesNetwork = val
1675}
1676
1677func (c *configImpl) BuildBrokenUsesNetwork() bool {
1678 return c.brokenUsesNetwork
1679}
1680
Dan Willemsene3336352020-01-02 19:10:38 -08001681func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1682 c.brokenNinjaEnvVars = val
1683}
1684
1685func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1686 return c.brokenNinjaEnvVars
1687}
1688
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001689func (c *configImpl) SetTargetDeviceDir(dir string) {
1690 c.targetDeviceDir = dir
1691}
1692
1693func (c *configImpl) TargetDeviceDir() string {
1694 return c.targetDeviceDir
1695}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001696
Patrice Arruda219eef32020-06-01 17:29:30 +00001697func (c *configImpl) BuildDateTime() string {
1698 return c.buildDateTime
1699}
1700
1701func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001702 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001703}
Patrice Arruda83842d72020-12-08 19:42:08 +00001704
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001705// LogsDir returns the absolute path to the logs directory where build log and
1706// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001707// directory. If the argument dist is specified, the logs directory
1708// is <dist_dir>/logs.
1709func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001710 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001711 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001712 // 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 -05001713 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001714 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001715 absDir, err := filepath.Abs(dir)
1716 if err != nil {
1717 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1718 os.Exit(1)
1719 }
1720 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001721}
1722
1723// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1724// where the bazel profiles are located.
1725func (c *configImpl) BazelMetricsDir() string {
1726 return filepath.Join(c.LogsDir(), "bazel_metrics")
1727}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001728
Chris Parsons53f68ae2022-03-03 12:01:40 -05001729// MkFileMetrics returns the file path for make-related metrics.
1730func (c *configImpl) MkMetrics() string {
1731 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1732}
1733
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001734func (c *configImpl) SetEmptyNinjaFile(v bool) {
1735 c.emptyNinjaFile = v
1736}
1737
1738func (c *configImpl) EmptyNinjaFile() bool {
1739 return c.emptyNinjaFile
1740}
Yu Liu6e13b402021-07-27 14:29:06 -07001741
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001742func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1743 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1744}
1745
Chris Parsons9402ca82023-02-23 17:28:06 -05001746func (c *configImpl) IsPersistentBazelEnabled() bool {
1747 return c.Environment().IsEnvTrue("USE_PERSISTENT_BAZEL")
1748}
1749
Chris Parsonsc83398f2023-05-31 18:41:41 +00001750// GetBazeliskBazelVersion returns the Bazel version to use for this build,
1751// or the empty string if the current canonical prod Bazel should be used.
1752// This environment variable should only be set to debug the build system.
1753// The Bazel version, if set, will be passed to Bazelisk, and Bazelisk will
1754// handle downloading and invoking the correct Bazel binary.
1755func (c *configImpl) GetBazeliskBazelVersion() string {
1756 value, _ := c.Environment().Get("USE_BAZEL_VERSION")
1757 return value
1758}
1759
MarkDacekd06db5d2022-11-29 00:47:59 +00001760func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1761 return c.bazelForceEnabledModules
1762}
1763
MarkDacekd0e7cd32022-12-02 22:22:40 +00001764func (c *configImpl) SkipMetricsUpload() bool {
1765 return c.skipMetricsUpload
1766}
1767
MarkDacekf47e1422023-04-19 16:47:36 +00001768func (c *configImpl) EnsureAllowlistIntegrity() bool {
1769 return c.ensureAllowlistIntegrity
1770}
1771
MarkDacek6614d9c2022-12-07 21:57:38 +00001772// Returns a Time object if one was passed via a command-line flag.
1773// Otherwise returns the passed default.
1774func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1775 if c.buildStartedTime == 0 {
1776 return defaultTime
1777 }
1778 return time.UnixMilli(c.buildStartedTime)
1779}
1780
MarkDacekd33c2fd2023-05-04 20:40:04 +00001781func (c *configImpl) BazelExitCode() int32 {
1782 return c.bazelExitCode
1783}
1784
Yu Liu6e13b402021-07-27 14:29:06 -07001785func GetMetricsUploader(topDir string, env *Environment) string {
1786 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1787 metricsUploader := filepath.Join(topDir, p)
1788 if _, err := os.Stat(metricsUploader); err == nil {
1789 return metricsUploader
1790 }
1791 }
1792
1793 return ""
1794}