blob: a755d14fddad78209fe26164762eb27a333e6b85 [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 Kumar84bd5bf2022-01-26 23:32:22 -050018 "context"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050019 "encoding/json"
Ramy Medhat0fc67eb2020-08-12 01:26:23 -040020 "fmt"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050021 "io/ioutil"
Kousik Kumar4c180ad2022-05-27 07:48:37 -040022 "math/rand"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080023 "os"
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050024 "os/exec"
Dan Willemsen1e704462016-08-21 15:17:17 -070025 "path/filepath"
26 "runtime"
27 "strconv"
28 "strings"
Kousik Kumar4c180ad2022-05-27 07:48:37 -040029 "syscall"
Nan Zhang2e6a4ff2018-02-14 13:27:26 -080030 "time"
Jeff Gastonefc1b412017-03-29 17:29:06 -070031
32 "android/soong/shared"
Kousik Kumarec478642020-09-21 13:39:24 -040033
Dan Willemsen4591b642021-05-24 14:24:12 -070034 "google.golang.org/protobuf/proto"
Patrice Arruda96850362020-08-11 20:41:11 +000035
36 smpb "android/soong/ui/metrics/metrics_proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070037)
38
Kousik Kumar3ff037e2022-01-25 22:11:01 -050039const (
Chris Parsons53f68ae2022-03-03 12:01:40 -050040 envConfigDir = "vendor/google/tools/soong_config"
41 jsonSuffix = "json"
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050042
Chris Parsons53f68ae2022-03-03 12:01:40 -050043 configFetcher = "vendor/google/tools/soong/expconfigfetcher"
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050044 envConfigFetchTimeout = 10 * time.Second
Kousik Kumar3ff037e2022-01-25 22:11:01 -050045)
46
Kousik Kumar4c180ad2022-05-27 07:48:37 -040047var (
Kevin Dagostino096ab2f2023-03-03 19:47:17 +000048 rbeRandPrefix int
49 googleProdCredsExistCache bool
Kousik Kumar4c180ad2022-05-27 07:48:37 -040050)
51
52func init() {
53 rand.Seed(time.Now().UnixNano())
54 rbeRandPrefix = rand.Intn(1000)
55}
56
Dan Willemsen1e704462016-08-21 15:17:17 -070057type Config struct{ *configImpl }
58
59type configImpl struct {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020060 // Some targets that are implemented in soong_build
61 // (bp2build, json-module-graph) are not here and have their own bits below.
Colin Cross28f527c2019-11-26 16:19:04 -080062 arguments []string
63 goma bool
64 environ *Environment
65 distDir string
66 buildDateTime string
MarkDacek6614d9c2022-12-07 21:57:38 +000067 logsPrefix string
Dan Willemsen1e704462016-08-21 15:17:17 -070068
69 // From the arguments
MarkDacekd0e7cd32022-12-02 22:22:40 +000070 parallel int
71 keepGoing int
72 verbose bool
73 checkbuild bool
74 dist bool
75 jsonModuleGraph bool
76 apiBp2build bool // Generate BUILD files for Soong modules that contribute APIs
77 bp2build bool
78 queryview bool
79 reportMkMetrics bool // Collect and report mk2bp migration progress metrics.
80 soongDocs bool
LaMont Jones52a72432023-03-09 18:19:35 +000081 multitreeBuild bool // This is a multitree build.
MarkDacekd0e7cd32022-12-02 22:22:40 +000082 skipConfig bool
83 skipKati bool
84 skipKatiNinja bool
85 skipSoong bool
86 skipNinja bool
87 skipSoongTests bool
88 searchApiDir bool // Scan the Android.bp files generated in out/api_surfaces
89 skipMetricsUpload bool
MarkDacek6614d9c2022-12-07 21:57:38 +000090 buildStartedTime int64 // For metrics-upload-only - manually specify a build-started time
Jihoon Kang1bff0342023-01-17 20:40:22 +000091 buildFromTextStub bool
Dan Willemsen1e704462016-08-21 15:17:17 -070092
93 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070094 katiArgs []string
95 ninjaArgs []string
96 katiSuffix string
97 targetDevice string
98 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +000099 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -0700100
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800101 // Autodetected
102 totalRAM uint64
103
Dan Willemsene3336352020-01-02 19:10:38 -0800104 brokenDupRules bool
105 brokenUsesNetwork bool
106 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -0700107
108 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000109
MarkDacekb78465d2022-10-18 20:10:16 +0000110 bazelProdMode bool
111 bazelDevMode bool
112 bazelStagingMode bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000113
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700114 // Set by multiproduct_kati
115 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700116
117 metricsUploader string
MarkDacekd06db5d2022-11-29 00:47:59 +0000118
119 bazelForceEnabledModules string
Spandan Dasc5763832022-11-08 18:42:16 +0000120
Sam Delmerico98a73292023-02-21 11:50:29 -0500121 includeTags []string
122 sourceRootDirs []string
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900123
124 // Data source to write ninja weight list
125 ninjaWeightListSource NinjaWeightListSource
Dan Willemsen1e704462016-08-21 15:17:17 -0700126}
127
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900128type NinjaWeightListSource uint
129
130const (
131 // ninja doesn't use weight list.
132 NOT_USED NinjaWeightListSource = iota
133 // ninja uses weight list based on previous builds by ninja log
134 NINJA_LOG
135 // ninja thinks every task has the same weight.
136 EVENLY_DISTRIBUTED
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900137 // ninja uses an external custom weight list
138 EXTERNAL_FILE
Jeongik Chae114e602023-03-19 00:12:39 +0900139 // ninja uses a prioritized module list from Soong
140 HINT_FROM_SOONG
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900141)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800142const srcDirFileCheck = "build/soong/root.bp"
143
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700144var buildFiles = []string{"Android.mk", "Android.bp"}
145
Patrice Arruda13848222019-04-22 17:12:02 -0700146type BuildAction uint
147
148const (
149 // Builds all of the modules and their dependencies of a specified directory, relative to the root
150 // directory of the source tree.
151 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
152
153 // Builds all of the modules and their dependencies of a list of specified directories. All specified
154 // directories are relative to the root directory of the source tree.
155 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700156
157 // Build a list of specified modules. If none was specified, simply build the whole source tree.
158 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700159)
160
161// checkTopDir validates that the current directory is at the root directory of the source tree.
162func checkTopDir(ctx Context) {
163 if _, err := os.Stat(srcDirFileCheck); err != nil {
164 if os.IsNotExist(err) {
165 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
166 }
167 ctx.Fatalln("Error verifying tree state:", err)
168 }
169}
170
Kousik Kumarc8818332023-01-16 16:33:05 +0000171// fetchEnvConfig optionally fetches a configuration file that can then subsequently be
172// loaded into Soong environment to control certain aspects of build behavior (e.g., enabling RBE).
173// If a configuration file already exists on disk, the fetch is run in the background
174// so as to NOT block the rest of the build execution.
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500175func fetchEnvConfig(ctx Context, config *configImpl, envConfigName string) error {
David Goldsmith62243a32022-04-08 13:42:04 +0000176 configName := envConfigName + "." + jsonSuffix
Kousik Kumarc75e1292022-07-07 02:20:51 +0000177 expConfigFetcher := &smpb.ExpConfigFetcher{Filename: &configName}
David Goldsmith62243a32022-04-08 13:42:04 +0000178 defer func() {
179 ctx.Metrics.ExpConfigFetcher(expConfigFetcher)
180 }()
Kousik Kumarc75e1292022-07-07 02:20:51 +0000181 if !config.GoogleProdCredsExist() {
182 status := smpb.ExpConfigFetcher_MISSING_GCERT
183 expConfigFetcher.Status = &status
184 return nil
185 }
David Goldsmith62243a32022-04-08 13:42:04 +0000186
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500187 s, err := os.Stat(configFetcher)
188 if err != nil {
189 if os.IsNotExist(err) {
190 return nil
191 }
192 return err
193 }
194 if s.Mode()&0111 == 0 {
David Goldsmith62243a32022-04-08 13:42:04 +0000195 status := smpb.ExpConfigFetcher_ERROR
196 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500197 return fmt.Errorf("configuration fetcher binary %v is not executable: %v", configFetcher, s.Mode())
198 }
199
Kousik Kumarc8818332023-01-16 16:33:05 +0000200 configExists := false
201 outConfigFilePath := filepath.Join(config.OutDir(), configName)
202 if _, err := os.Stat(outConfigFilePath); err == nil {
203 configExists = true
204 }
205
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500206 tCtx, cancel := context.WithTimeout(ctx, envConfigFetchTimeout)
David Goldsmith62243a32022-04-08 13:42:04 +0000207 fetchStart := time.Now()
208 cmd := exec.CommandContext(tCtx, configFetcher, "-output_config_dir", config.OutDir(),
209 "-output_config_name", configName)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500210 if err := cmd.Start(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000211 status := smpb.ExpConfigFetcher_ERROR
212 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500213 return err
214 }
215
Kousik Kumarc8818332023-01-16 16:33:05 +0000216 fetchCfg := func() error {
217 if err := cmd.Wait(); err != nil {
218 status := smpb.ExpConfigFetcher_ERROR
219 expConfigFetcher.Status = &status
220 return err
221 }
222 fetchEnd := time.Now()
223 expConfigFetcher.Micros = proto.Uint64(uint64(fetchEnd.Sub(fetchStart).Microseconds()))
224 expConfigFetcher.Filename = proto.String(outConfigFilePath)
225
226 if _, err := os.Stat(outConfigFilePath); err != nil {
227 status := smpb.ExpConfigFetcher_NO_CONFIG
228 expConfigFetcher.Status = &status
229 return err
230 }
David Goldsmith62243a32022-04-08 13:42:04 +0000231 status := smpb.ExpConfigFetcher_CONFIG
232 expConfigFetcher.Status = &status
Kousik Kumarc8818332023-01-16 16:33:05 +0000233 return nil
David Goldsmith62243a32022-04-08 13:42:04 +0000234 }
Kousik Kumarc8818332023-01-16 16:33:05 +0000235
236 // If a config file does not exist, wait for the config file to be fetched. Otherwise
237 // fetch the config file in the background and return immediately.
238 if !configExists {
239 defer cancel()
240 return fetchCfg()
241 }
242
243 go func() {
244 defer cancel()
245 if err := fetchCfg(); err != nil {
246 ctx.Verbosef("Failed to fetch config file %v: %v\n", configName, err)
247 }
248 }()
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500249 return nil
250}
251
MarkDacek7901e582023-01-09 19:48:01 +0000252func loadEnvConfig(ctx Context, config *configImpl, bc string) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500253 if bc == "" {
254 return nil
255 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500256
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500257 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500258 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500259 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500260 envConfigDir,
261 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500262 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500263 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
264 envVarsJSON, err := ioutil.ReadFile(cfgFile)
265 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500266 continue
267 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500268 ctx.Verbosef("Loading config file %v\n", cfgFile)
269 var envVars map[string]map[string]string
270 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
271 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
272 continue
273 }
274 for k, v := range envVars["env"] {
275 if os.Getenv(k) != "" {
276 continue
277 }
278 config.environ.Set(k, v)
279 }
280 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
281 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500282 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500283
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500284 return nil
285}
286
Chris Parsonsb6e96902022-10-31 20:08:45 -0400287func defaultBazelProdMode(cfg *configImpl) bool {
MarkDacekd06db5d2022-11-29 00:47:59 +0000288 // Environment flag to disable Bazel for users which experience
Chris Parsonsb6e96902022-10-31 20:08:45 -0400289 // broken bazel-handled builds, or significant performance regressions.
290 if cfg.IsBazelMixedBuildForceDisabled() {
291 return false
292 }
293 // Darwin-host builds are currently untested with Bazel.
294 if runtime.GOOS == "darwin" {
295 return false
296 }
Chris Parsons035e03a2022-11-01 14:25:45 -0400297 return true
Chris Parsonsb6e96902022-10-31 20:08:45 -0400298}
299
MarkDacek6614d9c2022-12-07 21:57:38 +0000300func UploadOnlyConfig(ctx Context, _ ...string) Config {
301 ret := &configImpl{
302 environ: OsEnvironment(),
303 sandboxConfig: &SandboxConfig{},
304 }
MarkDacek7901e582023-01-09 19:48:01 +0000305 srcDir := absPath(ctx, ".")
306 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
307 if err := loadEnvConfig(ctx, ret, bc); err != nil {
308 ctx.Fatalln("Failed to parse env config files: %v", err)
309 }
310 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
MarkDacek6614d9c2022-12-07 21:57:38 +0000311 return Config{ret}
312}
313
Dan Willemsen1e704462016-08-21 15:17:17 -0700314func NewConfig(ctx Context, args ...string) Config {
315 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000316 environ: OsEnvironment(),
317 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700318 }
319
Patrice Arruda90109172020-07-28 18:07:27 +0000320 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700321 ret.parallel = runtime.NumCPU() + 2
322 ret.keepGoing = 1
323
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800324 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700325 ret.parseArgs(ctx, args)
Jeongik Chae114e602023-03-19 00:12:39 +0900326
327 if ret.ninjaWeightListSource == HINT_FROM_SOONG {
328 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "true")
329 }
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800330 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700331 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
332 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
333 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800334 outDir := "out"
335 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
336 if wd, err := os.Getwd(); err != nil {
337 ctx.Fatalln("Failed to get working directory:", err)
338 } else {
339 outDir = filepath.Join(baseDir, filepath.Base(wd))
340 }
341 }
342 ret.environ.Set("OUT_DIR", outDir)
343 }
344
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500345 // loadEnvConfig needs to know what the OUT_DIR is, so it should
346 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000347 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
348
349 if bc != "" {
350 if err := fetchEnvConfig(ctx, ret, bc); err != nil {
351 ctx.Verbosef("Failed to fetch config file: %v\n", err)
Kousik Kumarc8818332023-01-16 16:33:05 +0000352 }
353 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000354 ctx.Fatalln("Failed to parse env config files: %v", err)
355 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500356 }
357
Dan Willemsen2d31a442018-10-20 21:33:41 -0700358 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
359 ret.distDir = filepath.Clean(distDir)
360 } else {
361 ret.distDir = filepath.Join(ret.OutDir(), "dist")
362 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700363
Spandan Das05063612021-06-25 01:39:04 +0000364 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
365 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
366 }
367
Dan Willemsen1e704462016-08-21 15:17:17 -0700368 ret.environ.Unset(
369 // We're already using it
370 "USE_SOONG_UI",
371
372 // We should never use GOROOT/GOPATH from the shell environment
373 "GOROOT",
374 "GOPATH",
375
376 // These should only come from Soong, not the environment.
377 "CLANG",
378 "CLANG_CXX",
379 "CCC_CC",
380 "CCC_CXX",
381
382 // Used by the goma compiler wrapper, but should only be set by
383 // gomacc
384 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800385
386 // We handle this above
387 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700388
Dan Willemsen2d31a442018-10-20 21:33:41 -0700389 // This is handled above too, and set for individual commands later
390 "DIST_DIR",
391
Dan Willemsen68a09852017-04-18 13:56:57 -0700392 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000393 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700394 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700395 "DISPLAY",
396 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000397 "JAVAC",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700398 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700399 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700400
401 // Drop make flags
402 "MAKEFLAGS",
403 "MAKELEVEL",
404 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700405
406 // Set in envsetup.sh, reset in makefiles
407 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700408
409 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
410 "ANDROID_BUILD_TOP",
411 "ANDROID_HOST_OUT",
412 "ANDROID_PRODUCT_OUT",
413 "ANDROID_HOST_OUT_TESTCASES",
414 "ANDROID_TARGET_OUT_TESTCASES",
415 "ANDROID_TOOLCHAIN",
416 "ANDROID_TOOLCHAIN_2ND_ARCH",
417 "ANDROID_DEV_SCRIPTS",
418 "ANDROID_EMULATOR_PREBUILTS",
419 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700420 )
421
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400422 if ret.UseGoma() || ret.ForceUseGoma() {
423 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
424 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400425 }
426
Dan Willemsen1e704462016-08-21 15:17:17 -0700427 // Tell python not to spam the source tree with .pyc files.
428 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
429
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400430 tmpDir := absPath(ctx, ret.TempDir())
431 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800432
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700433 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
434 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
435 "llvm-binutils-stable/llvm-symbolizer")
436 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
437
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800438 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700439 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800440
Yu Liu6e13b402021-07-27 14:29:06 -0700441 srcDir := absPath(ctx, ".")
442 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700443 ctx.Println("You are building in a directory whose absolute path contains a space character:")
444 ctx.Println()
445 ctx.Printf("%q\n", srcDir)
446 ctx.Println()
447 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700448 }
449
Yu Liu6e13b402021-07-27 14:29:06 -0700450 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
451
Dan Willemsendb8457c2017-05-12 16:38:17 -0700452 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700453 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
454 ctx.Println()
455 ctx.Printf("%q\n", outDir)
456 ctx.Println()
457 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700458 }
459
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000460 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700461 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
462 ctx.Println()
463 ctx.Printf("%q\n", distDir)
464 ctx.Println()
465 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700466 }
467
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700468 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000469 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
470 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100471 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800472 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700473 javaHome := func() string {
474 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
475 return override
476 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000477 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
478 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 +0100479 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000480 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
481 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
482 }
483 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700484 }()
485 absJavaHome := absPath(ctx, javaHome)
486
Dan Willemsened869522018-01-08 14:58:46 -0800487 ret.configureLocale(ctx)
488
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700489 newPath := []string{filepath.Join(absJavaHome, "bin")}
490 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
491 newPath = append(newPath, path)
492 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100493
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700494 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
495 ret.environ.Set("JAVA_HOME", absJavaHome)
496 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000497 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
498 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100499 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700500 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
501
LaMont Jones52a72432023-03-09 18:19:35 +0000502 if ret.MultitreeBuild() {
503 ret.environ.Set("MULTITREE_BUILD", "true")
504 }
505
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800506 outDir := ret.OutDir()
507 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800508 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800509 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800510 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800511 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800512 }
Colin Cross28f527c2019-11-26 16:19:04 -0800513
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800514 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
515
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400516 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400517 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400518 ret.environ.Set(k, v)
519 }
520 }
521
Jihoon Kang1bff0342023-01-17 20:40:22 +0000522 if ret.BuildFromTextStub() {
523 // TODO(b/271443071): support hidden api check for from-text stub build
524 ret.environ.Set("UNSAFE_DISABLE_HIDDENAPI_FLAGS", "true")
525 }
526
Patrice Arruda83842d72020-12-08 19:42:08 +0000527 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800528 if err := os.RemoveAll(bpd); err != nil {
529 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
530 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000531
Patrice Arruda96850362020-08-11 20:41:11 +0000532 c := Config{ret}
533 storeConfigMetrics(ctx, c)
534 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700535}
536
Patrice Arruda13848222019-04-22 17:12:02 -0700537// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
538// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700539func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
540 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700541}
542
Patrice Arruda96850362020-08-11 20:41:11 +0000543// storeConfigMetrics selects a set of configuration information and store in
544// the metrics system for further analysis.
545func storeConfigMetrics(ctx Context, config Config) {
546 if ctx.Metrics == nil {
547 return
548 }
549
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400550 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000551
552 s := &smpb.SystemResourceInfo{
553 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
554 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
555 }
556 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000557}
558
Jeongik Cha8d63d562023-03-17 03:52:13 +0900559func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900560 switch s {
561 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900562 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900563 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900564 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900565 case EXTERNAL_FILE:
566 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900567 case HINT_FROM_SOONG:
568 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900569 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900570 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900571 }
572}
573
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400574func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700575 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400576 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
577 UseGoma: proto.Bool(config.UseGoma()),
578 UseRbe: proto.Bool(config.UseRBE()),
579 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
580 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900581 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400582 }
Yu Liue737a992021-10-04 13:21:41 -0700583 c.Targets = append(c.Targets, config.arguments...)
584
585 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400586}
587
Patrice Arruda13848222019-04-22 17:12:02 -0700588// getConfigArgs processes the command arguments based on the build action and creates a set of new
589// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700590func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700591 // The next block of code verifies that the current directory is the root directory of the source
592 // tree. It then finds the relative path of dir based on the root directory of the source tree
593 // and verify that dir is inside of the source tree.
594 checkTopDir(ctx)
595 topDir, err := os.Getwd()
596 if err != nil {
597 ctx.Fatalf("Error retrieving top directory: %v", err)
598 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700599 dir, err = filepath.EvalSymlinks(dir)
600 if err != nil {
601 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
602 }
Patrice Arruda13848222019-04-22 17:12:02 -0700603 dir, err = filepath.Abs(dir)
604 if err != nil {
605 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
606 }
607 relDir, err := filepath.Rel(topDir, dir)
608 if err != nil {
609 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
610 }
611 // If there are ".." in the path, it's not in the source tree.
612 if strings.Contains(relDir, "..") {
613 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
614 }
615
616 configArgs := args[:]
617
618 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
619 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
620 targetNamePrefix := "MODULES-IN-"
621 if inList("GET-INSTALL-PATH", configArgs) {
622 targetNamePrefix = "GET-INSTALL-PATH-IN-"
623 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
624 }
625
Patrice Arruda13848222019-04-22 17:12:02 -0700626 var targets []string
627
628 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700629 case BUILD_MODULES:
630 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700631 case BUILD_MODULES_IN_A_DIRECTORY:
632 // If dir is the root source tree, all the modules are built of the source tree are built so
633 // no need to find the build file.
634 if topDir == dir {
635 break
636 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700637
Patrice Arruda13848222019-04-22 17:12:02 -0700638 buildFile := findBuildFile(ctx, relDir)
639 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700640 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700641 }
Patrice Arruda13848222019-04-22 17:12:02 -0700642 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
643 case BUILD_MODULES_IN_DIRECTORIES:
644 newConfigArgs, dirs := splitArgs(configArgs)
645 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700646 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700647 }
648
649 // Tidy only override all other specified targets.
650 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
651 if tidyOnly == "true" || tidyOnly == "1" {
652 configArgs = append(configArgs, "tidy_only")
653 } else {
654 configArgs = append(configArgs, targets...)
655 }
656
657 return configArgs
658}
659
660// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
661func convertToTarget(dir string, targetNamePrefix string) string {
662 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
663}
664
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700665// hasBuildFile returns true if dir contains an Android build file.
666func hasBuildFile(ctx Context, dir string) bool {
667 for _, buildFile := range buildFiles {
668 _, err := os.Stat(filepath.Join(dir, buildFile))
669 if err == nil {
670 return true
671 }
672 if !os.IsNotExist(err) {
673 ctx.Fatalf("Error retrieving the build file stats: %v", err)
674 }
675 }
676 return false
677}
678
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700679// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
680// in the current and any sub directory of dir. If a build file is not found, traverse the path
681// up by one directory and repeat again until either a build file is found or reached to the root
682// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
683// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700684func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700685 // If the string is empty or ".", assume it is top directory of the source tree.
686 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700687 return ""
688 }
689
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700690 found := false
691 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
692 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
693 if err != nil {
694 return err
695 }
696 if found {
697 return filepath.SkipDir
698 }
699 if info.IsDir() {
700 return nil
701 }
702 for _, buildFile := range buildFiles {
703 if info.Name() == buildFile {
704 found = true
705 return filepath.SkipDir
706 }
707 }
708 return nil
709 })
710 if err != nil {
711 ctx.Fatalf("Error finding Android build file: %v", err)
712 }
713
714 if found {
715 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700716 }
717 }
718
719 return ""
720}
721
722// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
723func splitArgs(args []string) (newArgs []string, dirs []string) {
724 specialArgs := map[string]bool{
725 "showcommands": true,
726 "snod": true,
727 "dist": true,
728 "checkbuild": true,
729 }
730
731 newArgs = []string{}
732 dirs = []string{}
733
734 for _, arg := range args {
735 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
736 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
737 newArgs = append(newArgs, arg)
738 continue
739 }
740
741 if _, ok := specialArgs[arg]; ok {
742 newArgs = append(newArgs, arg)
743 continue
744 }
745
746 dirs = append(dirs, arg)
747 }
748
749 return newArgs, dirs
750}
751
752// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
753// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
754// source root tree where the build action command was invoked. Each directory is validated if the
755// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700756func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700757 for _, dir := range dirs {
758 // The directory may have specified specific modules to build. ":" is the separator to separate
759 // the directory and the list of modules.
760 s := strings.Split(dir, ":")
761 l := len(s)
762 if l > 2 { // more than one ":" was specified.
763 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
764 }
765
766 dir = filepath.Join(relDir, s[0])
767 if _, err := os.Stat(dir); err != nil {
768 ctx.Fatalf("couldn't find directory %s", dir)
769 }
770
771 // Verify that if there are any targets specified after ":". Each target is separated by ",".
772 var newTargets []string
773 if l == 2 && s[1] != "" {
774 newTargets = strings.Split(s[1], ",")
775 if inList("", newTargets) {
776 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
777 }
778 }
779
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700780 // If there are specified targets to build in dir, an android build file must exist for the one
781 // shot build. For the non-targets case, find the appropriate build file and build all the
782 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700783 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700784 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700785 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
786 }
787 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700788 buildFile := findBuildFile(ctx, dir)
789 if buildFile == "" {
790 ctx.Fatalf("Build file not found for %s directory", dir)
791 }
792 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700793 }
794
Patrice Arruda13848222019-04-22 17:12:02 -0700795 targets = append(targets, newTargets...)
796 }
797
Dan Willemsence41e942019-07-29 23:39:30 -0700798 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700799}
800
Dan Willemsen9b587492017-07-10 22:13:00 -0700801func (c *configImpl) parseArgs(ctx Context, args []string) {
802 for i := 0; i < len(args); i++ {
803 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100804 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700805 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200806 } else if arg == "--empty-ninja-file" {
807 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100808 } else if arg == "--skip-ninja" {
809 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700810 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700811 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
812 // but it does run a Kati ninja file if the .kati_enabled marker file was created
813 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000814 c.skipConfig = true
815 c.skipKati = true
816 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100817 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000818 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100819 } else if arg == "--soong-only" {
820 c.skipKati = true
821 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200822 } else if arg == "--config-only" {
823 c.skipKati = true
824 c.skipKatiNinja = true
825 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700826 } else if arg == "--skip-config" {
827 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700828 } else if arg == "--skip-soong-tests" {
829 c.skipSoongTests = true
MarkDacekd0e7cd32022-12-02 22:22:40 +0000830 } else if arg == "--skip-metrics-upload" {
831 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500832 } else if arg == "--mk-metrics" {
833 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000834 } else if arg == "--multitree-build" {
835 c.multitreeBuild = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400836 } else if arg == "--bazel-mode" {
837 c.bazelProdMode = true
838 } else if arg == "--bazel-mode-dev" {
839 c.bazelDevMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000840 } else if arg == "--bazel-mode-staging" {
841 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000842 } else if arg == "--search-api-dir" {
843 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900844 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
845 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
846 if source == "ninja_log" {
847 c.ninjaWeightListSource = NINJA_LOG
848 } else if source == "evenly_distributed" {
849 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
850 } else if source == "not_used" {
851 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900852 } else if source == "soong" {
853 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900854 } else if strings.HasPrefix(source, "file,") {
855 c.ninjaWeightListSource = EXTERNAL_FILE
856 filePath := strings.TrimPrefix(source, "file,")
857 err := validateNinjaWeightList(filePath)
858 if err != nil {
859 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
860 }
861 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
862 if err != nil {
863 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
864 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900865 } else {
866 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
867 }
Jihoon Kang1bff0342023-01-17 20:40:22 +0000868 } else if arg == "--build-from-text-stub" {
869 c.buildFromTextStub = true
MarkDacekb96561e2022-12-02 04:34:43 +0000870 } else if strings.HasPrefix(arg, "--build-command=") {
871 buildCmd := strings.TrimPrefix(arg, "--build-command=")
872 // remove quotations
873 buildCmd = strings.TrimPrefix(buildCmd, "\"")
874 buildCmd = strings.TrimSuffix(buildCmd, "\"")
875 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000876 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
877 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
MarkDacek6614d9c2022-12-07 21:57:38 +0000878 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
879 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
880 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
881 if err == nil {
882 c.buildStartedTime = val
883 } else {
884 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
885 }
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700886 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700887 parseArgNum := func(def int) int {
888 if len(arg) > 2 {
889 p, err := strconv.ParseUint(arg[2:], 10, 31)
890 if err != nil {
891 ctx.Fatalf("Failed to parse %q: %v", arg, err)
892 }
893 return int(p)
894 } else if i+1 < len(args) {
895 p, err := strconv.ParseUint(args[i+1], 10, 31)
896 if err == nil {
897 i++
898 return int(p)
899 }
900 }
901 return def
902 }
903
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700904 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700905 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700906 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700907 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700908 } else {
909 ctx.Fatalln("Unknown option:", arg)
910 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700911 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700912 if k == "OUT_DIR" {
913 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
914 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700915 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700916 } else if arg == "dist" {
917 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200918 } else if arg == "json-module-graph" {
919 c.jsonModuleGraph = true
920 } else if arg == "bp2build" {
921 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000922 } else if arg == "api_bp2build" {
923 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200924 } else if arg == "queryview" {
925 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200926 } else if arg == "soong_docs" {
927 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700928 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700929 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800930 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700931 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700932 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700933 }
934 }
Chris Parsonsb6e96902022-10-31 20:08:45 -0400935 if (!c.bazelProdMode) && (!c.bazelDevMode) && (!c.bazelStagingMode) {
936 c.bazelProdMode = defaultBazelProdMode(c)
937 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700938}
939
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900940func validateNinjaWeightList(weightListFilePath string) (err error) {
941 data, err := os.ReadFile(weightListFilePath)
942 if err != nil {
943 return
944 }
945 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
946 for _, line := range lines {
947 fields := strings.Split(line, ",")
948 if len(fields) != 2 {
949 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
950 }
951 _, err = strconv.Atoi(fields[1])
952 if err != nil {
953 return
954 }
955 }
956 return
957}
958
Dan Willemsened869522018-01-08 14:58:46 -0800959func (c *configImpl) configureLocale(ctx Context) {
960 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
961 output, err := cmd.Output()
962
963 var locales []string
964 if err == nil {
965 locales = strings.Split(string(output), "\n")
966 } else {
967 // If we're unable to list the locales, let's assume en_US.UTF-8
968 locales = []string{"en_US.UTF-8"}
969 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
970 }
971
972 // gettext uses LANGUAGE, which is passed directly through
973
974 // For LANG and LC_*, only preserve the evaluated version of
975 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800976 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800977 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800978 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800979 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800980 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800981 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800982 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800983 }
984
985 c.environ.UnsetWithPrefix("LC_")
986
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800987 if userLang != "" {
988 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800989 }
990
991 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
992 // for others)
993 if inList("C.UTF-8", locales) {
994 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500995 } else if inList("C.utf8", locales) {
996 // These normalize to the same thing
997 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800998 } else if inList("en_US.UTF-8", locales) {
999 c.environ.Set("LANG", "en_US.UTF-8")
1000 } else if inList("en_US.utf8", locales) {
1001 // These normalize to the same thing
1002 c.environ.Set("LANG", "en_US.UTF-8")
1003 } else {
1004 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
1005 }
1006}
1007
Dan Willemsen1e704462016-08-21 15:17:17 -07001008func (c *configImpl) Environment() *Environment {
1009 return c.environ
1010}
1011
1012func (c *configImpl) Arguments() []string {
1013 return c.arguments
1014}
1015
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001016func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001017 if len(c.Arguments()) > 0 {
1018 // Explicit targets requested that are not special targets like b2pbuild
1019 // or the JSON module graph
1020 return true
1021 }
1022
Spandan Das5af0bd32022-09-28 20:43:08 +00001023 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001024 // Command line was empty, the default Ninja target is built
1025 return true
1026 }
1027
Liz Kammer88677422021-12-15 15:03:19 -05001028 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
1029 if c.Dist() && !c.Bp2Build() {
1030 return true
1031 }
1032
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001033 // build.ninja doesn't need to be generated
1034 return false
1035}
1036
Dan Willemsen1e704462016-08-21 15:17:17 -07001037func (c *configImpl) OutDir() string {
1038 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -07001039 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -07001040 }
1041 return "out"
1042}
1043
Dan Willemsen8a073a82017-02-04 17:30:44 -08001044func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -04001045 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001046}
1047
1048func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -07001049 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -08001050}
1051
Dan Willemsen1e704462016-08-21 15:17:17 -07001052func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001053 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001054 return c.arguments
1055 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001056 return c.ninjaArgs
1057}
1058
Jingwen Chen7c6089a2020-11-02 02:56:20 -05001059func (c *configImpl) BazelOutDir() string {
1060 return filepath.Join(c.OutDir(), "bazel")
1061}
1062
Liz Kammer2af5ea82022-11-11 14:21:03 -05001063func (c *configImpl) bazelOutputBase() string {
1064 return filepath.Join(c.BazelOutDir(), "output")
1065}
1066
Dan Willemsen1e704462016-08-21 15:17:17 -07001067func (c *configImpl) SoongOutDir() string {
1068 return filepath.Join(c.OutDir(), "soong")
1069}
1070
Spandan Das394aa322022-11-03 17:02:10 +00001071func (c *configImpl) ApiSurfacesOutDir() string {
1072 return filepath.Join(c.OutDir(), "api_surfaces")
1073}
1074
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001075func (c *configImpl) PrebuiltOS() string {
1076 switch runtime.GOOS {
1077 case "linux":
1078 return "linux-x86"
1079 case "darwin":
1080 return "darwin-x86"
1081 default:
1082 panic("Unknown GOOS")
1083 }
1084}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001085
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001086func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001087 if c.SkipKatiNinja() {
1088 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1089 } else {
1090 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1091 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001092}
1093
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001094func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001095 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001096}
1097
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001098func (c *configImpl) UsedEnvFile(tag string) string {
1099 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1100}
1101
Lukacs T. Berkic541cd22022-10-26 07:26:50 +00001102func (c *configImpl) Bp2BuildFilesMarkerFile() string {
1103 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
1104}
1105
1106func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001107 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +02001108}
1109
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001110func (c *configImpl) SoongDocsHtml() string {
1111 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1112}
1113
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001114func (c *configImpl) QueryviewMarkerFile() string {
1115 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1116}
1117
Spandan Das5af0bd32022-09-28 20:43:08 +00001118func (c *configImpl) ApiBp2buildMarkerFile() string {
1119 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
1120}
1121
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001122func (c *configImpl) ModuleGraphFile() string {
1123 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1124}
1125
kgui67007242022-01-25 13:50:25 +08001126func (c *configImpl) ModuleActionsFile() string {
1127 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1128}
1129
Jeff Gastonefc1b412017-03-29 17:29:06 -07001130func (c *configImpl) TempDir() string {
1131 return shared.TempDirForOutDir(c.SoongOutDir())
1132}
1133
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001134func (c *configImpl) FileListDir() string {
1135 return filepath.Join(c.OutDir(), ".module_paths")
1136}
1137
Dan Willemsen1e704462016-08-21 15:17:17 -07001138func (c *configImpl) KatiSuffix() string {
1139 if c.katiSuffix != "" {
1140 return c.katiSuffix
1141 }
1142 panic("SetKatiSuffix has not been called")
1143}
1144
Colin Cross37193492017-11-16 17:55:00 -08001145// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1146// user is interested in additional checks at the expense of build time.
1147func (c *configImpl) Checkbuild() bool {
1148 return c.checkbuild
1149}
1150
Dan Willemsen8a073a82017-02-04 17:30:44 -08001151func (c *configImpl) Dist() bool {
1152 return c.dist
1153}
1154
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001155func (c *configImpl) JsonModuleGraph() bool {
1156 return c.jsonModuleGraph
1157}
1158
1159func (c *configImpl) Bp2Build() bool {
1160 return c.bp2build
1161}
1162
Spandan Das5af0bd32022-09-28 20:43:08 +00001163func (c *configImpl) ApiBp2build() bool {
1164 return c.apiBp2build
1165}
1166
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001167func (c *configImpl) Queryview() bool {
1168 return c.queryview
1169}
1170
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001171func (c *configImpl) SoongDocs() bool {
1172 return c.soongDocs
1173}
1174
Dan Willemsen1e704462016-08-21 15:17:17 -07001175func (c *configImpl) IsVerbose() bool {
1176 return c.verbose
1177}
1178
LaMont Jones52a72432023-03-09 18:19:35 +00001179func (c *configImpl) MultitreeBuild() bool {
1180 return c.multitreeBuild
1181}
1182
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001183func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1184 return c.ninjaWeightListSource
1185}
1186
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001187func (c *configImpl) SkipKati() bool {
1188 return c.skipKati
1189}
1190
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001191func (c *configImpl) SkipKatiNinja() bool {
1192 return c.skipKatiNinja
1193}
1194
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001195func (c *configImpl) SkipSoong() bool {
1196 return c.skipSoong
1197}
1198
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001199func (c *configImpl) SkipNinja() bool {
1200 return c.skipNinja
1201}
1202
Anton Hansson5a7861a2021-06-04 10:09:01 +01001203func (c *configImpl) SetSkipNinja(v bool) {
1204 c.skipNinja = v
1205}
1206
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001207func (c *configImpl) SkipConfig() bool {
1208 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001209}
1210
Jihoon Kang1bff0342023-01-17 20:40:22 +00001211func (c *configImpl) BuildFromTextStub() bool {
1212 return c.buildFromTextStub
1213}
1214
Dan Willemsen1e704462016-08-21 15:17:17 -07001215func (c *configImpl) TargetProduct() string {
1216 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1217 return v
1218 }
1219 panic("TARGET_PRODUCT is not defined")
1220}
1221
Dan Willemsen02781d52017-05-12 19:28:13 -07001222func (c *configImpl) TargetDevice() string {
1223 return c.targetDevice
1224}
1225
1226func (c *configImpl) SetTargetDevice(device string) {
1227 c.targetDevice = device
1228}
1229
1230func (c *configImpl) TargetBuildVariant() string {
1231 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1232 return v
1233 }
1234 panic("TARGET_BUILD_VARIANT is not defined")
1235}
1236
Dan Willemsen1e704462016-08-21 15:17:17 -07001237func (c *configImpl) KatiArgs() []string {
1238 return c.katiArgs
1239}
1240
1241func (c *configImpl) Parallel() int {
1242 return c.parallel
1243}
1244
Sam Delmerico98a73292023-02-21 11:50:29 -05001245func (c *configImpl) GetSourceRootDirs() []string {
1246 return c.sourceRootDirs
1247}
1248
1249func (c *configImpl) SetSourceRootDirs(i []string) {
1250 c.sourceRootDirs = i
1251}
1252
Spandan Dasc5763832022-11-08 18:42:16 +00001253func (c *configImpl) GetIncludeTags() []string {
1254 return c.includeTags
1255}
1256
1257func (c *configImpl) SetIncludeTags(i []string) {
1258 c.includeTags = i
1259}
1260
MarkDacek6614d9c2022-12-07 21:57:38 +00001261func (c *configImpl) GetLogsPrefix() string {
1262 return c.logsPrefix
1263}
1264
1265func (c *configImpl) SetLogsPrefix(prefix string) {
1266 c.logsPrefix = prefix
1267}
1268
Colin Cross8b8bec32019-11-15 13:18:43 -08001269func (c *configImpl) HighmemParallel() int {
1270 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1271 return i
1272 }
1273
1274 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1275 parallel := c.Parallel()
1276 if c.UseRemoteBuild() {
1277 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1278 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1279 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1280 // Return 1/16th of the size of the local pool, rounding up.
1281 return (parallel + 15) / 16
1282 } else if c.totalRAM == 0 {
1283 // Couldn't detect the total RAM, don't restrict highmem processes.
1284 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001285 } else if c.totalRAM <= 16*1024*1024*1024 {
1286 // Less than 16GB of ram, restrict to 1 highmem processes
1287 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001288 } else if c.totalRAM <= 32*1024*1024*1024 {
1289 // Less than 32GB of ram, restrict to 2 highmem processes
1290 return 2
1291 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1292 // If less than 8GB total RAM per process, reduce the number of highmem processes
1293 return p
1294 }
1295 // No restriction on highmem processes
1296 return parallel
1297}
1298
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001299func (c *configImpl) TotalRAM() uint64 {
1300 return c.totalRAM
1301}
1302
Kousik Kumarec478642020-09-21 13:39:24 -04001303// ForceUseGoma determines whether we should override Goma deprecation
1304// and use Goma for the current build or not.
1305func (c *configImpl) ForceUseGoma() bool {
1306 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1307 v = strings.TrimSpace(v)
1308 if v != "" && v != "false" {
1309 return true
1310 }
1311 }
1312 return false
1313}
1314
Dan Willemsen1e704462016-08-21 15:17:17 -07001315func (c *configImpl) UseGoma() bool {
1316 if v, ok := c.environ.Get("USE_GOMA"); ok {
1317 v = strings.TrimSpace(v)
1318 if v != "" && v != "false" {
1319 return true
1320 }
1321 }
1322 return false
1323}
1324
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001325func (c *configImpl) StartGoma() bool {
1326 if !c.UseGoma() {
1327 return false
1328 }
1329
1330 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1331 v = strings.TrimSpace(v)
1332 if v != "" && v != "false" {
1333 return false
1334 }
1335 }
1336 return true
1337}
1338
Ramy Medhatbbf25672019-07-17 12:30:04 +00001339func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001340 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001341 v = strings.TrimSpace(v)
1342 if v != "" && v != "false" {
1343 return true
1344 }
1345 }
1346 return false
1347}
1348
Chris Parsonsef615e52022-08-18 22:04:11 -04001349func (c *configImpl) BazelBuildEnabled() bool {
MarkDacekb78465d2022-10-18 20:10:16 +00001350 return c.bazelProdMode || c.bazelDevMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001351}
1352
Ramy Medhatbbf25672019-07-17 12:30:04 +00001353func (c *configImpl) StartRBE() bool {
1354 if !c.UseRBE() {
1355 return false
1356 }
1357
1358 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1359 v = strings.TrimSpace(v)
1360 if v != "" && v != "false" {
1361 return false
1362 }
1363 }
1364 return true
1365}
1366
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001367func (c *configImpl) rbeProxyLogsDir() string {
1368 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001369 if v, ok := c.environ.Get(f); ok {
1370 return v
1371 }
1372 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001373 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1374 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001375}
1376
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001377func (c *configImpl) shouldCleanupRBELogsDir() bool {
1378 // Perform a log directory cleanup only when the log directory
1379 // is auto created by the build rather than user-specified.
1380 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1381 if _, ok := c.environ.Get(f); ok {
1382 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001383 }
1384 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001385 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001386}
1387
1388func (c *configImpl) rbeExecRoot() string {
1389 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1390 if v, ok := c.environ.Get(f); ok {
1391 return v
1392 }
1393 }
1394 wd, err := os.Getwd()
1395 if err != nil {
1396 return ""
1397 }
1398 return wd
1399}
1400
1401func (c *configImpl) rbeDir() string {
1402 if v, ok := c.environ.Get("RBE_DIR"); ok {
1403 return v
1404 }
1405 return "prebuilts/remoteexecution-client/live/"
1406}
1407
1408func (c *configImpl) rbeReproxy() string {
1409 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1410 if v, ok := c.environ.Get(f); ok {
1411 return v
1412 }
1413 }
1414 return filepath.Join(c.rbeDir(), "reproxy")
1415}
1416
1417func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001418 credFlags := []string{
1419 "use_application_default_credentials",
1420 "use_gce_credentials",
1421 "credential_file",
1422 "use_google_prod_creds",
1423 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001424 for _, cf := range credFlags {
1425 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1426 if v, ok := c.environ.Get(f); ok {
1427 v = strings.TrimSpace(v)
1428 if v != "" && v != "false" && v != "0" {
1429 return "RBE_" + cf, v
1430 }
1431 }
1432 }
1433 }
1434 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001435}
1436
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001437func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1438 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1439 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1440
1441 name := filepath.Join(dir, base)
1442 if len(name) < maxNameLen {
1443 return name, nil
1444 }
1445
1446 name = filepath.Join("/tmp", base)
1447 if len(name) < maxNameLen {
1448 return name, nil
1449 }
1450
1451 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1452}
1453
Kousik Kumar7bc78192022-04-27 14:52:56 -04001454// IsGooglerEnvironment returns true if the current build is running
1455// on a Google developer machine and false otherwise.
1456func (c *configImpl) IsGooglerEnvironment() bool {
1457 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1458 if v, ok := c.environ.Get(cf); ok {
1459 return v == "googler"
1460 }
1461 return false
1462}
1463
1464// GoogleProdCredsExist determine whether credentials exist on the
1465// Googler machine to use remote execution.
1466func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001467 if googleProdCredsExistCache {
1468 return googleProdCredsExistCache
1469 }
Kousik Kumar7bc78192022-04-27 14:52:56 -04001470 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1471 return false
1472 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001473 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001474 return true
1475}
1476
1477// UseRemoteBuild indicates whether to use a remote build acceleration system
1478// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001479func (c *configImpl) UseRemoteBuild() bool {
1480 return c.UseGoma() || c.UseRBE()
1481}
1482
Kousik Kumar7bc78192022-04-27 14:52:56 -04001483// StubbyExists checks whether the stubby binary exists on the machine running
1484// the build.
1485func (c *configImpl) StubbyExists() bool {
1486 if _, err := exec.LookPath("stubby"); err != nil {
1487 return false
1488 }
1489 return true
1490}
1491
Dan Willemsen1e704462016-08-21 15:17:17 -07001492// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001493// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001494// still limited by Parallel()
1495func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001496 if !c.UseRemoteBuild() {
1497 return 0
1498 }
1499 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1500 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001501 }
1502 return 500
1503}
1504
1505func (c *configImpl) SetKatiArgs(args []string) {
1506 c.katiArgs = args
1507}
1508
1509func (c *configImpl) SetNinjaArgs(args []string) {
1510 c.ninjaArgs = args
1511}
1512
1513func (c *configImpl) SetKatiSuffix(suffix string) {
1514 c.katiSuffix = suffix
1515}
1516
Dan Willemsene0879fc2017-08-04 15:06:27 -07001517func (c *configImpl) LastKatiSuffixFile() string {
1518 return filepath.Join(c.OutDir(), "last_kati_suffix")
1519}
1520
1521func (c *configImpl) HasKatiSuffix() bool {
1522 return c.katiSuffix != ""
1523}
1524
Dan Willemsen1e704462016-08-21 15:17:17 -07001525func (c *configImpl) KatiEnvFile() string {
1526 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1527}
1528
Dan Willemsen29971232018-09-26 14:58:30 -07001529func (c *configImpl) KatiBuildNinjaFile() string {
1530 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001531}
1532
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001533func (c *configImpl) KatiPackageNinjaFile() string {
1534 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1535}
1536
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001537func (c *configImpl) SoongVarsFile() string {
1538 return filepath.Join(c.SoongOutDir(), "soong.variables")
1539}
1540
Dan Willemsen1e704462016-08-21 15:17:17 -07001541func (c *configImpl) SoongNinjaFile() string {
1542 return filepath.Join(c.SoongOutDir(), "build.ninja")
1543}
1544
1545func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001546 if c.katiSuffix == "" {
1547 return filepath.Join(c.OutDir(), "combined.ninja")
1548 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001549 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1550}
1551
1552func (c *configImpl) SoongAndroidMk() string {
1553 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1554}
1555
1556func (c *configImpl) SoongMakeVarsMk() string {
1557 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1558}
1559
Dan Willemsenf052f782017-05-18 15:29:04 -07001560func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001561 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001562}
1563
Dan Willemsen02781d52017-05-12 19:28:13 -07001564func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001565 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1566}
1567
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001568func (c *configImpl) KatiPackageMkDir() string {
1569 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1570}
1571
Dan Willemsenf052f782017-05-18 15:29:04 -07001572func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001573 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001574}
1575
1576func (c *configImpl) HostOut() string {
1577 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1578}
1579
1580// This probably needs to be multi-valued, so not exporting it for now
1581func (c *configImpl) hostCrossOut() string {
1582 if runtime.GOOS == "linux" {
1583 return filepath.Join(c.hostOutRoot(), "windows-x86")
1584 } else {
1585 return ""
1586 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001587}
1588
Dan Willemsen1e704462016-08-21 15:17:17 -07001589func (c *configImpl) HostPrebuiltTag() string {
1590 if runtime.GOOS == "linux" {
1591 return "linux-x86"
1592 } else if runtime.GOOS == "darwin" {
1593 return "darwin-x86"
1594 } else {
1595 panic("Unsupported OS")
1596 }
1597}
Dan Willemsenf173d592017-04-27 14:28:00 -07001598
Dan Willemsen8122bd52017-10-12 20:20:41 -07001599func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001600 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1601 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001602 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1603 if _, err := os.Stat(asan); err == nil {
1604 return asan
1605 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001606 }
1607 }
1608 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1609}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001610
1611func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1612 c.brokenDupRules = val
1613}
1614
1615func (c *configImpl) BuildBrokenDupRules() bool {
1616 return c.brokenDupRules
1617}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001618
Dan Willemsen25e6f092019-04-09 10:22:43 -07001619func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1620 c.brokenUsesNetwork = val
1621}
1622
1623func (c *configImpl) BuildBrokenUsesNetwork() bool {
1624 return c.brokenUsesNetwork
1625}
1626
Dan Willemsene3336352020-01-02 19:10:38 -08001627func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1628 c.brokenNinjaEnvVars = val
1629}
1630
1631func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1632 return c.brokenNinjaEnvVars
1633}
1634
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001635func (c *configImpl) SetTargetDeviceDir(dir string) {
1636 c.targetDeviceDir = dir
1637}
1638
1639func (c *configImpl) TargetDeviceDir() string {
1640 return c.targetDeviceDir
1641}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001642
Patrice Arruda219eef32020-06-01 17:29:30 +00001643func (c *configImpl) BuildDateTime() string {
1644 return c.buildDateTime
1645}
1646
1647func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001648 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001649}
Patrice Arruda83842d72020-12-08 19:42:08 +00001650
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001651// LogsDir returns the absolute path to the logs directory where build log and
1652// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001653// directory. If the argument dist is specified, the logs directory
1654// is <dist_dir>/logs.
1655func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001656 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001657 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001658 // 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 -05001659 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001660 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001661 absDir, err := filepath.Abs(dir)
1662 if err != nil {
1663 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1664 os.Exit(1)
1665 }
1666 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001667}
1668
1669// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1670// where the bazel profiles are located.
1671func (c *configImpl) BazelMetricsDir() string {
1672 return filepath.Join(c.LogsDir(), "bazel_metrics")
1673}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001674
Chris Parsons53f68ae2022-03-03 12:01:40 -05001675// MkFileMetrics returns the file path for make-related metrics.
1676func (c *configImpl) MkMetrics() string {
1677 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1678}
1679
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001680func (c *configImpl) SetEmptyNinjaFile(v bool) {
1681 c.emptyNinjaFile = v
1682}
1683
1684func (c *configImpl) EmptyNinjaFile() bool {
1685 return c.emptyNinjaFile
1686}
Yu Liu6e13b402021-07-27 14:29:06 -07001687
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001688func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1689 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1690}
1691
Chris Parsons9402ca82023-02-23 17:28:06 -05001692func (c *configImpl) IsPersistentBazelEnabled() bool {
1693 return c.Environment().IsEnvTrue("USE_PERSISTENT_BAZEL")
1694}
1695
MarkDacekd06db5d2022-11-29 00:47:59 +00001696func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1697 return c.bazelForceEnabledModules
1698}
1699
MarkDacekd0e7cd32022-12-02 22:22:40 +00001700func (c *configImpl) SkipMetricsUpload() bool {
1701 return c.skipMetricsUpload
1702}
1703
MarkDacek6614d9c2022-12-07 21:57:38 +00001704// Returns a Time object if one was passed via a command-line flag.
1705// Otherwise returns the passed default.
1706func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1707 if c.buildStartedTime == 0 {
1708 return defaultTime
1709 }
1710 return time.UnixMilli(c.buildStartedTime)
1711}
1712
Yu Liu6e13b402021-07-27 14:29:06 -07001713func GetMetricsUploader(topDir string, env *Environment) string {
1714 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1715 metricsUploader := filepath.Join(topDir, p)
1716 if _, err := os.Stat(metricsUploader); err == nil {
1717 return metricsUploader
1718 }
1719 }
1720
1721 return ""
1722}