blob: 3fb38d771e466ad9bcc2b4534152e30daf38b71e [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
120 includeTags []string
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900121
122 // Data source to write ninja weight list
123 ninjaWeightListSource NinjaWeightListSource
Dan Willemsen1e704462016-08-21 15:17:17 -0700124}
125
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900126type NinjaWeightListSource uint
127
128const (
129 // ninja doesn't use weight list.
130 NOT_USED NinjaWeightListSource = iota
131 // ninja uses weight list based on previous builds by ninja log
132 NINJA_LOG
133 // ninja thinks every task has the same weight.
134 EVENLY_DISTRIBUTED
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900135 // ninja uses an external custom weight list
136 EXTERNAL_FILE
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900137)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800138const srcDirFileCheck = "build/soong/root.bp"
139
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700140var buildFiles = []string{"Android.mk", "Android.bp"}
141
Patrice Arruda13848222019-04-22 17:12:02 -0700142type BuildAction uint
143
144const (
145 // Builds all of the modules and their dependencies of a specified directory, relative to the root
146 // directory of the source tree.
147 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
148
149 // Builds all of the modules and their dependencies of a list of specified directories. All specified
150 // directories are relative to the root directory of the source tree.
151 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700152
153 // Build a list of specified modules. If none was specified, simply build the whole source tree.
154 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700155)
156
157// checkTopDir validates that the current directory is at the root directory of the source tree.
158func checkTopDir(ctx Context) {
159 if _, err := os.Stat(srcDirFileCheck); err != nil {
160 if os.IsNotExist(err) {
161 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
162 }
163 ctx.Fatalln("Error verifying tree state:", err)
164 }
165}
166
Kousik Kumarc8818332023-01-16 16:33:05 +0000167// fetchEnvConfig optionally fetches a configuration file that can then subsequently be
168// loaded into Soong environment to control certain aspects of build behavior (e.g., enabling RBE).
169// If a configuration file already exists on disk, the fetch is run in the background
170// so as to NOT block the rest of the build execution.
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500171func fetchEnvConfig(ctx Context, config *configImpl, envConfigName string) error {
David Goldsmith62243a32022-04-08 13:42:04 +0000172 configName := envConfigName + "." + jsonSuffix
Kousik Kumarc75e1292022-07-07 02:20:51 +0000173 expConfigFetcher := &smpb.ExpConfigFetcher{Filename: &configName}
David Goldsmith62243a32022-04-08 13:42:04 +0000174 defer func() {
175 ctx.Metrics.ExpConfigFetcher(expConfigFetcher)
176 }()
Kousik Kumarc75e1292022-07-07 02:20:51 +0000177 if !config.GoogleProdCredsExist() {
178 status := smpb.ExpConfigFetcher_MISSING_GCERT
179 expConfigFetcher.Status = &status
180 return nil
181 }
David Goldsmith62243a32022-04-08 13:42:04 +0000182
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500183 s, err := os.Stat(configFetcher)
184 if err != nil {
185 if os.IsNotExist(err) {
186 return nil
187 }
188 return err
189 }
190 if s.Mode()&0111 == 0 {
David Goldsmith62243a32022-04-08 13:42:04 +0000191 status := smpb.ExpConfigFetcher_ERROR
192 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500193 return fmt.Errorf("configuration fetcher binary %v is not executable: %v", configFetcher, s.Mode())
194 }
195
Kousik Kumarc8818332023-01-16 16:33:05 +0000196 configExists := false
197 outConfigFilePath := filepath.Join(config.OutDir(), configName)
198 if _, err := os.Stat(outConfigFilePath); err == nil {
199 configExists = true
200 }
201
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500202 tCtx, cancel := context.WithTimeout(ctx, envConfigFetchTimeout)
David Goldsmith62243a32022-04-08 13:42:04 +0000203 fetchStart := time.Now()
204 cmd := exec.CommandContext(tCtx, configFetcher, "-output_config_dir", config.OutDir(),
205 "-output_config_name", configName)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500206 if err := cmd.Start(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000207 status := smpb.ExpConfigFetcher_ERROR
208 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500209 return err
210 }
211
Kousik Kumarc8818332023-01-16 16:33:05 +0000212 fetchCfg := func() error {
213 if err := cmd.Wait(); err != nil {
214 status := smpb.ExpConfigFetcher_ERROR
215 expConfigFetcher.Status = &status
216 return err
217 }
218 fetchEnd := time.Now()
219 expConfigFetcher.Micros = proto.Uint64(uint64(fetchEnd.Sub(fetchStart).Microseconds()))
220 expConfigFetcher.Filename = proto.String(outConfigFilePath)
221
222 if _, err := os.Stat(outConfigFilePath); err != nil {
223 status := smpb.ExpConfigFetcher_NO_CONFIG
224 expConfigFetcher.Status = &status
225 return err
226 }
David Goldsmith62243a32022-04-08 13:42:04 +0000227 status := smpb.ExpConfigFetcher_CONFIG
228 expConfigFetcher.Status = &status
Kousik Kumarc8818332023-01-16 16:33:05 +0000229 return nil
David Goldsmith62243a32022-04-08 13:42:04 +0000230 }
Kousik Kumarc8818332023-01-16 16:33:05 +0000231
232 // If a config file does not exist, wait for the config file to be fetched. Otherwise
233 // fetch the config file in the background and return immediately.
234 if !configExists {
235 defer cancel()
236 return fetchCfg()
237 }
238
239 go func() {
240 defer cancel()
241 if err := fetchCfg(); err != nil {
242 ctx.Verbosef("Failed to fetch config file %v: %v\n", configName, err)
243 }
244 }()
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500245 return nil
246}
247
MarkDacek7901e582023-01-09 19:48:01 +0000248func loadEnvConfig(ctx Context, config *configImpl, bc string) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500249 if bc == "" {
250 return nil
251 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500252
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500253 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500254 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500255 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500256 envConfigDir,
257 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500258 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500259 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
260 envVarsJSON, err := ioutil.ReadFile(cfgFile)
261 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500262 continue
263 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500264 ctx.Verbosef("Loading config file %v\n", cfgFile)
265 var envVars map[string]map[string]string
266 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
267 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
268 continue
269 }
270 for k, v := range envVars["env"] {
271 if os.Getenv(k) != "" {
272 continue
273 }
274 config.environ.Set(k, v)
275 }
276 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
277 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500278 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500279
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500280 return nil
281}
282
Chris Parsonsb6e96902022-10-31 20:08:45 -0400283func defaultBazelProdMode(cfg *configImpl) bool {
MarkDacekd06db5d2022-11-29 00:47:59 +0000284 // Environment flag to disable Bazel for users which experience
Chris Parsonsb6e96902022-10-31 20:08:45 -0400285 // broken bazel-handled builds, or significant performance regressions.
286 if cfg.IsBazelMixedBuildForceDisabled() {
287 return false
288 }
289 // Darwin-host builds are currently untested with Bazel.
290 if runtime.GOOS == "darwin" {
291 return false
292 }
Chris Parsons035e03a2022-11-01 14:25:45 -0400293 return true
Chris Parsonsb6e96902022-10-31 20:08:45 -0400294}
295
MarkDacek6614d9c2022-12-07 21:57:38 +0000296func UploadOnlyConfig(ctx Context, _ ...string) Config {
297 ret := &configImpl{
298 environ: OsEnvironment(),
299 sandboxConfig: &SandboxConfig{},
300 }
MarkDacek7901e582023-01-09 19:48:01 +0000301 srcDir := absPath(ctx, ".")
302 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
303 if err := loadEnvConfig(ctx, ret, bc); err != nil {
304 ctx.Fatalln("Failed to parse env config files: %v", err)
305 }
306 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
MarkDacek6614d9c2022-12-07 21:57:38 +0000307 return Config{ret}
308}
309
Dan Willemsen1e704462016-08-21 15:17:17 -0700310func NewConfig(ctx Context, args ...string) Config {
311 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000312 environ: OsEnvironment(),
313 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700314 }
315
Patrice Arruda90109172020-07-28 18:07:27 +0000316 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700317 ret.parallel = runtime.NumCPU() + 2
318 ret.keepGoing = 1
319
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800320 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700321 ret.parseArgs(ctx, args)
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800322 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700323 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
324 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
325 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800326 outDir := "out"
327 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
328 if wd, err := os.Getwd(); err != nil {
329 ctx.Fatalln("Failed to get working directory:", err)
330 } else {
331 outDir = filepath.Join(baseDir, filepath.Base(wd))
332 }
333 }
334 ret.environ.Set("OUT_DIR", outDir)
335 }
336
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500337 // loadEnvConfig needs to know what the OUT_DIR is, so it should
338 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000339 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
340
341 if bc != "" {
342 if err := fetchEnvConfig(ctx, ret, bc); err != nil {
343 ctx.Verbosef("Failed to fetch config file: %v\n", err)
Kousik Kumarc8818332023-01-16 16:33:05 +0000344 }
345 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000346 ctx.Fatalln("Failed to parse env config files: %v", err)
347 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500348 }
349
Dan Willemsen2d31a442018-10-20 21:33:41 -0700350 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
351 ret.distDir = filepath.Clean(distDir)
352 } else {
353 ret.distDir = filepath.Join(ret.OutDir(), "dist")
354 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700355
Spandan Das05063612021-06-25 01:39:04 +0000356 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
357 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
358 }
359
Dan Willemsen1e704462016-08-21 15:17:17 -0700360 ret.environ.Unset(
361 // We're already using it
362 "USE_SOONG_UI",
363
364 // We should never use GOROOT/GOPATH from the shell environment
365 "GOROOT",
366 "GOPATH",
367
368 // These should only come from Soong, not the environment.
369 "CLANG",
370 "CLANG_CXX",
371 "CCC_CC",
372 "CCC_CXX",
373
374 // Used by the goma compiler wrapper, but should only be set by
375 // gomacc
376 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800377
378 // We handle this above
379 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700380
Dan Willemsen2d31a442018-10-20 21:33:41 -0700381 // This is handled above too, and set for individual commands later
382 "DIST_DIR",
383
Dan Willemsen68a09852017-04-18 13:56:57 -0700384 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000385 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700386 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700387 "DISPLAY",
388 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000389 "JAVAC",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700390 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700391 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700392
393 // Drop make flags
394 "MAKEFLAGS",
395 "MAKELEVEL",
396 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700397
398 // Set in envsetup.sh, reset in makefiles
399 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700400
401 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
402 "ANDROID_BUILD_TOP",
403 "ANDROID_HOST_OUT",
404 "ANDROID_PRODUCT_OUT",
405 "ANDROID_HOST_OUT_TESTCASES",
406 "ANDROID_TARGET_OUT_TESTCASES",
407 "ANDROID_TOOLCHAIN",
408 "ANDROID_TOOLCHAIN_2ND_ARCH",
409 "ANDROID_DEV_SCRIPTS",
410 "ANDROID_EMULATOR_PREBUILTS",
411 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700412 )
413
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400414 if ret.UseGoma() || ret.ForceUseGoma() {
415 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
416 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400417 }
418
Dan Willemsen1e704462016-08-21 15:17:17 -0700419 // Tell python not to spam the source tree with .pyc files.
420 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
421
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400422 tmpDir := absPath(ctx, ret.TempDir())
423 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800424
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700425 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
426 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
427 "llvm-binutils-stable/llvm-symbolizer")
428 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
429
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800430 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700431 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800432
Yu Liu6e13b402021-07-27 14:29:06 -0700433 srcDir := absPath(ctx, ".")
434 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700435 ctx.Println("You are building in a directory whose absolute path contains a space character:")
436 ctx.Println()
437 ctx.Printf("%q\n", srcDir)
438 ctx.Println()
439 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700440 }
441
Yu Liu6e13b402021-07-27 14:29:06 -0700442 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
443
Dan Willemsendb8457c2017-05-12 16:38:17 -0700444 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700445 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
446 ctx.Println()
447 ctx.Printf("%q\n", outDir)
448 ctx.Println()
449 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700450 }
451
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000452 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700453 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
454 ctx.Println()
455 ctx.Printf("%q\n", distDir)
456 ctx.Println()
457 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700458 }
459
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700460 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000461 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
462 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100463 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800464 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700465 javaHome := func() string {
466 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
467 return override
468 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000469 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
470 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 +0100471 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000472 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
473 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
474 }
475 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700476 }()
477 absJavaHome := absPath(ctx, javaHome)
478
Dan Willemsened869522018-01-08 14:58:46 -0800479 ret.configureLocale(ctx)
480
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700481 newPath := []string{filepath.Join(absJavaHome, "bin")}
482 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
483 newPath = append(newPath, path)
484 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100485
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700486 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
487 ret.environ.Set("JAVA_HOME", absJavaHome)
488 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000489 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
490 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100491 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700492 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
493
LaMont Jones52a72432023-03-09 18:19:35 +0000494 if ret.MultitreeBuild() {
495 ret.environ.Set("MULTITREE_BUILD", "true")
496 }
497
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800498 outDir := ret.OutDir()
499 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800500 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800501 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800502 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800503 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800504 }
Colin Cross28f527c2019-11-26 16:19:04 -0800505
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800506 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
507
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400508 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400509 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400510 ret.environ.Set(k, v)
511 }
512 }
513
Patrice Arruda83842d72020-12-08 19:42:08 +0000514 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800515 if err := os.RemoveAll(bpd); err != nil {
516 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
517 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000518
Patrice Arruda96850362020-08-11 20:41:11 +0000519 c := Config{ret}
520 storeConfigMetrics(ctx, c)
521 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700522}
523
Patrice Arruda13848222019-04-22 17:12:02 -0700524// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
525// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700526func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
527 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700528}
529
Patrice Arruda96850362020-08-11 20:41:11 +0000530// storeConfigMetrics selects a set of configuration information and store in
531// the metrics system for further analysis.
532func storeConfigMetrics(ctx Context, config Config) {
533 if ctx.Metrics == nil {
534 return
535 }
536
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400537 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000538
539 s := &smpb.SystemResourceInfo{
540 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
541 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
542 }
543 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000544}
545
Jeongik Cha8d63d562023-03-17 03:52:13 +0900546func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900547 switch s {
548 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900549 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900550 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900551 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900552 case EXTERNAL_FILE:
553 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900554 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900555 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900556 }
557}
558
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400559func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700560 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400561 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
562 UseGoma: proto.Bool(config.UseGoma()),
563 UseRbe: proto.Bool(config.UseRBE()),
564 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
565 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900566 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400567 }
Yu Liue737a992021-10-04 13:21:41 -0700568 c.Targets = append(c.Targets, config.arguments...)
569
570 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400571}
572
Patrice Arruda13848222019-04-22 17:12:02 -0700573// getConfigArgs processes the command arguments based on the build action and creates a set of new
574// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700575func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700576 // The next block of code verifies that the current directory is the root directory of the source
577 // tree. It then finds the relative path of dir based on the root directory of the source tree
578 // and verify that dir is inside of the source tree.
579 checkTopDir(ctx)
580 topDir, err := os.Getwd()
581 if err != nil {
582 ctx.Fatalf("Error retrieving top directory: %v", err)
583 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700584 dir, err = filepath.EvalSymlinks(dir)
585 if err != nil {
586 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
587 }
Patrice Arruda13848222019-04-22 17:12:02 -0700588 dir, err = filepath.Abs(dir)
589 if err != nil {
590 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
591 }
592 relDir, err := filepath.Rel(topDir, dir)
593 if err != nil {
594 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
595 }
596 // If there are ".." in the path, it's not in the source tree.
597 if strings.Contains(relDir, "..") {
598 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
599 }
600
601 configArgs := args[:]
602
603 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
604 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
605 targetNamePrefix := "MODULES-IN-"
606 if inList("GET-INSTALL-PATH", configArgs) {
607 targetNamePrefix = "GET-INSTALL-PATH-IN-"
608 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
609 }
610
Patrice Arruda13848222019-04-22 17:12:02 -0700611 var targets []string
612
613 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700614 case BUILD_MODULES:
615 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700616 case BUILD_MODULES_IN_A_DIRECTORY:
617 // If dir is the root source tree, all the modules are built of the source tree are built so
618 // no need to find the build file.
619 if topDir == dir {
620 break
621 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700622
Patrice Arruda13848222019-04-22 17:12:02 -0700623 buildFile := findBuildFile(ctx, relDir)
624 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700625 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700626 }
Patrice Arruda13848222019-04-22 17:12:02 -0700627 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
628 case BUILD_MODULES_IN_DIRECTORIES:
629 newConfigArgs, dirs := splitArgs(configArgs)
630 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700631 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700632 }
633
634 // Tidy only override all other specified targets.
635 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
636 if tidyOnly == "true" || tidyOnly == "1" {
637 configArgs = append(configArgs, "tidy_only")
638 } else {
639 configArgs = append(configArgs, targets...)
640 }
641
642 return configArgs
643}
644
645// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
646func convertToTarget(dir string, targetNamePrefix string) string {
647 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
648}
649
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700650// hasBuildFile returns true if dir contains an Android build file.
651func hasBuildFile(ctx Context, dir string) bool {
652 for _, buildFile := range buildFiles {
653 _, err := os.Stat(filepath.Join(dir, buildFile))
654 if err == nil {
655 return true
656 }
657 if !os.IsNotExist(err) {
658 ctx.Fatalf("Error retrieving the build file stats: %v", err)
659 }
660 }
661 return false
662}
663
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700664// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
665// in the current and any sub directory of dir. If a build file is not found, traverse the path
666// up by one directory and repeat again until either a build file is found or reached to the root
667// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
668// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700669func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700670 // If the string is empty or ".", assume it is top directory of the source tree.
671 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700672 return ""
673 }
674
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700675 found := false
676 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
677 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
678 if err != nil {
679 return err
680 }
681 if found {
682 return filepath.SkipDir
683 }
684 if info.IsDir() {
685 return nil
686 }
687 for _, buildFile := range buildFiles {
688 if info.Name() == buildFile {
689 found = true
690 return filepath.SkipDir
691 }
692 }
693 return nil
694 })
695 if err != nil {
696 ctx.Fatalf("Error finding Android build file: %v", err)
697 }
698
699 if found {
700 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700701 }
702 }
703
704 return ""
705}
706
707// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
708func splitArgs(args []string) (newArgs []string, dirs []string) {
709 specialArgs := map[string]bool{
710 "showcommands": true,
711 "snod": true,
712 "dist": true,
713 "checkbuild": true,
714 }
715
716 newArgs = []string{}
717 dirs = []string{}
718
719 for _, arg := range args {
720 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
721 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
722 newArgs = append(newArgs, arg)
723 continue
724 }
725
726 if _, ok := specialArgs[arg]; ok {
727 newArgs = append(newArgs, arg)
728 continue
729 }
730
731 dirs = append(dirs, arg)
732 }
733
734 return newArgs, dirs
735}
736
737// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
738// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
739// source root tree where the build action command was invoked. Each directory is validated if the
740// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700741func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700742 for _, dir := range dirs {
743 // The directory may have specified specific modules to build. ":" is the separator to separate
744 // the directory and the list of modules.
745 s := strings.Split(dir, ":")
746 l := len(s)
747 if l > 2 { // more than one ":" was specified.
748 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
749 }
750
751 dir = filepath.Join(relDir, s[0])
752 if _, err := os.Stat(dir); err != nil {
753 ctx.Fatalf("couldn't find directory %s", dir)
754 }
755
756 // Verify that if there are any targets specified after ":". Each target is separated by ",".
757 var newTargets []string
758 if l == 2 && s[1] != "" {
759 newTargets = strings.Split(s[1], ",")
760 if inList("", newTargets) {
761 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
762 }
763 }
764
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700765 // If there are specified targets to build in dir, an android build file must exist for the one
766 // shot build. For the non-targets case, find the appropriate build file and build all the
767 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700768 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700769 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700770 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
771 }
772 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700773 buildFile := findBuildFile(ctx, dir)
774 if buildFile == "" {
775 ctx.Fatalf("Build file not found for %s directory", dir)
776 }
777 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700778 }
779
Patrice Arruda13848222019-04-22 17:12:02 -0700780 targets = append(targets, newTargets...)
781 }
782
Dan Willemsence41e942019-07-29 23:39:30 -0700783 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700784}
785
Dan Willemsen9b587492017-07-10 22:13:00 -0700786func (c *configImpl) parseArgs(ctx Context, args []string) {
787 for i := 0; i < len(args); i++ {
788 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100789 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700790 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200791 } else if arg == "--empty-ninja-file" {
792 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100793 } else if arg == "--skip-ninja" {
794 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700795 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700796 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
797 // but it does run a Kati ninja file if the .kati_enabled marker file was created
798 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000799 c.skipConfig = true
800 c.skipKati = true
801 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100802 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000803 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100804 } else if arg == "--soong-only" {
805 c.skipKati = true
806 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200807 } else if arg == "--config-only" {
808 c.skipKati = true
809 c.skipKatiNinja = true
810 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700811 } else if arg == "--skip-config" {
812 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700813 } else if arg == "--skip-soong-tests" {
814 c.skipSoongTests = true
MarkDacekd0e7cd32022-12-02 22:22:40 +0000815 } else if arg == "--skip-metrics-upload" {
816 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500817 } else if arg == "--mk-metrics" {
818 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000819 } else if arg == "--multitree-build" {
820 c.multitreeBuild = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400821 } else if arg == "--bazel-mode" {
822 c.bazelProdMode = true
823 } else if arg == "--bazel-mode-dev" {
824 c.bazelDevMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000825 } else if arg == "--bazel-mode-staging" {
826 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000827 } else if arg == "--search-api-dir" {
828 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900829 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
830 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
831 if source == "ninja_log" {
832 c.ninjaWeightListSource = NINJA_LOG
833 } else if source == "evenly_distributed" {
834 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
835 } else if source == "not_used" {
836 c.ninjaWeightListSource = NOT_USED
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900837 } else if strings.HasPrefix(source, "file,") {
838 c.ninjaWeightListSource = EXTERNAL_FILE
839 filePath := strings.TrimPrefix(source, "file,")
840 err := validateNinjaWeightList(filePath)
841 if err != nil {
842 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
843 }
844 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
845 if err != nil {
846 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
847 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900848 } else {
849 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
850 }
MarkDacekb96561e2022-12-02 04:34:43 +0000851 } else if strings.HasPrefix(arg, "--build-command=") {
852 buildCmd := strings.TrimPrefix(arg, "--build-command=")
853 // remove quotations
854 buildCmd = strings.TrimPrefix(buildCmd, "\"")
855 buildCmd = strings.TrimSuffix(buildCmd, "\"")
856 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000857 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
858 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
MarkDacek6614d9c2022-12-07 21:57:38 +0000859 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
860 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
861 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
862 if err == nil {
863 c.buildStartedTime = val
864 } else {
865 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
866 }
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700867 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700868 parseArgNum := func(def int) int {
869 if len(arg) > 2 {
870 p, err := strconv.ParseUint(arg[2:], 10, 31)
871 if err != nil {
872 ctx.Fatalf("Failed to parse %q: %v", arg, err)
873 }
874 return int(p)
875 } else if i+1 < len(args) {
876 p, err := strconv.ParseUint(args[i+1], 10, 31)
877 if err == nil {
878 i++
879 return int(p)
880 }
881 }
882 return def
883 }
884
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700885 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700886 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700887 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700888 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700889 } else {
890 ctx.Fatalln("Unknown option:", arg)
891 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700892 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700893 if k == "OUT_DIR" {
894 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
895 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700896 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700897 } else if arg == "dist" {
898 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200899 } else if arg == "json-module-graph" {
900 c.jsonModuleGraph = true
901 } else if arg == "bp2build" {
902 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000903 } else if arg == "api_bp2build" {
904 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200905 } else if arg == "queryview" {
906 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200907 } else if arg == "soong_docs" {
908 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700909 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700910 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800911 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700912 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700913 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700914 }
915 }
Chris Parsonsb6e96902022-10-31 20:08:45 -0400916 if (!c.bazelProdMode) && (!c.bazelDevMode) && (!c.bazelStagingMode) {
917 c.bazelProdMode = defaultBazelProdMode(c)
918 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700919}
920
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900921func validateNinjaWeightList(weightListFilePath string) (err error) {
922 data, err := os.ReadFile(weightListFilePath)
923 if err != nil {
924 return
925 }
926 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
927 for _, line := range lines {
928 fields := strings.Split(line, ",")
929 if len(fields) != 2 {
930 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
931 }
932 _, err = strconv.Atoi(fields[1])
933 if err != nil {
934 return
935 }
936 }
937 return
938}
939
Dan Willemsened869522018-01-08 14:58:46 -0800940func (c *configImpl) configureLocale(ctx Context) {
941 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
942 output, err := cmd.Output()
943
944 var locales []string
945 if err == nil {
946 locales = strings.Split(string(output), "\n")
947 } else {
948 // If we're unable to list the locales, let's assume en_US.UTF-8
949 locales = []string{"en_US.UTF-8"}
950 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
951 }
952
953 // gettext uses LANGUAGE, which is passed directly through
954
955 // For LANG and LC_*, only preserve the evaluated version of
956 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800957 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800958 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800959 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800960 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800961 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800962 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800963 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800964 }
965
966 c.environ.UnsetWithPrefix("LC_")
967
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800968 if userLang != "" {
969 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800970 }
971
972 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
973 // for others)
974 if inList("C.UTF-8", locales) {
975 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500976 } else if inList("C.utf8", locales) {
977 // These normalize to the same thing
978 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800979 } else if inList("en_US.UTF-8", locales) {
980 c.environ.Set("LANG", "en_US.UTF-8")
981 } else if inList("en_US.utf8", locales) {
982 // These normalize to the same thing
983 c.environ.Set("LANG", "en_US.UTF-8")
984 } else {
985 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
986 }
987}
988
Dan Willemsen1e704462016-08-21 15:17:17 -0700989func (c *configImpl) Environment() *Environment {
990 return c.environ
991}
992
993func (c *configImpl) Arguments() []string {
994 return c.arguments
995}
996
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200997func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200998 if len(c.Arguments()) > 0 {
999 // Explicit targets requested that are not special targets like b2pbuild
1000 // or the JSON module graph
1001 return true
1002 }
1003
Spandan Das5af0bd32022-09-28 20:43:08 +00001004 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001005 // Command line was empty, the default Ninja target is built
1006 return true
1007 }
1008
Liz Kammer88677422021-12-15 15:03:19 -05001009 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
1010 if c.Dist() && !c.Bp2Build() {
1011 return true
1012 }
1013
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001014 // build.ninja doesn't need to be generated
1015 return false
1016}
1017
Dan Willemsen1e704462016-08-21 15:17:17 -07001018func (c *configImpl) OutDir() string {
1019 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -07001020 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -07001021 }
1022 return "out"
1023}
1024
Dan Willemsen8a073a82017-02-04 17:30:44 -08001025func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -04001026 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001027}
1028
1029func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -07001030 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -08001031}
1032
Dan Willemsen1e704462016-08-21 15:17:17 -07001033func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001034 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001035 return c.arguments
1036 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001037 return c.ninjaArgs
1038}
1039
Jingwen Chen7c6089a2020-11-02 02:56:20 -05001040func (c *configImpl) BazelOutDir() string {
1041 return filepath.Join(c.OutDir(), "bazel")
1042}
1043
Liz Kammer2af5ea82022-11-11 14:21:03 -05001044func (c *configImpl) bazelOutputBase() string {
1045 return filepath.Join(c.BazelOutDir(), "output")
1046}
1047
Dan Willemsen1e704462016-08-21 15:17:17 -07001048func (c *configImpl) SoongOutDir() string {
1049 return filepath.Join(c.OutDir(), "soong")
1050}
1051
Spandan Das394aa322022-11-03 17:02:10 +00001052func (c *configImpl) ApiSurfacesOutDir() string {
1053 return filepath.Join(c.OutDir(), "api_surfaces")
1054}
1055
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001056func (c *configImpl) PrebuiltOS() string {
1057 switch runtime.GOOS {
1058 case "linux":
1059 return "linux-x86"
1060 case "darwin":
1061 return "darwin-x86"
1062 default:
1063 panic("Unknown GOOS")
1064 }
1065}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001066
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001067func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001068 if c.SkipKatiNinja() {
1069 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1070 } else {
1071 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1072 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001073}
1074
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001075func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001076 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001077}
1078
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001079func (c *configImpl) UsedEnvFile(tag string) string {
1080 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1081}
1082
Lukacs T. Berkic541cd22022-10-26 07:26:50 +00001083func (c *configImpl) Bp2BuildFilesMarkerFile() string {
1084 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
1085}
1086
1087func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001088 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +02001089}
1090
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001091func (c *configImpl) SoongDocsHtml() string {
1092 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1093}
1094
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001095func (c *configImpl) QueryviewMarkerFile() string {
1096 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1097}
1098
Spandan Das5af0bd32022-09-28 20:43:08 +00001099func (c *configImpl) ApiBp2buildMarkerFile() string {
1100 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
1101}
1102
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001103func (c *configImpl) ModuleGraphFile() string {
1104 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1105}
1106
kgui67007242022-01-25 13:50:25 +08001107func (c *configImpl) ModuleActionsFile() string {
1108 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1109}
1110
Jeff Gastonefc1b412017-03-29 17:29:06 -07001111func (c *configImpl) TempDir() string {
1112 return shared.TempDirForOutDir(c.SoongOutDir())
1113}
1114
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001115func (c *configImpl) FileListDir() string {
1116 return filepath.Join(c.OutDir(), ".module_paths")
1117}
1118
Dan Willemsen1e704462016-08-21 15:17:17 -07001119func (c *configImpl) KatiSuffix() string {
1120 if c.katiSuffix != "" {
1121 return c.katiSuffix
1122 }
1123 panic("SetKatiSuffix has not been called")
1124}
1125
Colin Cross37193492017-11-16 17:55:00 -08001126// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1127// user is interested in additional checks at the expense of build time.
1128func (c *configImpl) Checkbuild() bool {
1129 return c.checkbuild
1130}
1131
Dan Willemsen8a073a82017-02-04 17:30:44 -08001132func (c *configImpl) Dist() bool {
1133 return c.dist
1134}
1135
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001136func (c *configImpl) JsonModuleGraph() bool {
1137 return c.jsonModuleGraph
1138}
1139
1140func (c *configImpl) Bp2Build() bool {
1141 return c.bp2build
1142}
1143
Spandan Das5af0bd32022-09-28 20:43:08 +00001144func (c *configImpl) ApiBp2build() bool {
1145 return c.apiBp2build
1146}
1147
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001148func (c *configImpl) Queryview() bool {
1149 return c.queryview
1150}
1151
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001152func (c *configImpl) SoongDocs() bool {
1153 return c.soongDocs
1154}
1155
Dan Willemsen1e704462016-08-21 15:17:17 -07001156func (c *configImpl) IsVerbose() bool {
1157 return c.verbose
1158}
1159
LaMont Jones52a72432023-03-09 18:19:35 +00001160func (c *configImpl) MultitreeBuild() bool {
1161 return c.multitreeBuild
1162}
1163
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001164func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1165 return c.ninjaWeightListSource
1166}
1167
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001168func (c *configImpl) SkipKati() bool {
1169 return c.skipKati
1170}
1171
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001172func (c *configImpl) SkipKatiNinja() bool {
1173 return c.skipKatiNinja
1174}
1175
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001176func (c *configImpl) SkipSoong() bool {
1177 return c.skipSoong
1178}
1179
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001180func (c *configImpl) SkipNinja() bool {
1181 return c.skipNinja
1182}
1183
Anton Hansson5a7861a2021-06-04 10:09:01 +01001184func (c *configImpl) SetSkipNinja(v bool) {
1185 c.skipNinja = v
1186}
1187
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001188func (c *configImpl) SkipConfig() bool {
1189 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001190}
1191
Dan Willemsen1e704462016-08-21 15:17:17 -07001192func (c *configImpl) TargetProduct() string {
1193 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1194 return v
1195 }
1196 panic("TARGET_PRODUCT is not defined")
1197}
1198
Dan Willemsen02781d52017-05-12 19:28:13 -07001199func (c *configImpl) TargetDevice() string {
1200 return c.targetDevice
1201}
1202
1203func (c *configImpl) SetTargetDevice(device string) {
1204 c.targetDevice = device
1205}
1206
1207func (c *configImpl) TargetBuildVariant() string {
1208 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1209 return v
1210 }
1211 panic("TARGET_BUILD_VARIANT is not defined")
1212}
1213
Dan Willemsen1e704462016-08-21 15:17:17 -07001214func (c *configImpl) KatiArgs() []string {
1215 return c.katiArgs
1216}
1217
1218func (c *configImpl) Parallel() int {
1219 return c.parallel
1220}
1221
Spandan Dasc5763832022-11-08 18:42:16 +00001222func (c *configImpl) GetIncludeTags() []string {
1223 return c.includeTags
1224}
1225
1226func (c *configImpl) SetIncludeTags(i []string) {
1227 c.includeTags = i
1228}
1229
MarkDacek6614d9c2022-12-07 21:57:38 +00001230func (c *configImpl) GetLogsPrefix() string {
1231 return c.logsPrefix
1232}
1233
1234func (c *configImpl) SetLogsPrefix(prefix string) {
1235 c.logsPrefix = prefix
1236}
1237
Colin Cross8b8bec32019-11-15 13:18:43 -08001238func (c *configImpl) HighmemParallel() int {
1239 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1240 return i
1241 }
1242
1243 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1244 parallel := c.Parallel()
1245 if c.UseRemoteBuild() {
1246 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1247 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1248 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1249 // Return 1/16th of the size of the local pool, rounding up.
1250 return (parallel + 15) / 16
1251 } else if c.totalRAM == 0 {
1252 // Couldn't detect the total RAM, don't restrict highmem processes.
1253 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001254 } else if c.totalRAM <= 16*1024*1024*1024 {
1255 // Less than 16GB of ram, restrict to 1 highmem processes
1256 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001257 } else if c.totalRAM <= 32*1024*1024*1024 {
1258 // Less than 32GB of ram, restrict to 2 highmem processes
1259 return 2
1260 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1261 // If less than 8GB total RAM per process, reduce the number of highmem processes
1262 return p
1263 }
1264 // No restriction on highmem processes
1265 return parallel
1266}
1267
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001268func (c *configImpl) TotalRAM() uint64 {
1269 return c.totalRAM
1270}
1271
Kousik Kumarec478642020-09-21 13:39:24 -04001272// ForceUseGoma determines whether we should override Goma deprecation
1273// and use Goma for the current build or not.
1274func (c *configImpl) ForceUseGoma() bool {
1275 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1276 v = strings.TrimSpace(v)
1277 if v != "" && v != "false" {
1278 return true
1279 }
1280 }
1281 return false
1282}
1283
Dan Willemsen1e704462016-08-21 15:17:17 -07001284func (c *configImpl) UseGoma() bool {
1285 if v, ok := c.environ.Get("USE_GOMA"); ok {
1286 v = strings.TrimSpace(v)
1287 if v != "" && v != "false" {
1288 return true
1289 }
1290 }
1291 return false
1292}
1293
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001294func (c *configImpl) StartGoma() bool {
1295 if !c.UseGoma() {
1296 return false
1297 }
1298
1299 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1300 v = strings.TrimSpace(v)
1301 if v != "" && v != "false" {
1302 return false
1303 }
1304 }
1305 return true
1306}
1307
Ramy Medhatbbf25672019-07-17 12:30:04 +00001308func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001309 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001310 v = strings.TrimSpace(v)
1311 if v != "" && v != "false" {
1312 return true
1313 }
1314 }
1315 return false
1316}
1317
Chris Parsonsef615e52022-08-18 22:04:11 -04001318func (c *configImpl) BazelBuildEnabled() bool {
MarkDacekb78465d2022-10-18 20:10:16 +00001319 return c.bazelProdMode || c.bazelDevMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001320}
1321
Ramy Medhatbbf25672019-07-17 12:30:04 +00001322func (c *configImpl) StartRBE() bool {
1323 if !c.UseRBE() {
1324 return false
1325 }
1326
1327 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1328 v = strings.TrimSpace(v)
1329 if v != "" && v != "false" {
1330 return false
1331 }
1332 }
1333 return true
1334}
1335
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001336func (c *configImpl) rbeProxyLogsDir() string {
1337 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001338 if v, ok := c.environ.Get(f); ok {
1339 return v
1340 }
1341 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001342 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1343 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001344}
1345
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001346func (c *configImpl) shouldCleanupRBELogsDir() bool {
1347 // Perform a log directory cleanup only when the log directory
1348 // is auto created by the build rather than user-specified.
1349 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1350 if _, ok := c.environ.Get(f); ok {
1351 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001352 }
1353 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001354 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001355}
1356
1357func (c *configImpl) rbeExecRoot() string {
1358 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1359 if v, ok := c.environ.Get(f); ok {
1360 return v
1361 }
1362 }
1363 wd, err := os.Getwd()
1364 if err != nil {
1365 return ""
1366 }
1367 return wd
1368}
1369
1370func (c *configImpl) rbeDir() string {
1371 if v, ok := c.environ.Get("RBE_DIR"); ok {
1372 return v
1373 }
1374 return "prebuilts/remoteexecution-client/live/"
1375}
1376
1377func (c *configImpl) rbeReproxy() string {
1378 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1379 if v, ok := c.environ.Get(f); ok {
1380 return v
1381 }
1382 }
1383 return filepath.Join(c.rbeDir(), "reproxy")
1384}
1385
1386func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001387 credFlags := []string{
1388 "use_application_default_credentials",
1389 "use_gce_credentials",
1390 "credential_file",
1391 "use_google_prod_creds",
1392 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001393 for _, cf := range credFlags {
1394 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1395 if v, ok := c.environ.Get(f); ok {
1396 v = strings.TrimSpace(v)
1397 if v != "" && v != "false" && v != "0" {
1398 return "RBE_" + cf, v
1399 }
1400 }
1401 }
1402 }
1403 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001404}
1405
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001406func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1407 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1408 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1409
1410 name := filepath.Join(dir, base)
1411 if len(name) < maxNameLen {
1412 return name, nil
1413 }
1414
1415 name = filepath.Join("/tmp", base)
1416 if len(name) < maxNameLen {
1417 return name, nil
1418 }
1419
1420 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1421}
1422
Kousik Kumar7bc78192022-04-27 14:52:56 -04001423// IsGooglerEnvironment returns true if the current build is running
1424// on a Google developer machine and false otherwise.
1425func (c *configImpl) IsGooglerEnvironment() bool {
1426 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1427 if v, ok := c.environ.Get(cf); ok {
1428 return v == "googler"
1429 }
1430 return false
1431}
1432
1433// GoogleProdCredsExist determine whether credentials exist on the
1434// Googler machine to use remote execution.
1435func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001436 if googleProdCredsExistCache {
1437 return googleProdCredsExistCache
1438 }
Kousik Kumar7bc78192022-04-27 14:52:56 -04001439 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1440 return false
1441 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001442 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001443 return true
1444}
1445
1446// UseRemoteBuild indicates whether to use a remote build acceleration system
1447// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001448func (c *configImpl) UseRemoteBuild() bool {
1449 return c.UseGoma() || c.UseRBE()
1450}
1451
Kousik Kumar7bc78192022-04-27 14:52:56 -04001452// StubbyExists checks whether the stubby binary exists on the machine running
1453// the build.
1454func (c *configImpl) StubbyExists() bool {
1455 if _, err := exec.LookPath("stubby"); err != nil {
1456 return false
1457 }
1458 return true
1459}
1460
Dan Willemsen1e704462016-08-21 15:17:17 -07001461// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001462// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001463// still limited by Parallel()
1464func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001465 if !c.UseRemoteBuild() {
1466 return 0
1467 }
1468 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1469 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001470 }
1471 return 500
1472}
1473
1474func (c *configImpl) SetKatiArgs(args []string) {
1475 c.katiArgs = args
1476}
1477
1478func (c *configImpl) SetNinjaArgs(args []string) {
1479 c.ninjaArgs = args
1480}
1481
1482func (c *configImpl) SetKatiSuffix(suffix string) {
1483 c.katiSuffix = suffix
1484}
1485
Dan Willemsene0879fc2017-08-04 15:06:27 -07001486func (c *configImpl) LastKatiSuffixFile() string {
1487 return filepath.Join(c.OutDir(), "last_kati_suffix")
1488}
1489
1490func (c *configImpl) HasKatiSuffix() bool {
1491 return c.katiSuffix != ""
1492}
1493
Dan Willemsen1e704462016-08-21 15:17:17 -07001494func (c *configImpl) KatiEnvFile() string {
1495 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1496}
1497
Dan Willemsen29971232018-09-26 14:58:30 -07001498func (c *configImpl) KatiBuildNinjaFile() string {
1499 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001500}
1501
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001502func (c *configImpl) KatiPackageNinjaFile() string {
1503 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1504}
1505
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001506func (c *configImpl) SoongVarsFile() string {
1507 return filepath.Join(c.SoongOutDir(), "soong.variables")
1508}
1509
Dan Willemsen1e704462016-08-21 15:17:17 -07001510func (c *configImpl) SoongNinjaFile() string {
1511 return filepath.Join(c.SoongOutDir(), "build.ninja")
1512}
1513
1514func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001515 if c.katiSuffix == "" {
1516 return filepath.Join(c.OutDir(), "combined.ninja")
1517 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001518 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1519}
1520
1521func (c *configImpl) SoongAndroidMk() string {
1522 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1523}
1524
1525func (c *configImpl) SoongMakeVarsMk() string {
1526 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1527}
1528
Dan Willemsenf052f782017-05-18 15:29:04 -07001529func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001530 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001531}
1532
Dan Willemsen02781d52017-05-12 19:28:13 -07001533func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001534 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1535}
1536
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001537func (c *configImpl) KatiPackageMkDir() string {
1538 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1539}
1540
Dan Willemsenf052f782017-05-18 15:29:04 -07001541func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001542 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001543}
1544
1545func (c *configImpl) HostOut() string {
1546 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1547}
1548
1549// This probably needs to be multi-valued, so not exporting it for now
1550func (c *configImpl) hostCrossOut() string {
1551 if runtime.GOOS == "linux" {
1552 return filepath.Join(c.hostOutRoot(), "windows-x86")
1553 } else {
1554 return ""
1555 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001556}
1557
Dan Willemsen1e704462016-08-21 15:17:17 -07001558func (c *configImpl) HostPrebuiltTag() string {
1559 if runtime.GOOS == "linux" {
1560 return "linux-x86"
1561 } else if runtime.GOOS == "darwin" {
1562 return "darwin-x86"
1563 } else {
1564 panic("Unsupported OS")
1565 }
1566}
Dan Willemsenf173d592017-04-27 14:28:00 -07001567
Dan Willemsen8122bd52017-10-12 20:20:41 -07001568func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001569 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1570 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001571 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1572 if _, err := os.Stat(asan); err == nil {
1573 return asan
1574 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001575 }
1576 }
1577 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1578}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001579
1580func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1581 c.brokenDupRules = val
1582}
1583
1584func (c *configImpl) BuildBrokenDupRules() bool {
1585 return c.brokenDupRules
1586}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001587
Dan Willemsen25e6f092019-04-09 10:22:43 -07001588func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1589 c.brokenUsesNetwork = val
1590}
1591
1592func (c *configImpl) BuildBrokenUsesNetwork() bool {
1593 return c.brokenUsesNetwork
1594}
1595
Dan Willemsene3336352020-01-02 19:10:38 -08001596func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1597 c.brokenNinjaEnvVars = val
1598}
1599
1600func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1601 return c.brokenNinjaEnvVars
1602}
1603
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001604func (c *configImpl) SetTargetDeviceDir(dir string) {
1605 c.targetDeviceDir = dir
1606}
1607
1608func (c *configImpl) TargetDeviceDir() string {
1609 return c.targetDeviceDir
1610}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001611
Patrice Arruda219eef32020-06-01 17:29:30 +00001612func (c *configImpl) BuildDateTime() string {
1613 return c.buildDateTime
1614}
1615
1616func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001617 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001618}
Patrice Arruda83842d72020-12-08 19:42:08 +00001619
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001620// LogsDir returns the absolute path to the logs directory where build log and
1621// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001622// directory. If the argument dist is specified, the logs directory
1623// is <dist_dir>/logs.
1624func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001625 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001626 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001627 // 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 -05001628 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001629 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001630 absDir, err := filepath.Abs(dir)
1631 if err != nil {
1632 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1633 os.Exit(1)
1634 }
1635 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001636}
1637
1638// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1639// where the bazel profiles are located.
1640func (c *configImpl) BazelMetricsDir() string {
1641 return filepath.Join(c.LogsDir(), "bazel_metrics")
1642}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001643
Chris Parsons53f68ae2022-03-03 12:01:40 -05001644// MkFileMetrics returns the file path for make-related metrics.
1645func (c *configImpl) MkMetrics() string {
1646 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1647}
1648
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001649func (c *configImpl) SetEmptyNinjaFile(v bool) {
1650 c.emptyNinjaFile = v
1651}
1652
1653func (c *configImpl) EmptyNinjaFile() bool {
1654 return c.emptyNinjaFile
1655}
Yu Liu6e13b402021-07-27 14:29:06 -07001656
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001657func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1658 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1659}
1660
Chris Parsons9402ca82023-02-23 17:28:06 -05001661func (c *configImpl) IsPersistentBazelEnabled() bool {
1662 return c.Environment().IsEnvTrue("USE_PERSISTENT_BAZEL")
1663}
1664
MarkDacekd06db5d2022-11-29 00:47:59 +00001665func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1666 return c.bazelForceEnabledModules
1667}
1668
MarkDacekd0e7cd32022-12-02 22:22:40 +00001669func (c *configImpl) SkipMetricsUpload() bool {
1670 return c.skipMetricsUpload
1671}
1672
MarkDacek6614d9c2022-12-07 21:57:38 +00001673// Returns a Time object if one was passed via a command-line flag.
1674// Otherwise returns the passed default.
1675func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1676 if c.buildStartedTime == 0 {
1677 return defaultTime
1678 }
1679 return time.UnixMilli(c.buildStartedTime)
1680}
1681
Yu Liu6e13b402021-07-27 14:29:06 -07001682func GetMetricsUploader(topDir string, env *Environment) string {
1683 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1684 metricsUploader := filepath.Join(topDir, p)
1685 if _, err := os.Stat(metricsUploader); err == nil {
1686 return metricsUploader
1687 }
1688 }
1689
1690 return ""
1691}