blob: b746cf8042ffe35297d7bc9896fb3b86036d01b0 [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{
Jeongik Chaf5c872f2023-04-14 00:17:47 +0900316 environ: OsEnvironment(),
317 sandboxConfig: &SandboxConfig{},
318 ninjaWeightListSource: HINT_FROM_SOONG,
Dan Willemsen1e704462016-08-21 15:17:17 -0700319 }
320
Patrice Arruda90109172020-07-28 18:07:27 +0000321 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700322 ret.parallel = runtime.NumCPU() + 2
323 ret.keepGoing = 1
324
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800325 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700326 ret.parseArgs(ctx, args)
Jeongik Chae114e602023-03-19 00:12:39 +0900327
328 if ret.ninjaWeightListSource == HINT_FROM_SOONG {
329 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "true")
330 }
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800331 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700332 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
333 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
334 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800335 outDir := "out"
336 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
337 if wd, err := os.Getwd(); err != nil {
338 ctx.Fatalln("Failed to get working directory:", err)
339 } else {
340 outDir = filepath.Join(baseDir, filepath.Base(wd))
341 }
342 }
343 ret.environ.Set("OUT_DIR", outDir)
344 }
345
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500346 // loadEnvConfig needs to know what the OUT_DIR is, so it should
347 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000348 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
349
350 if bc != "" {
351 if err := fetchEnvConfig(ctx, ret, bc); err != nil {
352 ctx.Verbosef("Failed to fetch config file: %v\n", err)
Kousik Kumarc8818332023-01-16 16:33:05 +0000353 }
354 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000355 ctx.Fatalln("Failed to parse env config files: %v", err)
356 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500357 }
358
Dan Willemsen2d31a442018-10-20 21:33:41 -0700359 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
360 ret.distDir = filepath.Clean(distDir)
361 } else {
362 ret.distDir = filepath.Join(ret.OutDir(), "dist")
363 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700364
Spandan Das05063612021-06-25 01:39:04 +0000365 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
366 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
367 }
368
Dan Willemsen1e704462016-08-21 15:17:17 -0700369 ret.environ.Unset(
370 // We're already using it
371 "USE_SOONG_UI",
372
373 // We should never use GOROOT/GOPATH from the shell environment
374 "GOROOT",
375 "GOPATH",
376
377 // These should only come from Soong, not the environment.
378 "CLANG",
379 "CLANG_CXX",
380 "CCC_CC",
381 "CCC_CXX",
382
383 // Used by the goma compiler wrapper, but should only be set by
384 // gomacc
385 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800386
387 // We handle this above
388 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700389
Dan Willemsen2d31a442018-10-20 21:33:41 -0700390 // This is handled above too, and set for individual commands later
391 "DIST_DIR",
392
Dan Willemsen68a09852017-04-18 13:56:57 -0700393 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000394 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700395 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700396 "DISPLAY",
397 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000398 "JAVAC",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700399 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700400 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700401
402 // Drop make flags
403 "MAKEFLAGS",
404 "MAKELEVEL",
405 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700406
407 // Set in envsetup.sh, reset in makefiles
408 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700409
410 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
411 "ANDROID_BUILD_TOP",
412 "ANDROID_HOST_OUT",
413 "ANDROID_PRODUCT_OUT",
414 "ANDROID_HOST_OUT_TESTCASES",
415 "ANDROID_TARGET_OUT_TESTCASES",
416 "ANDROID_TOOLCHAIN",
417 "ANDROID_TOOLCHAIN_2ND_ARCH",
418 "ANDROID_DEV_SCRIPTS",
419 "ANDROID_EMULATOR_PREBUILTS",
420 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700421 )
422
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400423 if ret.UseGoma() || ret.ForceUseGoma() {
424 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
425 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400426 }
427
Dan Willemsen1e704462016-08-21 15:17:17 -0700428 // Tell python not to spam the source tree with .pyc files.
429 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
430
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400431 tmpDir := absPath(ctx, ret.TempDir())
432 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800433
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700434 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
435 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
436 "llvm-binutils-stable/llvm-symbolizer")
437 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
438
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800439 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700440 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800441
Yu Liu6e13b402021-07-27 14:29:06 -0700442 srcDir := absPath(ctx, ".")
443 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700444 ctx.Println("You are building in a directory whose absolute path contains a space character:")
445 ctx.Println()
446 ctx.Printf("%q\n", srcDir)
447 ctx.Println()
448 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700449 }
450
Yu Liu6e13b402021-07-27 14:29:06 -0700451 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
452
Dan Willemsendb8457c2017-05-12 16:38:17 -0700453 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700454 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
455 ctx.Println()
456 ctx.Printf("%q\n", outDir)
457 ctx.Println()
458 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700459 }
460
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000461 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700462 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
463 ctx.Println()
464 ctx.Printf("%q\n", distDir)
465 ctx.Println()
466 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700467 }
468
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700469 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000470 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
471 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100472 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800473 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700474 javaHome := func() string {
475 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
476 return override
477 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000478 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
479 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 +0100480 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000481 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
482 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
483 }
484 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700485 }()
486 absJavaHome := absPath(ctx, javaHome)
487
Dan Willemsened869522018-01-08 14:58:46 -0800488 ret.configureLocale(ctx)
489
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700490 newPath := []string{filepath.Join(absJavaHome, "bin")}
491 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
492 newPath = append(newPath, path)
493 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100494
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700495 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
496 ret.environ.Set("JAVA_HOME", absJavaHome)
497 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000498 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
499 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100500 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700501 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
502
LaMont Jones52a72432023-03-09 18:19:35 +0000503 if ret.MultitreeBuild() {
504 ret.environ.Set("MULTITREE_BUILD", "true")
505 }
506
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800507 outDir := ret.OutDir()
508 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800509 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800510 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800511 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800512 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800513 }
Colin Cross28f527c2019-11-26 16:19:04 -0800514
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800515 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
516
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400517 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400518 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400519 ret.environ.Set(k, v)
520 }
521 }
522
Jihoon Kang1bff0342023-01-17 20:40:22 +0000523 if ret.BuildFromTextStub() {
524 // TODO(b/271443071): support hidden api check for from-text stub build
525 ret.environ.Set("UNSAFE_DISABLE_HIDDENAPI_FLAGS", "true")
526 }
527
Patrice Arruda83842d72020-12-08 19:42:08 +0000528 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800529 if err := os.RemoveAll(bpd); err != nil {
530 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
531 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000532
Patrice Arruda96850362020-08-11 20:41:11 +0000533 c := Config{ret}
534 storeConfigMetrics(ctx, c)
535 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700536}
537
Patrice Arruda13848222019-04-22 17:12:02 -0700538// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
539// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700540func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
541 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700542}
543
Patrice Arruda96850362020-08-11 20:41:11 +0000544// storeConfigMetrics selects a set of configuration information and store in
545// the metrics system for further analysis.
546func storeConfigMetrics(ctx Context, config Config) {
547 if ctx.Metrics == nil {
548 return
549 }
550
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400551 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000552
553 s := &smpb.SystemResourceInfo{
554 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
555 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
556 }
557 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000558}
559
Jeongik Cha8d63d562023-03-17 03:52:13 +0900560func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900561 switch s {
562 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900563 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900564 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900565 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900566 case EXTERNAL_FILE:
567 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900568 case HINT_FROM_SOONG:
569 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900570 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900571 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900572 }
573}
574
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400575func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700576 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400577 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
578 UseGoma: proto.Bool(config.UseGoma()),
579 UseRbe: proto.Bool(config.UseRBE()),
580 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
581 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900582 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400583 }
Yu Liue737a992021-10-04 13:21:41 -0700584 c.Targets = append(c.Targets, config.arguments...)
585
586 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400587}
588
Patrice Arruda13848222019-04-22 17:12:02 -0700589// getConfigArgs processes the command arguments based on the build action and creates a set of new
590// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700591func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700592 // The next block of code verifies that the current directory is the root directory of the source
593 // tree. It then finds the relative path of dir based on the root directory of the source tree
594 // and verify that dir is inside of the source tree.
595 checkTopDir(ctx)
596 topDir, err := os.Getwd()
597 if err != nil {
598 ctx.Fatalf("Error retrieving top directory: %v", err)
599 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700600 dir, err = filepath.EvalSymlinks(dir)
601 if err != nil {
602 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
603 }
Patrice Arruda13848222019-04-22 17:12:02 -0700604 dir, err = filepath.Abs(dir)
605 if err != nil {
606 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
607 }
608 relDir, err := filepath.Rel(topDir, dir)
609 if err != nil {
610 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
611 }
612 // If there are ".." in the path, it's not in the source tree.
613 if strings.Contains(relDir, "..") {
614 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
615 }
616
617 configArgs := args[:]
618
619 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
620 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
621 targetNamePrefix := "MODULES-IN-"
622 if inList("GET-INSTALL-PATH", configArgs) {
623 targetNamePrefix = "GET-INSTALL-PATH-IN-"
624 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
625 }
626
Patrice Arruda13848222019-04-22 17:12:02 -0700627 var targets []string
628
629 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700630 case BUILD_MODULES:
631 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700632 case BUILD_MODULES_IN_A_DIRECTORY:
633 // If dir is the root source tree, all the modules are built of the source tree are built so
634 // no need to find the build file.
635 if topDir == dir {
636 break
637 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700638
Patrice Arruda13848222019-04-22 17:12:02 -0700639 buildFile := findBuildFile(ctx, relDir)
640 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700641 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700642 }
Patrice Arruda13848222019-04-22 17:12:02 -0700643 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
644 case BUILD_MODULES_IN_DIRECTORIES:
645 newConfigArgs, dirs := splitArgs(configArgs)
646 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700647 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700648 }
649
650 // Tidy only override all other specified targets.
651 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
652 if tidyOnly == "true" || tidyOnly == "1" {
653 configArgs = append(configArgs, "tidy_only")
654 } else {
655 configArgs = append(configArgs, targets...)
656 }
657
658 return configArgs
659}
660
661// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
662func convertToTarget(dir string, targetNamePrefix string) string {
663 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
664}
665
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700666// hasBuildFile returns true if dir contains an Android build file.
667func hasBuildFile(ctx Context, dir string) bool {
668 for _, buildFile := range buildFiles {
669 _, err := os.Stat(filepath.Join(dir, buildFile))
670 if err == nil {
671 return true
672 }
673 if !os.IsNotExist(err) {
674 ctx.Fatalf("Error retrieving the build file stats: %v", err)
675 }
676 }
677 return false
678}
679
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700680// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
681// in the current and any sub directory of dir. If a build file is not found, traverse the path
682// up by one directory and repeat again until either a build file is found or reached to the root
683// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
684// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700685func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700686 // If the string is empty or ".", assume it is top directory of the source tree.
687 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700688 return ""
689 }
690
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700691 found := false
692 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
693 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
694 if err != nil {
695 return err
696 }
697 if found {
698 return filepath.SkipDir
699 }
700 if info.IsDir() {
701 return nil
702 }
703 for _, buildFile := range buildFiles {
704 if info.Name() == buildFile {
705 found = true
706 return filepath.SkipDir
707 }
708 }
709 return nil
710 })
711 if err != nil {
712 ctx.Fatalf("Error finding Android build file: %v", err)
713 }
714
715 if found {
716 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700717 }
718 }
719
720 return ""
721}
722
723// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
724func splitArgs(args []string) (newArgs []string, dirs []string) {
725 specialArgs := map[string]bool{
726 "showcommands": true,
727 "snod": true,
728 "dist": true,
729 "checkbuild": true,
730 }
731
732 newArgs = []string{}
733 dirs = []string{}
734
735 for _, arg := range args {
736 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
737 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
738 newArgs = append(newArgs, arg)
739 continue
740 }
741
742 if _, ok := specialArgs[arg]; ok {
743 newArgs = append(newArgs, arg)
744 continue
745 }
746
747 dirs = append(dirs, arg)
748 }
749
750 return newArgs, dirs
751}
752
753// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
754// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
755// source root tree where the build action command was invoked. Each directory is validated if the
756// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700757func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700758 for _, dir := range dirs {
759 // The directory may have specified specific modules to build. ":" is the separator to separate
760 // the directory and the list of modules.
761 s := strings.Split(dir, ":")
762 l := len(s)
763 if l > 2 { // more than one ":" was specified.
764 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
765 }
766
767 dir = filepath.Join(relDir, s[0])
768 if _, err := os.Stat(dir); err != nil {
769 ctx.Fatalf("couldn't find directory %s", dir)
770 }
771
772 // Verify that if there are any targets specified after ":". Each target is separated by ",".
773 var newTargets []string
774 if l == 2 && s[1] != "" {
775 newTargets = strings.Split(s[1], ",")
776 if inList("", newTargets) {
777 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
778 }
779 }
780
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700781 // If there are specified targets to build in dir, an android build file must exist for the one
782 // shot build. For the non-targets case, find the appropriate build file and build all the
783 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700784 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700785 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700786 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
787 }
788 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700789 buildFile := findBuildFile(ctx, dir)
790 if buildFile == "" {
791 ctx.Fatalf("Build file not found for %s directory", dir)
792 }
793 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700794 }
795
Patrice Arruda13848222019-04-22 17:12:02 -0700796 targets = append(targets, newTargets...)
797 }
798
Dan Willemsence41e942019-07-29 23:39:30 -0700799 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700800}
801
Dan Willemsen9b587492017-07-10 22:13:00 -0700802func (c *configImpl) parseArgs(ctx Context, args []string) {
803 for i := 0; i < len(args); i++ {
804 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100805 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700806 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200807 } else if arg == "--empty-ninja-file" {
808 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100809 } else if arg == "--skip-ninja" {
810 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700811 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700812 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
813 // but it does run a Kati ninja file if the .kati_enabled marker file was created
814 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000815 c.skipConfig = true
816 c.skipKati = true
817 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100818 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000819 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100820 } else if arg == "--soong-only" {
821 c.skipKati = true
822 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200823 } else if arg == "--config-only" {
824 c.skipKati = true
825 c.skipKatiNinja = true
826 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700827 } else if arg == "--skip-config" {
828 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700829 } else if arg == "--skip-soong-tests" {
830 c.skipSoongTests = true
MarkDacekd0e7cd32022-12-02 22:22:40 +0000831 } else if arg == "--skip-metrics-upload" {
832 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500833 } else if arg == "--mk-metrics" {
834 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000835 } else if arg == "--multitree-build" {
836 c.multitreeBuild = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400837 } else if arg == "--bazel-mode" {
838 c.bazelProdMode = true
839 } else if arg == "--bazel-mode-dev" {
840 c.bazelDevMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000841 } else if arg == "--bazel-mode-staging" {
842 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000843 } else if arg == "--search-api-dir" {
844 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900845 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
846 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
847 if source == "ninja_log" {
848 c.ninjaWeightListSource = NINJA_LOG
849 } else if source == "evenly_distributed" {
850 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
851 } else if source == "not_used" {
852 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900853 } else if source == "soong" {
854 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900855 } else if strings.HasPrefix(source, "file,") {
856 c.ninjaWeightListSource = EXTERNAL_FILE
857 filePath := strings.TrimPrefix(source, "file,")
858 err := validateNinjaWeightList(filePath)
859 if err != nil {
860 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
861 }
862 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
863 if err != nil {
864 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
865 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900866 } else {
867 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
868 }
Jihoon Kang1bff0342023-01-17 20:40:22 +0000869 } else if arg == "--build-from-text-stub" {
870 c.buildFromTextStub = true
MarkDacekb96561e2022-12-02 04:34:43 +0000871 } else if strings.HasPrefix(arg, "--build-command=") {
872 buildCmd := strings.TrimPrefix(arg, "--build-command=")
873 // remove quotations
874 buildCmd = strings.TrimPrefix(buildCmd, "\"")
875 buildCmd = strings.TrimSuffix(buildCmd, "\"")
876 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000877 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
878 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
MarkDacek6614d9c2022-12-07 21:57:38 +0000879 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
880 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
881 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
882 if err == nil {
883 c.buildStartedTime = val
884 } else {
885 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
886 }
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700887 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700888 parseArgNum := func(def int) int {
889 if len(arg) > 2 {
890 p, err := strconv.ParseUint(arg[2:], 10, 31)
891 if err != nil {
892 ctx.Fatalf("Failed to parse %q: %v", arg, err)
893 }
894 return int(p)
895 } else if i+1 < len(args) {
896 p, err := strconv.ParseUint(args[i+1], 10, 31)
897 if err == nil {
898 i++
899 return int(p)
900 }
901 }
902 return def
903 }
904
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700905 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700906 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700907 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700908 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700909 } else {
910 ctx.Fatalln("Unknown option:", arg)
911 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700912 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700913 if k == "OUT_DIR" {
914 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
915 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700916 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700917 } else if arg == "dist" {
918 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200919 } else if arg == "json-module-graph" {
920 c.jsonModuleGraph = true
921 } else if arg == "bp2build" {
922 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000923 } else if arg == "api_bp2build" {
924 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200925 } else if arg == "queryview" {
926 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200927 } else if arg == "soong_docs" {
928 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700929 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700930 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800931 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700932 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700933 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700934 }
935 }
Chris Parsonsb6e96902022-10-31 20:08:45 -0400936 if (!c.bazelProdMode) && (!c.bazelDevMode) && (!c.bazelStagingMode) {
937 c.bazelProdMode = defaultBazelProdMode(c)
938 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700939}
940
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900941func validateNinjaWeightList(weightListFilePath string) (err error) {
942 data, err := os.ReadFile(weightListFilePath)
943 if err != nil {
944 return
945 }
946 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
947 for _, line := range lines {
948 fields := strings.Split(line, ",")
949 if len(fields) != 2 {
950 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
951 }
952 _, err = strconv.Atoi(fields[1])
953 if err != nil {
954 return
955 }
956 }
957 return
958}
959
Dan Willemsened869522018-01-08 14:58:46 -0800960func (c *configImpl) configureLocale(ctx Context) {
961 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
962 output, err := cmd.Output()
963
964 var locales []string
965 if err == nil {
966 locales = strings.Split(string(output), "\n")
967 } else {
968 // If we're unable to list the locales, let's assume en_US.UTF-8
969 locales = []string{"en_US.UTF-8"}
970 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
971 }
972
973 // gettext uses LANGUAGE, which is passed directly through
974
975 // For LANG and LC_*, only preserve the evaluated version of
976 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800977 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800978 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800979 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800980 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800981 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800982 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800983 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800984 }
985
986 c.environ.UnsetWithPrefix("LC_")
987
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800988 if userLang != "" {
989 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800990 }
991
992 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
993 // for others)
994 if inList("C.UTF-8", locales) {
995 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500996 } else if inList("C.utf8", locales) {
997 // These normalize to the same thing
998 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800999 } else if inList("en_US.UTF-8", locales) {
1000 c.environ.Set("LANG", "en_US.UTF-8")
1001 } else if inList("en_US.utf8", locales) {
1002 // These normalize to the same thing
1003 c.environ.Set("LANG", "en_US.UTF-8")
1004 } else {
1005 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
1006 }
1007}
1008
Dan Willemsen1e704462016-08-21 15:17:17 -07001009func (c *configImpl) Environment() *Environment {
1010 return c.environ
1011}
1012
1013func (c *configImpl) Arguments() []string {
1014 return c.arguments
1015}
1016
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001017func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001018 if len(c.Arguments()) > 0 {
1019 // Explicit targets requested that are not special targets like b2pbuild
1020 // or the JSON module graph
1021 return true
1022 }
1023
Spandan Das5af0bd32022-09-28 20:43:08 +00001024 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001025 // Command line was empty, the default Ninja target is built
1026 return true
1027 }
1028
Liz Kammer88677422021-12-15 15:03:19 -05001029 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
1030 if c.Dist() && !c.Bp2Build() {
1031 return true
1032 }
1033
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001034 // build.ninja doesn't need to be generated
1035 return false
1036}
1037
Dan Willemsen1e704462016-08-21 15:17:17 -07001038func (c *configImpl) OutDir() string {
1039 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -07001040 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -07001041 }
1042 return "out"
1043}
1044
Dan Willemsen8a073a82017-02-04 17:30:44 -08001045func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -04001046 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001047}
1048
1049func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -07001050 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -08001051}
1052
Dan Willemsen1e704462016-08-21 15:17:17 -07001053func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001054 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001055 return c.arguments
1056 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001057 return c.ninjaArgs
1058}
1059
Jingwen Chen7c6089a2020-11-02 02:56:20 -05001060func (c *configImpl) BazelOutDir() string {
1061 return filepath.Join(c.OutDir(), "bazel")
1062}
1063
Liz Kammer2af5ea82022-11-11 14:21:03 -05001064func (c *configImpl) bazelOutputBase() string {
1065 return filepath.Join(c.BazelOutDir(), "output")
1066}
1067
Dan Willemsen1e704462016-08-21 15:17:17 -07001068func (c *configImpl) SoongOutDir() string {
1069 return filepath.Join(c.OutDir(), "soong")
1070}
1071
Spandan Das394aa322022-11-03 17:02:10 +00001072func (c *configImpl) ApiSurfacesOutDir() string {
1073 return filepath.Join(c.OutDir(), "api_surfaces")
1074}
1075
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001076func (c *configImpl) PrebuiltOS() string {
1077 switch runtime.GOOS {
1078 case "linux":
1079 return "linux-x86"
1080 case "darwin":
1081 return "darwin-x86"
1082 default:
1083 panic("Unknown GOOS")
1084 }
1085}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001086
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001087func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001088 if c.SkipKatiNinja() {
1089 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1090 } else {
1091 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1092 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001093}
1094
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001095func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001096 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001097}
1098
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001099func (c *configImpl) UsedEnvFile(tag string) string {
1100 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1101}
1102
Lukacs T. Berkic541cd22022-10-26 07:26:50 +00001103func (c *configImpl) Bp2BuildFilesMarkerFile() string {
1104 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
1105}
1106
1107func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001108 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +02001109}
1110
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001111func (c *configImpl) SoongDocsHtml() string {
1112 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1113}
1114
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001115func (c *configImpl) QueryviewMarkerFile() string {
1116 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1117}
1118
Spandan Das5af0bd32022-09-28 20:43:08 +00001119func (c *configImpl) ApiBp2buildMarkerFile() string {
1120 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
1121}
1122
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001123func (c *configImpl) ModuleGraphFile() string {
1124 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1125}
1126
kgui67007242022-01-25 13:50:25 +08001127func (c *configImpl) ModuleActionsFile() string {
1128 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1129}
1130
Jeff Gastonefc1b412017-03-29 17:29:06 -07001131func (c *configImpl) TempDir() string {
1132 return shared.TempDirForOutDir(c.SoongOutDir())
1133}
1134
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001135func (c *configImpl) FileListDir() string {
1136 return filepath.Join(c.OutDir(), ".module_paths")
1137}
1138
Dan Willemsen1e704462016-08-21 15:17:17 -07001139func (c *configImpl) KatiSuffix() string {
1140 if c.katiSuffix != "" {
1141 return c.katiSuffix
1142 }
1143 panic("SetKatiSuffix has not been called")
1144}
1145
Colin Cross37193492017-11-16 17:55:00 -08001146// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1147// user is interested in additional checks at the expense of build time.
1148func (c *configImpl) Checkbuild() bool {
1149 return c.checkbuild
1150}
1151
Dan Willemsen8a073a82017-02-04 17:30:44 -08001152func (c *configImpl) Dist() bool {
1153 return c.dist
1154}
1155
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001156func (c *configImpl) JsonModuleGraph() bool {
1157 return c.jsonModuleGraph
1158}
1159
1160func (c *configImpl) Bp2Build() bool {
1161 return c.bp2build
1162}
1163
Spandan Das5af0bd32022-09-28 20:43:08 +00001164func (c *configImpl) ApiBp2build() bool {
1165 return c.apiBp2build
1166}
1167
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001168func (c *configImpl) Queryview() bool {
1169 return c.queryview
1170}
1171
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001172func (c *configImpl) SoongDocs() bool {
1173 return c.soongDocs
1174}
1175
Dan Willemsen1e704462016-08-21 15:17:17 -07001176func (c *configImpl) IsVerbose() bool {
1177 return c.verbose
1178}
1179
LaMont Jones52a72432023-03-09 18:19:35 +00001180func (c *configImpl) MultitreeBuild() bool {
1181 return c.multitreeBuild
1182}
1183
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001184func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1185 return c.ninjaWeightListSource
1186}
1187
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001188func (c *configImpl) SkipKati() bool {
1189 return c.skipKati
1190}
1191
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001192func (c *configImpl) SkipKatiNinja() bool {
1193 return c.skipKatiNinja
1194}
1195
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001196func (c *configImpl) SkipSoong() bool {
1197 return c.skipSoong
1198}
1199
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001200func (c *configImpl) SkipNinja() bool {
1201 return c.skipNinja
1202}
1203
Anton Hansson5a7861a2021-06-04 10:09:01 +01001204func (c *configImpl) SetSkipNinja(v bool) {
1205 c.skipNinja = v
1206}
1207
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001208func (c *configImpl) SkipConfig() bool {
1209 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001210}
1211
Jihoon Kang1bff0342023-01-17 20:40:22 +00001212func (c *configImpl) BuildFromTextStub() bool {
1213 return c.buildFromTextStub
1214}
1215
Dan Willemsen1e704462016-08-21 15:17:17 -07001216func (c *configImpl) TargetProduct() string {
1217 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1218 return v
1219 }
1220 panic("TARGET_PRODUCT is not defined")
1221}
1222
Dan Willemsen02781d52017-05-12 19:28:13 -07001223func (c *configImpl) TargetDevice() string {
1224 return c.targetDevice
1225}
1226
1227func (c *configImpl) SetTargetDevice(device string) {
1228 c.targetDevice = device
1229}
1230
1231func (c *configImpl) TargetBuildVariant() string {
1232 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1233 return v
1234 }
1235 panic("TARGET_BUILD_VARIANT is not defined")
1236}
1237
Dan Willemsen1e704462016-08-21 15:17:17 -07001238func (c *configImpl) KatiArgs() []string {
1239 return c.katiArgs
1240}
1241
1242func (c *configImpl) Parallel() int {
1243 return c.parallel
1244}
1245
Sam Delmerico98a73292023-02-21 11:50:29 -05001246func (c *configImpl) GetSourceRootDirs() []string {
1247 return c.sourceRootDirs
1248}
1249
1250func (c *configImpl) SetSourceRootDirs(i []string) {
1251 c.sourceRootDirs = i
1252}
1253
Spandan Dasc5763832022-11-08 18:42:16 +00001254func (c *configImpl) GetIncludeTags() []string {
1255 return c.includeTags
1256}
1257
1258func (c *configImpl) SetIncludeTags(i []string) {
1259 c.includeTags = i
1260}
1261
MarkDacek6614d9c2022-12-07 21:57:38 +00001262func (c *configImpl) GetLogsPrefix() string {
1263 return c.logsPrefix
1264}
1265
1266func (c *configImpl) SetLogsPrefix(prefix string) {
1267 c.logsPrefix = prefix
1268}
1269
Colin Cross8b8bec32019-11-15 13:18:43 -08001270func (c *configImpl) HighmemParallel() int {
1271 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1272 return i
1273 }
1274
1275 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1276 parallel := c.Parallel()
1277 if c.UseRemoteBuild() {
1278 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1279 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1280 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1281 // Return 1/16th of the size of the local pool, rounding up.
1282 return (parallel + 15) / 16
1283 } else if c.totalRAM == 0 {
1284 // Couldn't detect the total RAM, don't restrict highmem processes.
1285 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001286 } else if c.totalRAM <= 16*1024*1024*1024 {
1287 // Less than 16GB of ram, restrict to 1 highmem processes
1288 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001289 } else if c.totalRAM <= 32*1024*1024*1024 {
1290 // Less than 32GB of ram, restrict to 2 highmem processes
1291 return 2
1292 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1293 // If less than 8GB total RAM per process, reduce the number of highmem processes
1294 return p
1295 }
1296 // No restriction on highmem processes
1297 return parallel
1298}
1299
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001300func (c *configImpl) TotalRAM() uint64 {
1301 return c.totalRAM
1302}
1303
Kousik Kumarec478642020-09-21 13:39:24 -04001304// ForceUseGoma determines whether we should override Goma deprecation
1305// and use Goma for the current build or not.
1306func (c *configImpl) ForceUseGoma() bool {
1307 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1308 v = strings.TrimSpace(v)
1309 if v != "" && v != "false" {
1310 return true
1311 }
1312 }
1313 return false
1314}
1315
Dan Willemsen1e704462016-08-21 15:17:17 -07001316func (c *configImpl) UseGoma() bool {
1317 if v, ok := c.environ.Get("USE_GOMA"); ok {
1318 v = strings.TrimSpace(v)
1319 if v != "" && v != "false" {
1320 return true
1321 }
1322 }
1323 return false
1324}
1325
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001326func (c *configImpl) StartGoma() bool {
1327 if !c.UseGoma() {
1328 return false
1329 }
1330
1331 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1332 v = strings.TrimSpace(v)
1333 if v != "" && v != "false" {
1334 return false
1335 }
1336 }
1337 return true
1338}
1339
Ramy Medhatbbf25672019-07-17 12:30:04 +00001340func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001341 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001342 v = strings.TrimSpace(v)
1343 if v != "" && v != "false" {
1344 return true
1345 }
1346 }
1347 return false
1348}
1349
Chris Parsonsef615e52022-08-18 22:04:11 -04001350func (c *configImpl) BazelBuildEnabled() bool {
MarkDacekb78465d2022-10-18 20:10:16 +00001351 return c.bazelProdMode || c.bazelDevMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001352}
1353
Ramy Medhatbbf25672019-07-17 12:30:04 +00001354func (c *configImpl) StartRBE() bool {
1355 if !c.UseRBE() {
1356 return false
1357 }
1358
1359 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1360 v = strings.TrimSpace(v)
1361 if v != "" && v != "false" {
1362 return false
1363 }
1364 }
1365 return true
1366}
1367
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001368func (c *configImpl) rbeProxyLogsDir() string {
1369 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001370 if v, ok := c.environ.Get(f); ok {
1371 return v
1372 }
1373 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001374 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1375 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001376}
1377
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001378func (c *configImpl) shouldCleanupRBELogsDir() bool {
1379 // Perform a log directory cleanup only when the log directory
1380 // is auto created by the build rather than user-specified.
1381 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1382 if _, ok := c.environ.Get(f); ok {
1383 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001384 }
1385 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001386 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001387}
1388
1389func (c *configImpl) rbeExecRoot() string {
1390 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1391 if v, ok := c.environ.Get(f); ok {
1392 return v
1393 }
1394 }
1395 wd, err := os.Getwd()
1396 if err != nil {
1397 return ""
1398 }
1399 return wd
1400}
1401
1402func (c *configImpl) rbeDir() string {
1403 if v, ok := c.environ.Get("RBE_DIR"); ok {
1404 return v
1405 }
1406 return "prebuilts/remoteexecution-client/live/"
1407}
1408
1409func (c *configImpl) rbeReproxy() string {
1410 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1411 if v, ok := c.environ.Get(f); ok {
1412 return v
1413 }
1414 }
1415 return filepath.Join(c.rbeDir(), "reproxy")
1416}
1417
1418func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001419 credFlags := []string{
1420 "use_application_default_credentials",
1421 "use_gce_credentials",
1422 "credential_file",
1423 "use_google_prod_creds",
1424 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001425 for _, cf := range credFlags {
1426 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1427 if v, ok := c.environ.Get(f); ok {
1428 v = strings.TrimSpace(v)
1429 if v != "" && v != "false" && v != "0" {
1430 return "RBE_" + cf, v
1431 }
1432 }
1433 }
1434 }
1435 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001436}
1437
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001438func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1439 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1440 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1441
1442 name := filepath.Join(dir, base)
1443 if len(name) < maxNameLen {
1444 return name, nil
1445 }
1446
1447 name = filepath.Join("/tmp", base)
1448 if len(name) < maxNameLen {
1449 return name, nil
1450 }
1451
1452 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1453}
1454
Kousik Kumar7bc78192022-04-27 14:52:56 -04001455// IsGooglerEnvironment returns true if the current build is running
1456// on a Google developer machine and false otherwise.
1457func (c *configImpl) IsGooglerEnvironment() bool {
1458 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1459 if v, ok := c.environ.Get(cf); ok {
1460 return v == "googler"
1461 }
1462 return false
1463}
1464
1465// GoogleProdCredsExist determine whether credentials exist on the
1466// Googler machine to use remote execution.
1467func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001468 if googleProdCredsExistCache {
1469 return googleProdCredsExistCache
1470 }
Kousik Kumar7bc78192022-04-27 14:52:56 -04001471 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1472 return false
1473 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001474 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001475 return true
1476}
1477
1478// UseRemoteBuild indicates whether to use a remote build acceleration system
1479// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001480func (c *configImpl) UseRemoteBuild() bool {
1481 return c.UseGoma() || c.UseRBE()
1482}
1483
Kousik Kumar7bc78192022-04-27 14:52:56 -04001484// StubbyExists checks whether the stubby binary exists on the machine running
1485// the build.
1486func (c *configImpl) StubbyExists() bool {
1487 if _, err := exec.LookPath("stubby"); err != nil {
1488 return false
1489 }
1490 return true
1491}
1492
Dan Willemsen1e704462016-08-21 15:17:17 -07001493// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001494// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001495// still limited by Parallel()
1496func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001497 if !c.UseRemoteBuild() {
1498 return 0
1499 }
1500 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1501 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001502 }
1503 return 500
1504}
1505
1506func (c *configImpl) SetKatiArgs(args []string) {
1507 c.katiArgs = args
1508}
1509
1510func (c *configImpl) SetNinjaArgs(args []string) {
1511 c.ninjaArgs = args
1512}
1513
1514func (c *configImpl) SetKatiSuffix(suffix string) {
1515 c.katiSuffix = suffix
1516}
1517
Dan Willemsene0879fc2017-08-04 15:06:27 -07001518func (c *configImpl) LastKatiSuffixFile() string {
1519 return filepath.Join(c.OutDir(), "last_kati_suffix")
1520}
1521
1522func (c *configImpl) HasKatiSuffix() bool {
1523 return c.katiSuffix != ""
1524}
1525
Dan Willemsen1e704462016-08-21 15:17:17 -07001526func (c *configImpl) KatiEnvFile() string {
1527 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1528}
1529
Dan Willemsen29971232018-09-26 14:58:30 -07001530func (c *configImpl) KatiBuildNinjaFile() string {
1531 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001532}
1533
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001534func (c *configImpl) KatiPackageNinjaFile() string {
1535 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1536}
1537
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001538func (c *configImpl) SoongVarsFile() string {
1539 return filepath.Join(c.SoongOutDir(), "soong.variables")
1540}
1541
Dan Willemsen1e704462016-08-21 15:17:17 -07001542func (c *configImpl) SoongNinjaFile() string {
1543 return filepath.Join(c.SoongOutDir(), "build.ninja")
1544}
1545
1546func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001547 if c.katiSuffix == "" {
1548 return filepath.Join(c.OutDir(), "combined.ninja")
1549 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001550 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1551}
1552
1553func (c *configImpl) SoongAndroidMk() string {
1554 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1555}
1556
1557func (c *configImpl) SoongMakeVarsMk() string {
1558 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1559}
1560
Dan Willemsenf052f782017-05-18 15:29:04 -07001561func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001562 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001563}
1564
Dan Willemsen02781d52017-05-12 19:28:13 -07001565func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001566 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1567}
1568
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001569func (c *configImpl) KatiPackageMkDir() string {
1570 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1571}
1572
Dan Willemsenf052f782017-05-18 15:29:04 -07001573func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001574 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001575}
1576
1577func (c *configImpl) HostOut() string {
1578 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1579}
1580
1581// This probably needs to be multi-valued, so not exporting it for now
1582func (c *configImpl) hostCrossOut() string {
1583 if runtime.GOOS == "linux" {
1584 return filepath.Join(c.hostOutRoot(), "windows-x86")
1585 } else {
1586 return ""
1587 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001588}
1589
Dan Willemsen1e704462016-08-21 15:17:17 -07001590func (c *configImpl) HostPrebuiltTag() string {
1591 if runtime.GOOS == "linux" {
1592 return "linux-x86"
1593 } else if runtime.GOOS == "darwin" {
1594 return "darwin-x86"
1595 } else {
1596 panic("Unsupported OS")
1597 }
1598}
Dan Willemsenf173d592017-04-27 14:28:00 -07001599
Dan Willemsen8122bd52017-10-12 20:20:41 -07001600func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001601 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1602 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001603 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1604 if _, err := os.Stat(asan); err == nil {
1605 return asan
1606 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001607 }
1608 }
1609 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1610}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001611
1612func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1613 c.brokenDupRules = val
1614}
1615
1616func (c *configImpl) BuildBrokenDupRules() bool {
1617 return c.brokenDupRules
1618}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001619
Dan Willemsen25e6f092019-04-09 10:22:43 -07001620func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1621 c.brokenUsesNetwork = val
1622}
1623
1624func (c *configImpl) BuildBrokenUsesNetwork() bool {
1625 return c.brokenUsesNetwork
1626}
1627
Dan Willemsene3336352020-01-02 19:10:38 -08001628func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1629 c.brokenNinjaEnvVars = val
1630}
1631
1632func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1633 return c.brokenNinjaEnvVars
1634}
1635
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001636func (c *configImpl) SetTargetDeviceDir(dir string) {
1637 c.targetDeviceDir = dir
1638}
1639
1640func (c *configImpl) TargetDeviceDir() string {
1641 return c.targetDeviceDir
1642}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001643
Patrice Arruda219eef32020-06-01 17:29:30 +00001644func (c *configImpl) BuildDateTime() string {
1645 return c.buildDateTime
1646}
1647
1648func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001649 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001650}
Patrice Arruda83842d72020-12-08 19:42:08 +00001651
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001652// LogsDir returns the absolute path to the logs directory where build log and
1653// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001654// directory. If the argument dist is specified, the logs directory
1655// is <dist_dir>/logs.
1656func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001657 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001658 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001659 // 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 -05001660 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001661 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001662 absDir, err := filepath.Abs(dir)
1663 if err != nil {
1664 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1665 os.Exit(1)
1666 }
1667 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001668}
1669
1670// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1671// where the bazel profiles are located.
1672func (c *configImpl) BazelMetricsDir() string {
1673 return filepath.Join(c.LogsDir(), "bazel_metrics")
1674}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001675
Chris Parsons53f68ae2022-03-03 12:01:40 -05001676// MkFileMetrics returns the file path for make-related metrics.
1677func (c *configImpl) MkMetrics() string {
1678 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1679}
1680
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001681func (c *configImpl) SetEmptyNinjaFile(v bool) {
1682 c.emptyNinjaFile = v
1683}
1684
1685func (c *configImpl) EmptyNinjaFile() bool {
1686 return c.emptyNinjaFile
1687}
Yu Liu6e13b402021-07-27 14:29:06 -07001688
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001689func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1690 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1691}
1692
Chris Parsons9402ca82023-02-23 17:28:06 -05001693func (c *configImpl) IsPersistentBazelEnabled() bool {
1694 return c.Environment().IsEnvTrue("USE_PERSISTENT_BAZEL")
1695}
1696
MarkDacekd06db5d2022-11-29 00:47:59 +00001697func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1698 return c.bazelForceEnabledModules
1699}
1700
MarkDacekd0e7cd32022-12-02 22:22:40 +00001701func (c *configImpl) SkipMetricsUpload() bool {
1702 return c.skipMetricsUpload
1703}
1704
MarkDacek6614d9c2022-12-07 21:57:38 +00001705// Returns a Time object if one was passed via a command-line flag.
1706// Otherwise returns the passed default.
1707func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1708 if c.buildStartedTime == 0 {
1709 return defaultTime
1710 }
1711 return time.UnixMilli(c.buildStartedTime)
1712}
1713
Yu Liu6e13b402021-07-27 14:29:06 -07001714func GetMetricsUploader(topDir string, env *Environment) string {
1715 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1716 metricsUploader := filepath.Join(topDir, p)
1717 if _, err := os.Stat(metricsUploader); err == nil {
1718 return metricsUploader
1719 }
1720 }
1721
1722 return ""
1723}