blob: 9e02cd6a009352d2dc869fa4e4c951be0114361f [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
Dan Willemsen1e704462016-08-21 15:17:17 -070091
92 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070093 katiArgs []string
94 ninjaArgs []string
95 katiSuffix string
96 targetDevice string
97 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +000098 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -070099
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800100 // Autodetected
101 totalRAM uint64
102
Dan Willemsene3336352020-01-02 19:10:38 -0800103 brokenDupRules bool
104 brokenUsesNetwork bool
105 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -0700106
107 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000108
MarkDacekb78465d2022-10-18 20:10:16 +0000109 bazelProdMode bool
110 bazelDevMode bool
111 bazelStagingMode bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000112
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700113 // Set by multiproduct_kati
114 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700115
116 metricsUploader string
MarkDacekd06db5d2022-11-29 00:47:59 +0000117
118 bazelForceEnabledModules string
Spandan Dasc5763832022-11-08 18:42:16 +0000119
Sam Delmerico98a73292023-02-21 11:50:29 -0500120 includeTags []string
121 sourceRootDirs []string
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900122
123 // Data source to write ninja weight list
124 ninjaWeightListSource NinjaWeightListSource
Dan Willemsen1e704462016-08-21 15:17:17 -0700125}
126
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900127type NinjaWeightListSource uint
128
129const (
130 // ninja doesn't use weight list.
131 NOT_USED NinjaWeightListSource = iota
132 // ninja uses weight list based on previous builds by ninja log
133 NINJA_LOG
134 // ninja thinks every task has the same weight.
135 EVENLY_DISTRIBUTED
136)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800137const srcDirFileCheck = "build/soong/root.bp"
138
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700139var buildFiles = []string{"Android.mk", "Android.bp"}
140
Patrice Arruda13848222019-04-22 17:12:02 -0700141type BuildAction uint
142
143const (
144 // Builds all of the modules and their dependencies of a specified directory, relative to the root
145 // directory of the source tree.
146 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
147
148 // Builds all of the modules and their dependencies of a list of specified directories. All specified
149 // directories are relative to the root directory of the source tree.
150 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700151
152 // Build a list of specified modules. If none was specified, simply build the whole source tree.
153 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700154)
155
156// checkTopDir validates that the current directory is at the root directory of the source tree.
157func checkTopDir(ctx Context) {
158 if _, err := os.Stat(srcDirFileCheck); err != nil {
159 if os.IsNotExist(err) {
160 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
161 }
162 ctx.Fatalln("Error verifying tree state:", err)
163 }
164}
165
Kousik Kumarc8818332023-01-16 16:33:05 +0000166// fetchEnvConfig optionally fetches a configuration file that can then subsequently be
167// loaded into Soong environment to control certain aspects of build behavior (e.g., enabling RBE).
168// If a configuration file already exists on disk, the fetch is run in the background
169// so as to NOT block the rest of the build execution.
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500170func fetchEnvConfig(ctx Context, config *configImpl, envConfigName string) error {
David Goldsmith62243a32022-04-08 13:42:04 +0000171 configName := envConfigName + "." + jsonSuffix
Kousik Kumarc75e1292022-07-07 02:20:51 +0000172 expConfigFetcher := &smpb.ExpConfigFetcher{Filename: &configName}
David Goldsmith62243a32022-04-08 13:42:04 +0000173 defer func() {
174 ctx.Metrics.ExpConfigFetcher(expConfigFetcher)
175 }()
Kousik Kumarc75e1292022-07-07 02:20:51 +0000176 if !config.GoogleProdCredsExist() {
177 status := smpb.ExpConfigFetcher_MISSING_GCERT
178 expConfigFetcher.Status = &status
179 return nil
180 }
David Goldsmith62243a32022-04-08 13:42:04 +0000181
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500182 s, err := os.Stat(configFetcher)
183 if err != nil {
184 if os.IsNotExist(err) {
185 return nil
186 }
187 return err
188 }
189 if s.Mode()&0111 == 0 {
David Goldsmith62243a32022-04-08 13:42:04 +0000190 status := smpb.ExpConfigFetcher_ERROR
191 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500192 return fmt.Errorf("configuration fetcher binary %v is not executable: %v", configFetcher, s.Mode())
193 }
194
Kousik Kumarc8818332023-01-16 16:33:05 +0000195 configExists := false
196 outConfigFilePath := filepath.Join(config.OutDir(), configName)
197 if _, err := os.Stat(outConfigFilePath); err == nil {
198 configExists = true
199 }
200
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500201 tCtx, cancel := context.WithTimeout(ctx, envConfigFetchTimeout)
David Goldsmith62243a32022-04-08 13:42:04 +0000202 fetchStart := time.Now()
203 cmd := exec.CommandContext(tCtx, configFetcher, "-output_config_dir", config.OutDir(),
204 "-output_config_name", configName)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500205 if err := cmd.Start(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000206 status := smpb.ExpConfigFetcher_ERROR
207 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500208 return err
209 }
210
Kousik Kumarc8818332023-01-16 16:33:05 +0000211 fetchCfg := func() error {
212 if err := cmd.Wait(); err != nil {
213 status := smpb.ExpConfigFetcher_ERROR
214 expConfigFetcher.Status = &status
215 return err
216 }
217 fetchEnd := time.Now()
218 expConfigFetcher.Micros = proto.Uint64(uint64(fetchEnd.Sub(fetchStart).Microseconds()))
219 expConfigFetcher.Filename = proto.String(outConfigFilePath)
220
221 if _, err := os.Stat(outConfigFilePath); err != nil {
222 status := smpb.ExpConfigFetcher_NO_CONFIG
223 expConfigFetcher.Status = &status
224 return err
225 }
David Goldsmith62243a32022-04-08 13:42:04 +0000226 status := smpb.ExpConfigFetcher_CONFIG
227 expConfigFetcher.Status = &status
Kousik Kumarc8818332023-01-16 16:33:05 +0000228 return nil
David Goldsmith62243a32022-04-08 13:42:04 +0000229 }
Kousik Kumarc8818332023-01-16 16:33:05 +0000230
231 // If a config file does not exist, wait for the config file to be fetched. Otherwise
232 // fetch the config file in the background and return immediately.
233 if !configExists {
234 defer cancel()
235 return fetchCfg()
236 }
237
238 go func() {
239 defer cancel()
240 if err := fetchCfg(); err != nil {
241 ctx.Verbosef("Failed to fetch config file %v: %v\n", configName, err)
242 }
243 }()
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500244 return nil
245}
246
MarkDacek7901e582023-01-09 19:48:01 +0000247func loadEnvConfig(ctx Context, config *configImpl, bc string) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500248 if bc == "" {
249 return nil
250 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500251
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500252 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500253 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500254 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500255 envConfigDir,
256 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500257 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500258 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
259 envVarsJSON, err := ioutil.ReadFile(cfgFile)
260 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500261 continue
262 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500263 ctx.Verbosef("Loading config file %v\n", cfgFile)
264 var envVars map[string]map[string]string
265 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
266 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
267 continue
268 }
269 for k, v := range envVars["env"] {
270 if os.Getenv(k) != "" {
271 continue
272 }
273 config.environ.Set(k, v)
274 }
275 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
276 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500277 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500278
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500279 return nil
280}
281
Chris Parsonsb6e96902022-10-31 20:08:45 -0400282func defaultBazelProdMode(cfg *configImpl) bool {
MarkDacekd06db5d2022-11-29 00:47:59 +0000283 // Environment flag to disable Bazel for users which experience
Chris Parsonsb6e96902022-10-31 20:08:45 -0400284 // broken bazel-handled builds, or significant performance regressions.
285 if cfg.IsBazelMixedBuildForceDisabled() {
286 return false
287 }
288 // Darwin-host builds are currently untested with Bazel.
289 if runtime.GOOS == "darwin" {
290 return false
291 }
Chris Parsons035e03a2022-11-01 14:25:45 -0400292 return true
Chris Parsonsb6e96902022-10-31 20:08:45 -0400293}
294
MarkDacek6614d9c2022-12-07 21:57:38 +0000295func UploadOnlyConfig(ctx Context, _ ...string) Config {
296 ret := &configImpl{
297 environ: OsEnvironment(),
298 sandboxConfig: &SandboxConfig{},
299 }
MarkDacek7901e582023-01-09 19:48:01 +0000300 srcDir := absPath(ctx, ".")
301 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
302 if err := loadEnvConfig(ctx, ret, bc); err != nil {
303 ctx.Fatalln("Failed to parse env config files: %v", err)
304 }
305 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
MarkDacek6614d9c2022-12-07 21:57:38 +0000306 return Config{ret}
307}
308
Dan Willemsen1e704462016-08-21 15:17:17 -0700309func NewConfig(ctx Context, args ...string) Config {
310 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000311 environ: OsEnvironment(),
312 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700313 }
314
Patrice Arruda90109172020-07-28 18:07:27 +0000315 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700316 ret.parallel = runtime.NumCPU() + 2
317 ret.keepGoing = 1
318
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800319 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700320 ret.parseArgs(ctx, args)
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800321 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700322 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
323 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
324 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800325 outDir := "out"
326 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
327 if wd, err := os.Getwd(); err != nil {
328 ctx.Fatalln("Failed to get working directory:", err)
329 } else {
330 outDir = filepath.Join(baseDir, filepath.Base(wd))
331 }
332 }
333 ret.environ.Set("OUT_DIR", outDir)
334 }
335
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500336 // loadEnvConfig needs to know what the OUT_DIR is, so it should
337 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000338 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
339
340 if bc != "" {
341 if err := fetchEnvConfig(ctx, ret, bc); err != nil {
342 ctx.Verbosef("Failed to fetch config file: %v\n", err)
Kousik Kumarc8818332023-01-16 16:33:05 +0000343 }
344 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000345 ctx.Fatalln("Failed to parse env config files: %v", err)
346 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500347 }
348
Dan Willemsen2d31a442018-10-20 21:33:41 -0700349 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
350 ret.distDir = filepath.Clean(distDir)
351 } else {
352 ret.distDir = filepath.Join(ret.OutDir(), "dist")
353 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700354
Spandan Das05063612021-06-25 01:39:04 +0000355 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
356 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
357 }
358
Dan Willemsen1e704462016-08-21 15:17:17 -0700359 ret.environ.Unset(
360 // We're already using it
361 "USE_SOONG_UI",
362
363 // We should never use GOROOT/GOPATH from the shell environment
364 "GOROOT",
365 "GOPATH",
366
367 // These should only come from Soong, not the environment.
368 "CLANG",
369 "CLANG_CXX",
370 "CCC_CC",
371 "CCC_CXX",
372
373 // Used by the goma compiler wrapper, but should only be set by
374 // gomacc
375 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800376
377 // We handle this above
378 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700379
Dan Willemsen2d31a442018-10-20 21:33:41 -0700380 // This is handled above too, and set for individual commands later
381 "DIST_DIR",
382
Dan Willemsen68a09852017-04-18 13:56:57 -0700383 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000384 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700385 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700386 "DISPLAY",
387 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000388 "JAVAC",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700389 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700390 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700391
392 // Drop make flags
393 "MAKEFLAGS",
394 "MAKELEVEL",
395 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700396
397 // Set in envsetup.sh, reset in makefiles
398 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700399
400 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
401 "ANDROID_BUILD_TOP",
402 "ANDROID_HOST_OUT",
403 "ANDROID_PRODUCT_OUT",
404 "ANDROID_HOST_OUT_TESTCASES",
405 "ANDROID_TARGET_OUT_TESTCASES",
406 "ANDROID_TOOLCHAIN",
407 "ANDROID_TOOLCHAIN_2ND_ARCH",
408 "ANDROID_DEV_SCRIPTS",
409 "ANDROID_EMULATOR_PREBUILTS",
410 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700411 )
412
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400413 if ret.UseGoma() || ret.ForceUseGoma() {
414 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
415 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400416 }
417
Dan Willemsen1e704462016-08-21 15:17:17 -0700418 // Tell python not to spam the source tree with .pyc files.
419 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
420
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400421 tmpDir := absPath(ctx, ret.TempDir())
422 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800423
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700424 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
425 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
426 "llvm-binutils-stable/llvm-symbolizer")
427 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
428
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800429 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700430 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800431
Yu Liu6e13b402021-07-27 14:29:06 -0700432 srcDir := absPath(ctx, ".")
433 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700434 ctx.Println("You are building in a directory whose absolute path contains a space character:")
435 ctx.Println()
436 ctx.Printf("%q\n", srcDir)
437 ctx.Println()
438 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700439 }
440
Yu Liu6e13b402021-07-27 14:29:06 -0700441 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
442
Dan Willemsendb8457c2017-05-12 16:38:17 -0700443 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700444 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
445 ctx.Println()
446 ctx.Printf("%q\n", outDir)
447 ctx.Println()
448 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700449 }
450
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000451 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700452 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
453 ctx.Println()
454 ctx.Printf("%q\n", distDir)
455 ctx.Println()
456 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700457 }
458
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700459 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000460 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
461 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100462 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800463 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700464 javaHome := func() string {
465 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
466 return override
467 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000468 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
469 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 +0100470 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000471 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
472 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
473 }
474 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700475 }()
476 absJavaHome := absPath(ctx, javaHome)
477
Dan Willemsened869522018-01-08 14:58:46 -0800478 ret.configureLocale(ctx)
479
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700480 newPath := []string{filepath.Join(absJavaHome, "bin")}
481 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
482 newPath = append(newPath, path)
483 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100484
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700485 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
486 ret.environ.Set("JAVA_HOME", absJavaHome)
487 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000488 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
489 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100490 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700491 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
492
LaMont Jones52a72432023-03-09 18:19:35 +0000493 if ret.MultitreeBuild() {
494 ret.environ.Set("MULTITREE_BUILD", "true")
495 }
496
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800497 outDir := ret.OutDir()
498 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800499 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800500 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800501 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800502 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800503 }
Colin Cross28f527c2019-11-26 16:19:04 -0800504
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800505 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
506
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400507 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400508 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400509 ret.environ.Set(k, v)
510 }
511 }
512
Patrice Arruda83842d72020-12-08 19:42:08 +0000513 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800514 if err := os.RemoveAll(bpd); err != nil {
515 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
516 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000517
Patrice Arruda96850362020-08-11 20:41:11 +0000518 c := Config{ret}
519 storeConfigMetrics(ctx, c)
520 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700521}
522
Patrice Arruda13848222019-04-22 17:12:02 -0700523// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
524// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700525func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
526 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700527}
528
Patrice Arruda96850362020-08-11 20:41:11 +0000529// storeConfigMetrics selects a set of configuration information and store in
530// the metrics system for further analysis.
531func storeConfigMetrics(ctx Context, config Config) {
532 if ctx.Metrics == nil {
533 return
534 }
535
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400536 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000537
538 s := &smpb.SystemResourceInfo{
539 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
540 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
541 }
542 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000543}
544
Jeongik Cha8d63d562023-03-17 03:52:13 +0900545func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900546 switch s {
547 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900548 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900549 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900550 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900551 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900552 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900553 }
554}
555
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400556func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700557 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400558 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
559 UseGoma: proto.Bool(config.UseGoma()),
560 UseRbe: proto.Bool(config.UseRBE()),
561 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
562 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900563 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400564 }
Yu Liue737a992021-10-04 13:21:41 -0700565 c.Targets = append(c.Targets, config.arguments...)
566
567 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400568}
569
Patrice Arruda13848222019-04-22 17:12:02 -0700570// getConfigArgs processes the command arguments based on the build action and creates a set of new
571// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700572func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700573 // The next block of code verifies that the current directory is the root directory of the source
574 // tree. It then finds the relative path of dir based on the root directory of the source tree
575 // and verify that dir is inside of the source tree.
576 checkTopDir(ctx)
577 topDir, err := os.Getwd()
578 if err != nil {
579 ctx.Fatalf("Error retrieving top directory: %v", err)
580 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700581 dir, err = filepath.EvalSymlinks(dir)
582 if err != nil {
583 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
584 }
Patrice Arruda13848222019-04-22 17:12:02 -0700585 dir, err = filepath.Abs(dir)
586 if err != nil {
587 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
588 }
589 relDir, err := filepath.Rel(topDir, dir)
590 if err != nil {
591 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
592 }
593 // If there are ".." in the path, it's not in the source tree.
594 if strings.Contains(relDir, "..") {
595 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
596 }
597
598 configArgs := args[:]
599
600 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
601 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
602 targetNamePrefix := "MODULES-IN-"
603 if inList("GET-INSTALL-PATH", configArgs) {
604 targetNamePrefix = "GET-INSTALL-PATH-IN-"
605 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
606 }
607
Patrice Arruda13848222019-04-22 17:12:02 -0700608 var targets []string
609
610 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700611 case BUILD_MODULES:
612 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700613 case BUILD_MODULES_IN_A_DIRECTORY:
614 // If dir is the root source tree, all the modules are built of the source tree are built so
615 // no need to find the build file.
616 if topDir == dir {
617 break
618 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700619
Patrice Arruda13848222019-04-22 17:12:02 -0700620 buildFile := findBuildFile(ctx, relDir)
621 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700622 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700623 }
Patrice Arruda13848222019-04-22 17:12:02 -0700624 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
625 case BUILD_MODULES_IN_DIRECTORIES:
626 newConfigArgs, dirs := splitArgs(configArgs)
627 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700628 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700629 }
630
631 // Tidy only override all other specified targets.
632 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
633 if tidyOnly == "true" || tidyOnly == "1" {
634 configArgs = append(configArgs, "tidy_only")
635 } else {
636 configArgs = append(configArgs, targets...)
637 }
638
639 return configArgs
640}
641
642// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
643func convertToTarget(dir string, targetNamePrefix string) string {
644 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
645}
646
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700647// hasBuildFile returns true if dir contains an Android build file.
648func hasBuildFile(ctx Context, dir string) bool {
649 for _, buildFile := range buildFiles {
650 _, err := os.Stat(filepath.Join(dir, buildFile))
651 if err == nil {
652 return true
653 }
654 if !os.IsNotExist(err) {
655 ctx.Fatalf("Error retrieving the build file stats: %v", err)
656 }
657 }
658 return false
659}
660
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700661// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
662// in the current and any sub directory of dir. If a build file is not found, traverse the path
663// up by one directory and repeat again until either a build file is found or reached to the root
664// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
665// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700666func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700667 // If the string is empty or ".", assume it is top directory of the source tree.
668 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700669 return ""
670 }
671
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700672 found := false
673 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
674 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
675 if err != nil {
676 return err
677 }
678 if found {
679 return filepath.SkipDir
680 }
681 if info.IsDir() {
682 return nil
683 }
684 for _, buildFile := range buildFiles {
685 if info.Name() == buildFile {
686 found = true
687 return filepath.SkipDir
688 }
689 }
690 return nil
691 })
692 if err != nil {
693 ctx.Fatalf("Error finding Android build file: %v", err)
694 }
695
696 if found {
697 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700698 }
699 }
700
701 return ""
702}
703
704// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
705func splitArgs(args []string) (newArgs []string, dirs []string) {
706 specialArgs := map[string]bool{
707 "showcommands": true,
708 "snod": true,
709 "dist": true,
710 "checkbuild": true,
711 }
712
713 newArgs = []string{}
714 dirs = []string{}
715
716 for _, arg := range args {
717 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
718 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
719 newArgs = append(newArgs, arg)
720 continue
721 }
722
723 if _, ok := specialArgs[arg]; ok {
724 newArgs = append(newArgs, arg)
725 continue
726 }
727
728 dirs = append(dirs, arg)
729 }
730
731 return newArgs, dirs
732}
733
734// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
735// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
736// source root tree where the build action command was invoked. Each directory is validated if the
737// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700738func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700739 for _, dir := range dirs {
740 // The directory may have specified specific modules to build. ":" is the separator to separate
741 // the directory and the list of modules.
742 s := strings.Split(dir, ":")
743 l := len(s)
744 if l > 2 { // more than one ":" was specified.
745 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
746 }
747
748 dir = filepath.Join(relDir, s[0])
749 if _, err := os.Stat(dir); err != nil {
750 ctx.Fatalf("couldn't find directory %s", dir)
751 }
752
753 // Verify that if there are any targets specified after ":". Each target is separated by ",".
754 var newTargets []string
755 if l == 2 && s[1] != "" {
756 newTargets = strings.Split(s[1], ",")
757 if inList("", newTargets) {
758 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
759 }
760 }
761
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700762 // If there are specified targets to build in dir, an android build file must exist for the one
763 // shot build. For the non-targets case, find the appropriate build file and build all the
764 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700765 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700766 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700767 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
768 }
769 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700770 buildFile := findBuildFile(ctx, dir)
771 if buildFile == "" {
772 ctx.Fatalf("Build file not found for %s directory", dir)
773 }
774 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700775 }
776
Patrice Arruda13848222019-04-22 17:12:02 -0700777 targets = append(targets, newTargets...)
778 }
779
Dan Willemsence41e942019-07-29 23:39:30 -0700780 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700781}
782
Dan Willemsen9b587492017-07-10 22:13:00 -0700783func (c *configImpl) parseArgs(ctx Context, args []string) {
784 for i := 0; i < len(args); i++ {
785 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100786 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700787 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200788 } else if arg == "--empty-ninja-file" {
789 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100790 } else if arg == "--skip-ninja" {
791 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700792 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700793 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
794 // but it does run a Kati ninja file if the .kati_enabled marker file was created
795 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000796 c.skipConfig = true
797 c.skipKati = true
798 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100799 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000800 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100801 } else if arg == "--soong-only" {
802 c.skipKati = true
803 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200804 } else if arg == "--config-only" {
805 c.skipKati = true
806 c.skipKatiNinja = true
807 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700808 } else if arg == "--skip-config" {
809 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700810 } else if arg == "--skip-soong-tests" {
811 c.skipSoongTests = true
MarkDacekd0e7cd32022-12-02 22:22:40 +0000812 } else if arg == "--skip-metrics-upload" {
813 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500814 } else if arg == "--mk-metrics" {
815 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000816 } else if arg == "--multitree-build" {
817 c.multitreeBuild = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400818 } else if arg == "--bazel-mode" {
819 c.bazelProdMode = true
820 } else if arg == "--bazel-mode-dev" {
821 c.bazelDevMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000822 } else if arg == "--bazel-mode-staging" {
823 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000824 } else if arg == "--search-api-dir" {
825 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900826 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
827 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
828 if source == "ninja_log" {
829 c.ninjaWeightListSource = NINJA_LOG
830 } else if source == "evenly_distributed" {
831 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
832 } else if source == "not_used" {
833 c.ninjaWeightListSource = NOT_USED
834 } else {
835 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
836 }
MarkDacekb96561e2022-12-02 04:34:43 +0000837 } else if strings.HasPrefix(arg, "--build-command=") {
838 buildCmd := strings.TrimPrefix(arg, "--build-command=")
839 // remove quotations
840 buildCmd = strings.TrimPrefix(buildCmd, "\"")
841 buildCmd = strings.TrimSuffix(buildCmd, "\"")
842 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000843 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
844 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
MarkDacek6614d9c2022-12-07 21:57:38 +0000845 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
846 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
847 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
848 if err == nil {
849 c.buildStartedTime = val
850 } else {
851 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
852 }
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700853 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700854 parseArgNum := func(def int) int {
855 if len(arg) > 2 {
856 p, err := strconv.ParseUint(arg[2:], 10, 31)
857 if err != nil {
858 ctx.Fatalf("Failed to parse %q: %v", arg, err)
859 }
860 return int(p)
861 } else if i+1 < len(args) {
862 p, err := strconv.ParseUint(args[i+1], 10, 31)
863 if err == nil {
864 i++
865 return int(p)
866 }
867 }
868 return def
869 }
870
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700871 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700872 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700873 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700874 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700875 } else {
876 ctx.Fatalln("Unknown option:", arg)
877 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700878 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700879 if k == "OUT_DIR" {
880 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
881 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700882 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700883 } else if arg == "dist" {
884 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200885 } else if arg == "json-module-graph" {
886 c.jsonModuleGraph = true
887 } else if arg == "bp2build" {
888 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000889 } else if arg == "api_bp2build" {
890 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200891 } else if arg == "queryview" {
892 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200893 } else if arg == "soong_docs" {
894 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700895 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700896 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800897 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700898 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700899 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700900 }
901 }
Chris Parsonsb6e96902022-10-31 20:08:45 -0400902 if (!c.bazelProdMode) && (!c.bazelDevMode) && (!c.bazelStagingMode) {
903 c.bazelProdMode = defaultBazelProdMode(c)
904 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700905}
906
Dan Willemsened869522018-01-08 14:58:46 -0800907func (c *configImpl) configureLocale(ctx Context) {
908 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
909 output, err := cmd.Output()
910
911 var locales []string
912 if err == nil {
913 locales = strings.Split(string(output), "\n")
914 } else {
915 // If we're unable to list the locales, let's assume en_US.UTF-8
916 locales = []string{"en_US.UTF-8"}
917 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
918 }
919
920 // gettext uses LANGUAGE, which is passed directly through
921
922 // For LANG and LC_*, only preserve the evaluated version of
923 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800924 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800925 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800926 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800927 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800928 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800929 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800930 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800931 }
932
933 c.environ.UnsetWithPrefix("LC_")
934
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800935 if userLang != "" {
936 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800937 }
938
939 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
940 // for others)
941 if inList("C.UTF-8", locales) {
942 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500943 } else if inList("C.utf8", locales) {
944 // These normalize to the same thing
945 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800946 } else if inList("en_US.UTF-8", locales) {
947 c.environ.Set("LANG", "en_US.UTF-8")
948 } else if inList("en_US.utf8", locales) {
949 // These normalize to the same thing
950 c.environ.Set("LANG", "en_US.UTF-8")
951 } else {
952 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
953 }
954}
955
Dan Willemsen1e704462016-08-21 15:17:17 -0700956func (c *configImpl) Environment() *Environment {
957 return c.environ
958}
959
960func (c *configImpl) Arguments() []string {
961 return c.arguments
962}
963
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200964func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200965 if len(c.Arguments()) > 0 {
966 // Explicit targets requested that are not special targets like b2pbuild
967 // or the JSON module graph
968 return true
969 }
970
Spandan Das5af0bd32022-09-28 20:43:08 +0000971 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200972 // Command line was empty, the default Ninja target is built
973 return true
974 }
975
Liz Kammer88677422021-12-15 15:03:19 -0500976 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
977 if c.Dist() && !c.Bp2Build() {
978 return true
979 }
980
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200981 // build.ninja doesn't need to be generated
982 return false
983}
984
Dan Willemsen1e704462016-08-21 15:17:17 -0700985func (c *configImpl) OutDir() string {
986 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700987 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700988 }
989 return "out"
990}
991
Dan Willemsen8a073a82017-02-04 17:30:44 -0800992func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400993 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000994}
995
996func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700997 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800998}
999
Dan Willemsen1e704462016-08-21 15:17:17 -07001000func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001001 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001002 return c.arguments
1003 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001004 return c.ninjaArgs
1005}
1006
Jingwen Chen7c6089a2020-11-02 02:56:20 -05001007func (c *configImpl) BazelOutDir() string {
1008 return filepath.Join(c.OutDir(), "bazel")
1009}
1010
Liz Kammer2af5ea82022-11-11 14:21:03 -05001011func (c *configImpl) bazelOutputBase() string {
1012 return filepath.Join(c.BazelOutDir(), "output")
1013}
1014
Dan Willemsen1e704462016-08-21 15:17:17 -07001015func (c *configImpl) SoongOutDir() string {
1016 return filepath.Join(c.OutDir(), "soong")
1017}
1018
Spandan Das394aa322022-11-03 17:02:10 +00001019func (c *configImpl) ApiSurfacesOutDir() string {
1020 return filepath.Join(c.OutDir(), "api_surfaces")
1021}
1022
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001023func (c *configImpl) PrebuiltOS() string {
1024 switch runtime.GOOS {
1025 case "linux":
1026 return "linux-x86"
1027 case "darwin":
1028 return "darwin-x86"
1029 default:
1030 panic("Unknown GOOS")
1031 }
1032}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001033
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001034func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001035 if c.SkipKatiNinja() {
1036 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1037 } else {
1038 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1039 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001040}
1041
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001042func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001043 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001044}
1045
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001046func (c *configImpl) UsedEnvFile(tag string) string {
1047 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1048}
1049
Lukacs T. Berkic541cd22022-10-26 07:26:50 +00001050func (c *configImpl) Bp2BuildFilesMarkerFile() string {
1051 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
1052}
1053
1054func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001055 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +02001056}
1057
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001058func (c *configImpl) SoongDocsHtml() string {
1059 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1060}
1061
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001062func (c *configImpl) QueryviewMarkerFile() string {
1063 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1064}
1065
Spandan Das5af0bd32022-09-28 20:43:08 +00001066func (c *configImpl) ApiBp2buildMarkerFile() string {
1067 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
1068}
1069
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001070func (c *configImpl) ModuleGraphFile() string {
1071 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1072}
1073
kgui67007242022-01-25 13:50:25 +08001074func (c *configImpl) ModuleActionsFile() string {
1075 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1076}
1077
Jeff Gastonefc1b412017-03-29 17:29:06 -07001078func (c *configImpl) TempDir() string {
1079 return shared.TempDirForOutDir(c.SoongOutDir())
1080}
1081
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001082func (c *configImpl) FileListDir() string {
1083 return filepath.Join(c.OutDir(), ".module_paths")
1084}
1085
Dan Willemsen1e704462016-08-21 15:17:17 -07001086func (c *configImpl) KatiSuffix() string {
1087 if c.katiSuffix != "" {
1088 return c.katiSuffix
1089 }
1090 panic("SetKatiSuffix has not been called")
1091}
1092
Colin Cross37193492017-11-16 17:55:00 -08001093// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1094// user is interested in additional checks at the expense of build time.
1095func (c *configImpl) Checkbuild() bool {
1096 return c.checkbuild
1097}
1098
Dan Willemsen8a073a82017-02-04 17:30:44 -08001099func (c *configImpl) Dist() bool {
1100 return c.dist
1101}
1102
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001103func (c *configImpl) JsonModuleGraph() bool {
1104 return c.jsonModuleGraph
1105}
1106
1107func (c *configImpl) Bp2Build() bool {
1108 return c.bp2build
1109}
1110
Spandan Das5af0bd32022-09-28 20:43:08 +00001111func (c *configImpl) ApiBp2build() bool {
1112 return c.apiBp2build
1113}
1114
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001115func (c *configImpl) Queryview() bool {
1116 return c.queryview
1117}
1118
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001119func (c *configImpl) SoongDocs() bool {
1120 return c.soongDocs
1121}
1122
Dan Willemsen1e704462016-08-21 15:17:17 -07001123func (c *configImpl) IsVerbose() bool {
1124 return c.verbose
1125}
1126
LaMont Jones52a72432023-03-09 18:19:35 +00001127func (c *configImpl) MultitreeBuild() bool {
1128 return c.multitreeBuild
1129}
1130
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001131func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1132 return c.ninjaWeightListSource
1133}
1134
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001135func (c *configImpl) SkipKati() bool {
1136 return c.skipKati
1137}
1138
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001139func (c *configImpl) SkipKatiNinja() bool {
1140 return c.skipKatiNinja
1141}
1142
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001143func (c *configImpl) SkipSoong() bool {
1144 return c.skipSoong
1145}
1146
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001147func (c *configImpl) SkipNinja() bool {
1148 return c.skipNinja
1149}
1150
Anton Hansson5a7861a2021-06-04 10:09:01 +01001151func (c *configImpl) SetSkipNinja(v bool) {
1152 c.skipNinja = v
1153}
1154
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001155func (c *configImpl) SkipConfig() bool {
1156 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001157}
1158
Dan Willemsen1e704462016-08-21 15:17:17 -07001159func (c *configImpl) TargetProduct() string {
1160 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1161 return v
1162 }
1163 panic("TARGET_PRODUCT is not defined")
1164}
1165
Dan Willemsen02781d52017-05-12 19:28:13 -07001166func (c *configImpl) TargetDevice() string {
1167 return c.targetDevice
1168}
1169
1170func (c *configImpl) SetTargetDevice(device string) {
1171 c.targetDevice = device
1172}
1173
1174func (c *configImpl) TargetBuildVariant() string {
1175 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1176 return v
1177 }
1178 panic("TARGET_BUILD_VARIANT is not defined")
1179}
1180
Dan Willemsen1e704462016-08-21 15:17:17 -07001181func (c *configImpl) KatiArgs() []string {
1182 return c.katiArgs
1183}
1184
1185func (c *configImpl) Parallel() int {
1186 return c.parallel
1187}
1188
Sam Delmerico98a73292023-02-21 11:50:29 -05001189func (c *configImpl) GetSourceRootDirs() []string {
1190 return c.sourceRootDirs
1191}
1192
1193func (c *configImpl) SetSourceRootDirs(i []string) {
1194 c.sourceRootDirs = i
1195}
1196
Spandan Dasc5763832022-11-08 18:42:16 +00001197func (c *configImpl) GetIncludeTags() []string {
1198 return c.includeTags
1199}
1200
1201func (c *configImpl) SetIncludeTags(i []string) {
1202 c.includeTags = i
1203}
1204
MarkDacek6614d9c2022-12-07 21:57:38 +00001205func (c *configImpl) GetLogsPrefix() string {
1206 return c.logsPrefix
1207}
1208
1209func (c *configImpl) SetLogsPrefix(prefix string) {
1210 c.logsPrefix = prefix
1211}
1212
Colin Cross8b8bec32019-11-15 13:18:43 -08001213func (c *configImpl) HighmemParallel() int {
1214 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1215 return i
1216 }
1217
1218 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1219 parallel := c.Parallel()
1220 if c.UseRemoteBuild() {
1221 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1222 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1223 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1224 // Return 1/16th of the size of the local pool, rounding up.
1225 return (parallel + 15) / 16
1226 } else if c.totalRAM == 0 {
1227 // Couldn't detect the total RAM, don't restrict highmem processes.
1228 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001229 } else if c.totalRAM <= 16*1024*1024*1024 {
1230 // Less than 16GB of ram, restrict to 1 highmem processes
1231 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001232 } else if c.totalRAM <= 32*1024*1024*1024 {
1233 // Less than 32GB of ram, restrict to 2 highmem processes
1234 return 2
1235 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1236 // If less than 8GB total RAM per process, reduce the number of highmem processes
1237 return p
1238 }
1239 // No restriction on highmem processes
1240 return parallel
1241}
1242
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001243func (c *configImpl) TotalRAM() uint64 {
1244 return c.totalRAM
1245}
1246
Kousik Kumarec478642020-09-21 13:39:24 -04001247// ForceUseGoma determines whether we should override Goma deprecation
1248// and use Goma for the current build or not.
1249func (c *configImpl) ForceUseGoma() bool {
1250 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1251 v = strings.TrimSpace(v)
1252 if v != "" && v != "false" {
1253 return true
1254 }
1255 }
1256 return false
1257}
1258
Dan Willemsen1e704462016-08-21 15:17:17 -07001259func (c *configImpl) UseGoma() bool {
1260 if v, ok := c.environ.Get("USE_GOMA"); ok {
1261 v = strings.TrimSpace(v)
1262 if v != "" && v != "false" {
1263 return true
1264 }
1265 }
1266 return false
1267}
1268
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001269func (c *configImpl) StartGoma() bool {
1270 if !c.UseGoma() {
1271 return false
1272 }
1273
1274 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1275 v = strings.TrimSpace(v)
1276 if v != "" && v != "false" {
1277 return false
1278 }
1279 }
1280 return true
1281}
1282
Ramy Medhatbbf25672019-07-17 12:30:04 +00001283func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001284 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001285 v = strings.TrimSpace(v)
1286 if v != "" && v != "false" {
1287 return true
1288 }
1289 }
1290 return false
1291}
1292
Chris Parsonsef615e52022-08-18 22:04:11 -04001293func (c *configImpl) BazelBuildEnabled() bool {
MarkDacekb78465d2022-10-18 20:10:16 +00001294 return c.bazelProdMode || c.bazelDevMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001295}
1296
Ramy Medhatbbf25672019-07-17 12:30:04 +00001297func (c *configImpl) StartRBE() bool {
1298 if !c.UseRBE() {
1299 return false
1300 }
1301
1302 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1303 v = strings.TrimSpace(v)
1304 if v != "" && v != "false" {
1305 return false
1306 }
1307 }
1308 return true
1309}
1310
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001311func (c *configImpl) rbeProxyLogsDir() string {
1312 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001313 if v, ok := c.environ.Get(f); ok {
1314 return v
1315 }
1316 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001317 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1318 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001319}
1320
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001321func (c *configImpl) shouldCleanupRBELogsDir() bool {
1322 // Perform a log directory cleanup only when the log directory
1323 // is auto created by the build rather than user-specified.
1324 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1325 if _, ok := c.environ.Get(f); ok {
1326 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001327 }
1328 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001329 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001330}
1331
1332func (c *configImpl) rbeExecRoot() string {
1333 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1334 if v, ok := c.environ.Get(f); ok {
1335 return v
1336 }
1337 }
1338 wd, err := os.Getwd()
1339 if err != nil {
1340 return ""
1341 }
1342 return wd
1343}
1344
1345func (c *configImpl) rbeDir() string {
1346 if v, ok := c.environ.Get("RBE_DIR"); ok {
1347 return v
1348 }
1349 return "prebuilts/remoteexecution-client/live/"
1350}
1351
1352func (c *configImpl) rbeReproxy() string {
1353 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1354 if v, ok := c.environ.Get(f); ok {
1355 return v
1356 }
1357 }
1358 return filepath.Join(c.rbeDir(), "reproxy")
1359}
1360
1361func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001362 credFlags := []string{
1363 "use_application_default_credentials",
1364 "use_gce_credentials",
1365 "credential_file",
1366 "use_google_prod_creds",
1367 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001368 for _, cf := range credFlags {
1369 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1370 if v, ok := c.environ.Get(f); ok {
1371 v = strings.TrimSpace(v)
1372 if v != "" && v != "false" && v != "0" {
1373 return "RBE_" + cf, v
1374 }
1375 }
1376 }
1377 }
1378 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001379}
1380
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001381func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1382 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1383 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1384
1385 name := filepath.Join(dir, base)
1386 if len(name) < maxNameLen {
1387 return name, nil
1388 }
1389
1390 name = filepath.Join("/tmp", base)
1391 if len(name) < maxNameLen {
1392 return name, nil
1393 }
1394
1395 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1396}
1397
Kousik Kumar7bc78192022-04-27 14:52:56 -04001398// IsGooglerEnvironment returns true if the current build is running
1399// on a Google developer machine and false otherwise.
1400func (c *configImpl) IsGooglerEnvironment() bool {
1401 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1402 if v, ok := c.environ.Get(cf); ok {
1403 return v == "googler"
1404 }
1405 return false
1406}
1407
1408// GoogleProdCredsExist determine whether credentials exist on the
1409// Googler machine to use remote execution.
1410func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001411 if googleProdCredsExistCache {
1412 return googleProdCredsExistCache
1413 }
Kousik Kumar7bc78192022-04-27 14:52:56 -04001414 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1415 return false
1416 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001417 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001418 return true
1419}
1420
1421// UseRemoteBuild indicates whether to use a remote build acceleration system
1422// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001423func (c *configImpl) UseRemoteBuild() bool {
1424 return c.UseGoma() || c.UseRBE()
1425}
1426
Kousik Kumar7bc78192022-04-27 14:52:56 -04001427// StubbyExists checks whether the stubby binary exists on the machine running
1428// the build.
1429func (c *configImpl) StubbyExists() bool {
1430 if _, err := exec.LookPath("stubby"); err != nil {
1431 return false
1432 }
1433 return true
1434}
1435
Dan Willemsen1e704462016-08-21 15:17:17 -07001436// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001437// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001438// still limited by Parallel()
1439func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001440 if !c.UseRemoteBuild() {
1441 return 0
1442 }
1443 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1444 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001445 }
1446 return 500
1447}
1448
1449func (c *configImpl) SetKatiArgs(args []string) {
1450 c.katiArgs = args
1451}
1452
1453func (c *configImpl) SetNinjaArgs(args []string) {
1454 c.ninjaArgs = args
1455}
1456
1457func (c *configImpl) SetKatiSuffix(suffix string) {
1458 c.katiSuffix = suffix
1459}
1460
Dan Willemsene0879fc2017-08-04 15:06:27 -07001461func (c *configImpl) LastKatiSuffixFile() string {
1462 return filepath.Join(c.OutDir(), "last_kati_suffix")
1463}
1464
1465func (c *configImpl) HasKatiSuffix() bool {
1466 return c.katiSuffix != ""
1467}
1468
Dan Willemsen1e704462016-08-21 15:17:17 -07001469func (c *configImpl) KatiEnvFile() string {
1470 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1471}
1472
Dan Willemsen29971232018-09-26 14:58:30 -07001473func (c *configImpl) KatiBuildNinjaFile() string {
1474 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001475}
1476
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001477func (c *configImpl) KatiPackageNinjaFile() string {
1478 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1479}
1480
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001481func (c *configImpl) SoongVarsFile() string {
1482 return filepath.Join(c.SoongOutDir(), "soong.variables")
1483}
1484
Dan Willemsen1e704462016-08-21 15:17:17 -07001485func (c *configImpl) SoongNinjaFile() string {
1486 return filepath.Join(c.SoongOutDir(), "build.ninja")
1487}
1488
1489func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001490 if c.katiSuffix == "" {
1491 return filepath.Join(c.OutDir(), "combined.ninja")
1492 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001493 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1494}
1495
1496func (c *configImpl) SoongAndroidMk() string {
1497 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1498}
1499
1500func (c *configImpl) SoongMakeVarsMk() string {
1501 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1502}
1503
Dan Willemsenf052f782017-05-18 15:29:04 -07001504func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001505 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001506}
1507
Dan Willemsen02781d52017-05-12 19:28:13 -07001508func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001509 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1510}
1511
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001512func (c *configImpl) KatiPackageMkDir() string {
1513 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1514}
1515
Dan Willemsenf052f782017-05-18 15:29:04 -07001516func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001517 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001518}
1519
1520func (c *configImpl) HostOut() string {
1521 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1522}
1523
1524// This probably needs to be multi-valued, so not exporting it for now
1525func (c *configImpl) hostCrossOut() string {
1526 if runtime.GOOS == "linux" {
1527 return filepath.Join(c.hostOutRoot(), "windows-x86")
1528 } else {
1529 return ""
1530 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001531}
1532
Dan Willemsen1e704462016-08-21 15:17:17 -07001533func (c *configImpl) HostPrebuiltTag() string {
1534 if runtime.GOOS == "linux" {
1535 return "linux-x86"
1536 } else if runtime.GOOS == "darwin" {
1537 return "darwin-x86"
1538 } else {
1539 panic("Unsupported OS")
1540 }
1541}
Dan Willemsenf173d592017-04-27 14:28:00 -07001542
Dan Willemsen8122bd52017-10-12 20:20:41 -07001543func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001544 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1545 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001546 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1547 if _, err := os.Stat(asan); err == nil {
1548 return asan
1549 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001550 }
1551 }
1552 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1553}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001554
1555func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1556 c.brokenDupRules = val
1557}
1558
1559func (c *configImpl) BuildBrokenDupRules() bool {
1560 return c.brokenDupRules
1561}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001562
Dan Willemsen25e6f092019-04-09 10:22:43 -07001563func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1564 c.brokenUsesNetwork = val
1565}
1566
1567func (c *configImpl) BuildBrokenUsesNetwork() bool {
1568 return c.brokenUsesNetwork
1569}
1570
Dan Willemsene3336352020-01-02 19:10:38 -08001571func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1572 c.brokenNinjaEnvVars = val
1573}
1574
1575func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1576 return c.brokenNinjaEnvVars
1577}
1578
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001579func (c *configImpl) SetTargetDeviceDir(dir string) {
1580 c.targetDeviceDir = dir
1581}
1582
1583func (c *configImpl) TargetDeviceDir() string {
1584 return c.targetDeviceDir
1585}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001586
Patrice Arruda219eef32020-06-01 17:29:30 +00001587func (c *configImpl) BuildDateTime() string {
1588 return c.buildDateTime
1589}
1590
1591func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001592 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001593}
Patrice Arruda83842d72020-12-08 19:42:08 +00001594
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001595// LogsDir returns the absolute path to the logs directory where build log and
1596// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001597// directory. If the argument dist is specified, the logs directory
1598// is <dist_dir>/logs.
1599func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001600 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001601 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001602 // 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 -05001603 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001604 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001605 absDir, err := filepath.Abs(dir)
1606 if err != nil {
1607 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1608 os.Exit(1)
1609 }
1610 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001611}
1612
1613// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1614// where the bazel profiles are located.
1615func (c *configImpl) BazelMetricsDir() string {
1616 return filepath.Join(c.LogsDir(), "bazel_metrics")
1617}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001618
Chris Parsons53f68ae2022-03-03 12:01:40 -05001619// MkFileMetrics returns the file path for make-related metrics.
1620func (c *configImpl) MkMetrics() string {
1621 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1622}
1623
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001624func (c *configImpl) SetEmptyNinjaFile(v bool) {
1625 c.emptyNinjaFile = v
1626}
1627
1628func (c *configImpl) EmptyNinjaFile() bool {
1629 return c.emptyNinjaFile
1630}
Yu Liu6e13b402021-07-27 14:29:06 -07001631
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001632func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1633 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1634}
1635
Chris Parsons9402ca82023-02-23 17:28:06 -05001636func (c *configImpl) IsPersistentBazelEnabled() bool {
1637 return c.Environment().IsEnvTrue("USE_PERSISTENT_BAZEL")
1638}
1639
MarkDacekd06db5d2022-11-29 00:47:59 +00001640func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1641 return c.bazelForceEnabledModules
1642}
1643
MarkDacekd0e7cd32022-12-02 22:22:40 +00001644func (c *configImpl) SkipMetricsUpload() bool {
1645 return c.skipMetricsUpload
1646}
1647
MarkDacek6614d9c2022-12-07 21:57:38 +00001648// Returns a Time object if one was passed via a command-line flag.
1649// Otherwise returns the passed default.
1650func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1651 if c.buildStartedTime == 0 {
1652 return defaultTime
1653 }
1654 return time.UnixMilli(c.buildStartedTime)
1655}
1656
Yu Liu6e13b402021-07-27 14:29:06 -07001657func GetMetricsUploader(topDir string, env *Environment) string {
1658 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1659 metricsUploader := filepath.Join(topDir, p)
1660 if _, err := os.Stat(metricsUploader); err == nil {
1661 return metricsUploader
1662 }
1663 }
1664
1665 return ""
1666}