blob: 8a77b081c7d4d229d05973aa1172b943ce696bae [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
135)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800136const srcDirFileCheck = "build/soong/root.bp"
137
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700138var buildFiles = []string{"Android.mk", "Android.bp"}
139
Patrice Arruda13848222019-04-22 17:12:02 -0700140type BuildAction uint
141
142const (
143 // Builds all of the modules and their dependencies of a specified directory, relative to the root
144 // directory of the source tree.
145 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
146
147 // Builds all of the modules and their dependencies of a list of specified directories. All specified
148 // directories are relative to the root directory of the source tree.
149 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700150
151 // Build a list of specified modules. If none was specified, simply build the whole source tree.
152 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700153)
154
155// checkTopDir validates that the current directory is at the root directory of the source tree.
156func checkTopDir(ctx Context) {
157 if _, err := os.Stat(srcDirFileCheck); err != nil {
158 if os.IsNotExist(err) {
159 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
160 }
161 ctx.Fatalln("Error verifying tree state:", err)
162 }
163}
164
Kousik Kumarc8818332023-01-16 16:33:05 +0000165// fetchEnvConfig optionally fetches a configuration file that can then subsequently be
166// loaded into Soong environment to control certain aspects of build behavior (e.g., enabling RBE).
167// If a configuration file already exists on disk, the fetch is run in the background
168// so as to NOT block the rest of the build execution.
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500169func fetchEnvConfig(ctx Context, config *configImpl, envConfigName string) error {
David Goldsmith62243a32022-04-08 13:42:04 +0000170 configName := envConfigName + "." + jsonSuffix
Kousik Kumarc75e1292022-07-07 02:20:51 +0000171 expConfigFetcher := &smpb.ExpConfigFetcher{Filename: &configName}
David Goldsmith62243a32022-04-08 13:42:04 +0000172 defer func() {
173 ctx.Metrics.ExpConfigFetcher(expConfigFetcher)
174 }()
Kousik Kumarc75e1292022-07-07 02:20:51 +0000175 if !config.GoogleProdCredsExist() {
176 status := smpb.ExpConfigFetcher_MISSING_GCERT
177 expConfigFetcher.Status = &status
178 return nil
179 }
David Goldsmith62243a32022-04-08 13:42:04 +0000180
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500181 s, err := os.Stat(configFetcher)
182 if err != nil {
183 if os.IsNotExist(err) {
184 return nil
185 }
186 return err
187 }
188 if s.Mode()&0111 == 0 {
David Goldsmith62243a32022-04-08 13:42:04 +0000189 status := smpb.ExpConfigFetcher_ERROR
190 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500191 return fmt.Errorf("configuration fetcher binary %v is not executable: %v", configFetcher, s.Mode())
192 }
193
Kousik Kumarc8818332023-01-16 16:33:05 +0000194 configExists := false
195 outConfigFilePath := filepath.Join(config.OutDir(), configName)
196 if _, err := os.Stat(outConfigFilePath); err == nil {
197 configExists = true
198 }
199
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500200 tCtx, cancel := context.WithTimeout(ctx, envConfigFetchTimeout)
David Goldsmith62243a32022-04-08 13:42:04 +0000201 fetchStart := time.Now()
202 cmd := exec.CommandContext(tCtx, configFetcher, "-output_config_dir", config.OutDir(),
203 "-output_config_name", configName)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500204 if err := cmd.Start(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000205 status := smpb.ExpConfigFetcher_ERROR
206 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500207 return err
208 }
209
Kousik Kumarc8818332023-01-16 16:33:05 +0000210 fetchCfg := func() error {
211 if err := cmd.Wait(); err != nil {
212 status := smpb.ExpConfigFetcher_ERROR
213 expConfigFetcher.Status = &status
214 return err
215 }
216 fetchEnd := time.Now()
217 expConfigFetcher.Micros = proto.Uint64(uint64(fetchEnd.Sub(fetchStart).Microseconds()))
218 expConfigFetcher.Filename = proto.String(outConfigFilePath)
219
220 if _, err := os.Stat(outConfigFilePath); err != nil {
221 status := smpb.ExpConfigFetcher_NO_CONFIG
222 expConfigFetcher.Status = &status
223 return err
224 }
David Goldsmith62243a32022-04-08 13:42:04 +0000225 status := smpb.ExpConfigFetcher_CONFIG
226 expConfigFetcher.Status = &status
Kousik Kumarc8818332023-01-16 16:33:05 +0000227 return nil
David Goldsmith62243a32022-04-08 13:42:04 +0000228 }
Kousik Kumarc8818332023-01-16 16:33:05 +0000229
230 // If a config file does not exist, wait for the config file to be fetched. Otherwise
231 // fetch the config file in the background and return immediately.
232 if !configExists {
233 defer cancel()
234 return fetchCfg()
235 }
236
237 go func() {
238 defer cancel()
239 if err := fetchCfg(); err != nil {
240 ctx.Verbosef("Failed to fetch config file %v: %v\n", configName, err)
241 }
242 }()
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500243 return nil
244}
245
MarkDacek7901e582023-01-09 19:48:01 +0000246func loadEnvConfig(ctx Context, config *configImpl, bc string) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500247 if bc == "" {
248 return nil
249 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500250
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500251 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500252 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500253 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500254 envConfigDir,
255 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500256 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500257 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
258 envVarsJSON, err := ioutil.ReadFile(cfgFile)
259 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500260 continue
261 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500262 ctx.Verbosef("Loading config file %v\n", cfgFile)
263 var envVars map[string]map[string]string
264 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
265 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
266 continue
267 }
268 for k, v := range envVars["env"] {
269 if os.Getenv(k) != "" {
270 continue
271 }
272 config.environ.Set(k, v)
273 }
274 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
275 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500276 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500277
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500278 return nil
279}
280
Chris Parsonsb6e96902022-10-31 20:08:45 -0400281func defaultBazelProdMode(cfg *configImpl) bool {
MarkDacekd06db5d2022-11-29 00:47:59 +0000282 // Environment flag to disable Bazel for users which experience
Chris Parsonsb6e96902022-10-31 20:08:45 -0400283 // broken bazel-handled builds, or significant performance regressions.
284 if cfg.IsBazelMixedBuildForceDisabled() {
285 return false
286 }
287 // Darwin-host builds are currently untested with Bazel.
288 if runtime.GOOS == "darwin" {
289 return false
290 }
Chris Parsons035e03a2022-11-01 14:25:45 -0400291 return true
Chris Parsonsb6e96902022-10-31 20:08:45 -0400292}
293
MarkDacek6614d9c2022-12-07 21:57:38 +0000294func UploadOnlyConfig(ctx Context, _ ...string) Config {
295 ret := &configImpl{
296 environ: OsEnvironment(),
297 sandboxConfig: &SandboxConfig{},
298 }
MarkDacek7901e582023-01-09 19:48:01 +0000299 srcDir := absPath(ctx, ".")
300 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
301 if err := loadEnvConfig(ctx, ret, bc); err != nil {
302 ctx.Fatalln("Failed to parse env config files: %v", err)
303 }
304 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
MarkDacek6614d9c2022-12-07 21:57:38 +0000305 return Config{ret}
306}
307
Dan Willemsen1e704462016-08-21 15:17:17 -0700308func NewConfig(ctx Context, args ...string) Config {
309 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000310 environ: OsEnvironment(),
311 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700312 }
313
Patrice Arruda90109172020-07-28 18:07:27 +0000314 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700315 ret.parallel = runtime.NumCPU() + 2
316 ret.keepGoing = 1
317
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800318 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700319 ret.parseArgs(ctx, args)
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800320 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700321 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
322 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
323 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800324 outDir := "out"
325 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
326 if wd, err := os.Getwd(); err != nil {
327 ctx.Fatalln("Failed to get working directory:", err)
328 } else {
329 outDir = filepath.Join(baseDir, filepath.Base(wd))
330 }
331 }
332 ret.environ.Set("OUT_DIR", outDir)
333 }
334
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500335 // loadEnvConfig needs to know what the OUT_DIR is, so it should
336 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000337 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
338
339 if bc != "" {
340 if err := fetchEnvConfig(ctx, ret, bc); err != nil {
341 ctx.Verbosef("Failed to fetch config file: %v\n", err)
Kousik Kumarc8818332023-01-16 16:33:05 +0000342 }
343 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000344 ctx.Fatalln("Failed to parse env config files: %v", err)
345 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500346 }
347
Dan Willemsen2d31a442018-10-20 21:33:41 -0700348 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
349 ret.distDir = filepath.Clean(distDir)
350 } else {
351 ret.distDir = filepath.Join(ret.OutDir(), "dist")
352 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700353
Spandan Das05063612021-06-25 01:39:04 +0000354 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
355 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
356 }
357
Dan Willemsen1e704462016-08-21 15:17:17 -0700358 ret.environ.Unset(
359 // We're already using it
360 "USE_SOONG_UI",
361
362 // We should never use GOROOT/GOPATH from the shell environment
363 "GOROOT",
364 "GOPATH",
365
366 // These should only come from Soong, not the environment.
367 "CLANG",
368 "CLANG_CXX",
369 "CCC_CC",
370 "CCC_CXX",
371
372 // Used by the goma compiler wrapper, but should only be set by
373 // gomacc
374 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800375
376 // We handle this above
377 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700378
Dan Willemsen2d31a442018-10-20 21:33:41 -0700379 // This is handled above too, and set for individual commands later
380 "DIST_DIR",
381
Dan Willemsen68a09852017-04-18 13:56:57 -0700382 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000383 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700384 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700385 "DISPLAY",
386 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000387 "JAVAC",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700388 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700389 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700390
391 // Drop make flags
392 "MAKEFLAGS",
393 "MAKELEVEL",
394 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700395
396 // Set in envsetup.sh, reset in makefiles
397 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700398
399 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
400 "ANDROID_BUILD_TOP",
401 "ANDROID_HOST_OUT",
402 "ANDROID_PRODUCT_OUT",
403 "ANDROID_HOST_OUT_TESTCASES",
404 "ANDROID_TARGET_OUT_TESTCASES",
405 "ANDROID_TOOLCHAIN",
406 "ANDROID_TOOLCHAIN_2ND_ARCH",
407 "ANDROID_DEV_SCRIPTS",
408 "ANDROID_EMULATOR_PREBUILTS",
409 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700410 )
411
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400412 if ret.UseGoma() || ret.ForceUseGoma() {
413 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
414 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400415 }
416
Dan Willemsen1e704462016-08-21 15:17:17 -0700417 // Tell python not to spam the source tree with .pyc files.
418 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
419
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400420 tmpDir := absPath(ctx, ret.TempDir())
421 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800422
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700423 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
424 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
425 "llvm-binutils-stable/llvm-symbolizer")
426 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
427
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800428 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700429 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800430
Yu Liu6e13b402021-07-27 14:29:06 -0700431 srcDir := absPath(ctx, ".")
432 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700433 ctx.Println("You are building in a directory whose absolute path contains a space character:")
434 ctx.Println()
435 ctx.Printf("%q\n", srcDir)
436 ctx.Println()
437 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700438 }
439
Yu Liu6e13b402021-07-27 14:29:06 -0700440 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
441
Dan Willemsendb8457c2017-05-12 16:38:17 -0700442 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700443 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
444 ctx.Println()
445 ctx.Printf("%q\n", outDir)
446 ctx.Println()
447 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700448 }
449
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000450 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700451 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
452 ctx.Println()
453 ctx.Printf("%q\n", distDir)
454 ctx.Println()
455 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700456 }
457
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700458 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000459 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
460 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100461 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800462 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700463 javaHome := func() string {
464 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
465 return override
466 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000467 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
468 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 +0100469 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000470 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
471 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
472 }
473 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700474 }()
475 absJavaHome := absPath(ctx, javaHome)
476
Dan Willemsened869522018-01-08 14:58:46 -0800477 ret.configureLocale(ctx)
478
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700479 newPath := []string{filepath.Join(absJavaHome, "bin")}
480 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
481 newPath = append(newPath, path)
482 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100483
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700484 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
485 ret.environ.Set("JAVA_HOME", absJavaHome)
486 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000487 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
488 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100489 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700490 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
491
LaMont Jones52a72432023-03-09 18:19:35 +0000492 if ret.MultitreeBuild() {
493 ret.environ.Set("MULTITREE_BUILD", "true")
494 }
495
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800496 outDir := ret.OutDir()
497 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800498 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800499 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800500 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800501 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800502 }
Colin Cross28f527c2019-11-26 16:19:04 -0800503
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800504 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
505
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400506 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400507 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400508 ret.environ.Set(k, v)
509 }
510 }
511
Patrice Arruda83842d72020-12-08 19:42:08 +0000512 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800513 if err := os.RemoveAll(bpd); err != nil {
514 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
515 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000516
Patrice Arruda96850362020-08-11 20:41:11 +0000517 c := Config{ret}
518 storeConfigMetrics(ctx, c)
519 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700520}
521
Patrice Arruda13848222019-04-22 17:12:02 -0700522// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
523// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700524func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
525 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700526}
527
Patrice Arruda96850362020-08-11 20:41:11 +0000528// storeConfigMetrics selects a set of configuration information and store in
529// the metrics system for further analysis.
530func storeConfigMetrics(ctx Context, config Config) {
531 if ctx.Metrics == nil {
532 return
533 }
534
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400535 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000536
537 s := &smpb.SystemResourceInfo{
538 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
539 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
540 }
541 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000542}
543
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900544func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.NinjaWeightListSource {
545 switch s {
546 case NINJA_LOG:
547 return smpb.NinjaWeightListSource_NINJA_LOG.Enum()
548 case EVENLY_DISTRIBUTED:
549 return smpb.NinjaWeightListSource_EVENLY_DISTRIBUTED.Enum()
550 default:
551 return smpb.NinjaWeightListSource_NOT_USED.Enum()
552 }
553}
554
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400555func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700556 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400557 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
558 UseGoma: proto.Bool(config.UseGoma()),
559 UseRbe: proto.Bool(config.UseRBE()),
560 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
561 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900562 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400563 }
Yu Liue737a992021-10-04 13:21:41 -0700564 c.Targets = append(c.Targets, config.arguments...)
565
566 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400567}
568
Patrice Arruda13848222019-04-22 17:12:02 -0700569// getConfigArgs processes the command arguments based on the build action and creates a set of new
570// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700571func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700572 // The next block of code verifies that the current directory is the root directory of the source
573 // tree. It then finds the relative path of dir based on the root directory of the source tree
574 // and verify that dir is inside of the source tree.
575 checkTopDir(ctx)
576 topDir, err := os.Getwd()
577 if err != nil {
578 ctx.Fatalf("Error retrieving top directory: %v", err)
579 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700580 dir, err = filepath.EvalSymlinks(dir)
581 if err != nil {
582 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
583 }
Patrice Arruda13848222019-04-22 17:12:02 -0700584 dir, err = filepath.Abs(dir)
585 if err != nil {
586 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
587 }
588 relDir, err := filepath.Rel(topDir, dir)
589 if err != nil {
590 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
591 }
592 // If there are ".." in the path, it's not in the source tree.
593 if strings.Contains(relDir, "..") {
594 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
595 }
596
597 configArgs := args[:]
598
599 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
600 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
601 targetNamePrefix := "MODULES-IN-"
602 if inList("GET-INSTALL-PATH", configArgs) {
603 targetNamePrefix = "GET-INSTALL-PATH-IN-"
604 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
605 }
606
Patrice Arruda13848222019-04-22 17:12:02 -0700607 var targets []string
608
609 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700610 case BUILD_MODULES:
611 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700612 case BUILD_MODULES_IN_A_DIRECTORY:
613 // If dir is the root source tree, all the modules are built of the source tree are built so
614 // no need to find the build file.
615 if topDir == dir {
616 break
617 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700618
Patrice Arruda13848222019-04-22 17:12:02 -0700619 buildFile := findBuildFile(ctx, relDir)
620 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700621 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700622 }
Patrice Arruda13848222019-04-22 17:12:02 -0700623 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
624 case BUILD_MODULES_IN_DIRECTORIES:
625 newConfigArgs, dirs := splitArgs(configArgs)
626 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700627 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700628 }
629
630 // Tidy only override all other specified targets.
631 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
632 if tidyOnly == "true" || tidyOnly == "1" {
633 configArgs = append(configArgs, "tidy_only")
634 } else {
635 configArgs = append(configArgs, targets...)
636 }
637
638 return configArgs
639}
640
641// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
642func convertToTarget(dir string, targetNamePrefix string) string {
643 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
644}
645
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700646// hasBuildFile returns true if dir contains an Android build file.
647func hasBuildFile(ctx Context, dir string) bool {
648 for _, buildFile := range buildFiles {
649 _, err := os.Stat(filepath.Join(dir, buildFile))
650 if err == nil {
651 return true
652 }
653 if !os.IsNotExist(err) {
654 ctx.Fatalf("Error retrieving the build file stats: %v", err)
655 }
656 }
657 return false
658}
659
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700660// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
661// in the current and any sub directory of dir. If a build file is not found, traverse the path
662// up by one directory and repeat again until either a build file is found or reached to the root
663// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
664// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700665func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700666 // If the string is empty or ".", assume it is top directory of the source tree.
667 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700668 return ""
669 }
670
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700671 found := false
672 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
673 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
674 if err != nil {
675 return err
676 }
677 if found {
678 return filepath.SkipDir
679 }
680 if info.IsDir() {
681 return nil
682 }
683 for _, buildFile := range buildFiles {
684 if info.Name() == buildFile {
685 found = true
686 return filepath.SkipDir
687 }
688 }
689 return nil
690 })
691 if err != nil {
692 ctx.Fatalf("Error finding Android build file: %v", err)
693 }
694
695 if found {
696 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700697 }
698 }
699
700 return ""
701}
702
703// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
704func splitArgs(args []string) (newArgs []string, dirs []string) {
705 specialArgs := map[string]bool{
706 "showcommands": true,
707 "snod": true,
708 "dist": true,
709 "checkbuild": true,
710 }
711
712 newArgs = []string{}
713 dirs = []string{}
714
715 for _, arg := range args {
716 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
717 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
718 newArgs = append(newArgs, arg)
719 continue
720 }
721
722 if _, ok := specialArgs[arg]; ok {
723 newArgs = append(newArgs, arg)
724 continue
725 }
726
727 dirs = append(dirs, arg)
728 }
729
730 return newArgs, dirs
731}
732
733// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
734// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
735// source root tree where the build action command was invoked. Each directory is validated if the
736// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700737func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700738 for _, dir := range dirs {
739 // The directory may have specified specific modules to build. ":" is the separator to separate
740 // the directory and the list of modules.
741 s := strings.Split(dir, ":")
742 l := len(s)
743 if l > 2 { // more than one ":" was specified.
744 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
745 }
746
747 dir = filepath.Join(relDir, s[0])
748 if _, err := os.Stat(dir); err != nil {
749 ctx.Fatalf("couldn't find directory %s", dir)
750 }
751
752 // Verify that if there are any targets specified after ":". Each target is separated by ",".
753 var newTargets []string
754 if l == 2 && s[1] != "" {
755 newTargets = strings.Split(s[1], ",")
756 if inList("", newTargets) {
757 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
758 }
759 }
760
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700761 // If there are specified targets to build in dir, an android build file must exist for the one
762 // shot build. For the non-targets case, find the appropriate build file and build all the
763 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700764 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700765 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700766 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
767 }
768 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700769 buildFile := findBuildFile(ctx, dir)
770 if buildFile == "" {
771 ctx.Fatalf("Build file not found for %s directory", dir)
772 }
773 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700774 }
775
Patrice Arruda13848222019-04-22 17:12:02 -0700776 targets = append(targets, newTargets...)
777 }
778
Dan Willemsence41e942019-07-29 23:39:30 -0700779 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700780}
781
Dan Willemsen9b587492017-07-10 22:13:00 -0700782func (c *configImpl) parseArgs(ctx Context, args []string) {
783 for i := 0; i < len(args); i++ {
784 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100785 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700786 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200787 } else if arg == "--empty-ninja-file" {
788 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100789 } else if arg == "--skip-ninja" {
790 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700791 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700792 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
793 // but it does run a Kati ninja file if the .kati_enabled marker file was created
794 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000795 c.skipConfig = true
796 c.skipKati = true
797 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100798 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000799 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100800 } else if arg == "--soong-only" {
801 c.skipKati = true
802 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200803 } else if arg == "--config-only" {
804 c.skipKati = true
805 c.skipKatiNinja = true
806 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700807 } else if arg == "--skip-config" {
808 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700809 } else if arg == "--skip-soong-tests" {
810 c.skipSoongTests = true
MarkDacekd0e7cd32022-12-02 22:22:40 +0000811 } else if arg == "--skip-metrics-upload" {
812 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500813 } else if arg == "--mk-metrics" {
814 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000815 } else if arg == "--multitree-build" {
816 c.multitreeBuild = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400817 } else if arg == "--bazel-mode" {
818 c.bazelProdMode = true
819 } else if arg == "--bazel-mode-dev" {
820 c.bazelDevMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000821 } else if arg == "--bazel-mode-staging" {
822 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000823 } else if arg == "--search-api-dir" {
824 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900825 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
826 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
827 if source == "ninja_log" {
828 c.ninjaWeightListSource = NINJA_LOG
829 } else if source == "evenly_distributed" {
830 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
831 } else if source == "not_used" {
832 c.ninjaWeightListSource = NOT_USED
833 } else {
834 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
835 }
MarkDacekb96561e2022-12-02 04:34:43 +0000836 } else if strings.HasPrefix(arg, "--build-command=") {
837 buildCmd := strings.TrimPrefix(arg, "--build-command=")
838 // remove quotations
839 buildCmd = strings.TrimPrefix(buildCmd, "\"")
840 buildCmd = strings.TrimSuffix(buildCmd, "\"")
841 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000842 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
843 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
MarkDacek6614d9c2022-12-07 21:57:38 +0000844 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
845 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
846 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
847 if err == nil {
848 c.buildStartedTime = val
849 } else {
850 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
851 }
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700852 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700853 parseArgNum := func(def int) int {
854 if len(arg) > 2 {
855 p, err := strconv.ParseUint(arg[2:], 10, 31)
856 if err != nil {
857 ctx.Fatalf("Failed to parse %q: %v", arg, err)
858 }
859 return int(p)
860 } else if i+1 < len(args) {
861 p, err := strconv.ParseUint(args[i+1], 10, 31)
862 if err == nil {
863 i++
864 return int(p)
865 }
866 }
867 return def
868 }
869
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700870 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700871 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700872 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700873 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700874 } else {
875 ctx.Fatalln("Unknown option:", arg)
876 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700877 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700878 if k == "OUT_DIR" {
879 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
880 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700881 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700882 } else if arg == "dist" {
883 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200884 } else if arg == "json-module-graph" {
885 c.jsonModuleGraph = true
886 } else if arg == "bp2build" {
887 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000888 } else if arg == "api_bp2build" {
889 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200890 } else if arg == "queryview" {
891 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200892 } else if arg == "soong_docs" {
893 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700894 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700895 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800896 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700897 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700898 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700899 }
900 }
Chris Parsonsb6e96902022-10-31 20:08:45 -0400901 if (!c.bazelProdMode) && (!c.bazelDevMode) && (!c.bazelStagingMode) {
902 c.bazelProdMode = defaultBazelProdMode(c)
903 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700904}
905
Dan Willemsened869522018-01-08 14:58:46 -0800906func (c *configImpl) configureLocale(ctx Context) {
907 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
908 output, err := cmd.Output()
909
910 var locales []string
911 if err == nil {
912 locales = strings.Split(string(output), "\n")
913 } else {
914 // If we're unable to list the locales, let's assume en_US.UTF-8
915 locales = []string{"en_US.UTF-8"}
916 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
917 }
918
919 // gettext uses LANGUAGE, which is passed directly through
920
921 // For LANG and LC_*, only preserve the evaluated version of
922 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800923 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800924 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800925 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800926 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800927 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800928 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800929 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800930 }
931
932 c.environ.UnsetWithPrefix("LC_")
933
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800934 if userLang != "" {
935 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800936 }
937
938 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
939 // for others)
940 if inList("C.UTF-8", locales) {
941 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500942 } else if inList("C.utf8", locales) {
943 // These normalize to the same thing
944 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800945 } else if inList("en_US.UTF-8", locales) {
946 c.environ.Set("LANG", "en_US.UTF-8")
947 } else if inList("en_US.utf8", locales) {
948 // These normalize to the same thing
949 c.environ.Set("LANG", "en_US.UTF-8")
950 } else {
951 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
952 }
953}
954
Dan Willemsen1e704462016-08-21 15:17:17 -0700955func (c *configImpl) Environment() *Environment {
956 return c.environ
957}
958
959func (c *configImpl) Arguments() []string {
960 return c.arguments
961}
962
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200963func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200964 if len(c.Arguments()) > 0 {
965 // Explicit targets requested that are not special targets like b2pbuild
966 // or the JSON module graph
967 return true
968 }
969
Spandan Das5af0bd32022-09-28 20:43:08 +0000970 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200971 // Command line was empty, the default Ninja target is built
972 return true
973 }
974
Liz Kammer88677422021-12-15 15:03:19 -0500975 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
976 if c.Dist() && !c.Bp2Build() {
977 return true
978 }
979
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200980 // build.ninja doesn't need to be generated
981 return false
982}
983
Dan Willemsen1e704462016-08-21 15:17:17 -0700984func (c *configImpl) OutDir() string {
985 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700986 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700987 }
988 return "out"
989}
990
Dan Willemsen8a073a82017-02-04 17:30:44 -0800991func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400992 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000993}
994
995func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700996 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800997}
998
Dan Willemsen1e704462016-08-21 15:17:17 -0700999func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001000 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001001 return c.arguments
1002 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001003 return c.ninjaArgs
1004}
1005
Jingwen Chen7c6089a2020-11-02 02:56:20 -05001006func (c *configImpl) BazelOutDir() string {
1007 return filepath.Join(c.OutDir(), "bazel")
1008}
1009
Liz Kammer2af5ea82022-11-11 14:21:03 -05001010func (c *configImpl) bazelOutputBase() string {
1011 return filepath.Join(c.BazelOutDir(), "output")
1012}
1013
Dan Willemsen1e704462016-08-21 15:17:17 -07001014func (c *configImpl) SoongOutDir() string {
1015 return filepath.Join(c.OutDir(), "soong")
1016}
1017
Spandan Das394aa322022-11-03 17:02:10 +00001018func (c *configImpl) ApiSurfacesOutDir() string {
1019 return filepath.Join(c.OutDir(), "api_surfaces")
1020}
1021
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001022func (c *configImpl) PrebuiltOS() string {
1023 switch runtime.GOOS {
1024 case "linux":
1025 return "linux-x86"
1026 case "darwin":
1027 return "darwin-x86"
1028 default:
1029 panic("Unknown GOOS")
1030 }
1031}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001032
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001033func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001034 if c.SkipKatiNinja() {
1035 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1036 } else {
1037 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1038 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001039}
1040
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001041func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001042 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001043}
1044
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001045func (c *configImpl) UsedEnvFile(tag string) string {
1046 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1047}
1048
Lukacs T. Berkic541cd22022-10-26 07:26:50 +00001049func (c *configImpl) Bp2BuildFilesMarkerFile() string {
1050 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
1051}
1052
1053func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001054 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +02001055}
1056
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001057func (c *configImpl) SoongDocsHtml() string {
1058 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1059}
1060
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001061func (c *configImpl) QueryviewMarkerFile() string {
1062 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1063}
1064
Spandan Das5af0bd32022-09-28 20:43:08 +00001065func (c *configImpl) ApiBp2buildMarkerFile() string {
1066 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
1067}
1068
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001069func (c *configImpl) ModuleGraphFile() string {
1070 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1071}
1072
kgui67007242022-01-25 13:50:25 +08001073func (c *configImpl) ModuleActionsFile() string {
1074 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1075}
1076
Jeff Gastonefc1b412017-03-29 17:29:06 -07001077func (c *configImpl) TempDir() string {
1078 return shared.TempDirForOutDir(c.SoongOutDir())
1079}
1080
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001081func (c *configImpl) FileListDir() string {
1082 return filepath.Join(c.OutDir(), ".module_paths")
1083}
1084
Dan Willemsen1e704462016-08-21 15:17:17 -07001085func (c *configImpl) KatiSuffix() string {
1086 if c.katiSuffix != "" {
1087 return c.katiSuffix
1088 }
1089 panic("SetKatiSuffix has not been called")
1090}
1091
Colin Cross37193492017-11-16 17:55:00 -08001092// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1093// user is interested in additional checks at the expense of build time.
1094func (c *configImpl) Checkbuild() bool {
1095 return c.checkbuild
1096}
1097
Dan Willemsen8a073a82017-02-04 17:30:44 -08001098func (c *configImpl) Dist() bool {
1099 return c.dist
1100}
1101
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001102func (c *configImpl) JsonModuleGraph() bool {
1103 return c.jsonModuleGraph
1104}
1105
1106func (c *configImpl) Bp2Build() bool {
1107 return c.bp2build
1108}
1109
Spandan Das5af0bd32022-09-28 20:43:08 +00001110func (c *configImpl) ApiBp2build() bool {
1111 return c.apiBp2build
1112}
1113
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001114func (c *configImpl) Queryview() bool {
1115 return c.queryview
1116}
1117
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001118func (c *configImpl) SoongDocs() bool {
1119 return c.soongDocs
1120}
1121
Dan Willemsen1e704462016-08-21 15:17:17 -07001122func (c *configImpl) IsVerbose() bool {
1123 return c.verbose
1124}
1125
LaMont Jones52a72432023-03-09 18:19:35 +00001126func (c *configImpl) MultitreeBuild() bool {
1127 return c.multitreeBuild
1128}
1129
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001130func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1131 return c.ninjaWeightListSource
1132}
1133
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001134func (c *configImpl) SkipKati() bool {
1135 return c.skipKati
1136}
1137
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001138func (c *configImpl) SkipKatiNinja() bool {
1139 return c.skipKatiNinja
1140}
1141
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001142func (c *configImpl) SkipSoong() bool {
1143 return c.skipSoong
1144}
1145
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001146func (c *configImpl) SkipNinja() bool {
1147 return c.skipNinja
1148}
1149
Anton Hansson5a7861a2021-06-04 10:09:01 +01001150func (c *configImpl) SetSkipNinja(v bool) {
1151 c.skipNinja = v
1152}
1153
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001154func (c *configImpl) SkipConfig() bool {
1155 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001156}
1157
Dan Willemsen1e704462016-08-21 15:17:17 -07001158func (c *configImpl) TargetProduct() string {
1159 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1160 return v
1161 }
1162 panic("TARGET_PRODUCT is not defined")
1163}
1164
Dan Willemsen02781d52017-05-12 19:28:13 -07001165func (c *configImpl) TargetDevice() string {
1166 return c.targetDevice
1167}
1168
1169func (c *configImpl) SetTargetDevice(device string) {
1170 c.targetDevice = device
1171}
1172
1173func (c *configImpl) TargetBuildVariant() string {
1174 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1175 return v
1176 }
1177 panic("TARGET_BUILD_VARIANT is not defined")
1178}
1179
Dan Willemsen1e704462016-08-21 15:17:17 -07001180func (c *configImpl) KatiArgs() []string {
1181 return c.katiArgs
1182}
1183
1184func (c *configImpl) Parallel() int {
1185 return c.parallel
1186}
1187
Spandan Dasc5763832022-11-08 18:42:16 +00001188func (c *configImpl) GetIncludeTags() []string {
1189 return c.includeTags
1190}
1191
1192func (c *configImpl) SetIncludeTags(i []string) {
1193 c.includeTags = i
1194}
1195
MarkDacek6614d9c2022-12-07 21:57:38 +00001196func (c *configImpl) GetLogsPrefix() string {
1197 return c.logsPrefix
1198}
1199
1200func (c *configImpl) SetLogsPrefix(prefix string) {
1201 c.logsPrefix = prefix
1202}
1203
Colin Cross8b8bec32019-11-15 13:18:43 -08001204func (c *configImpl) HighmemParallel() int {
1205 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1206 return i
1207 }
1208
1209 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1210 parallel := c.Parallel()
1211 if c.UseRemoteBuild() {
1212 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1213 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1214 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1215 // Return 1/16th of the size of the local pool, rounding up.
1216 return (parallel + 15) / 16
1217 } else if c.totalRAM == 0 {
1218 // Couldn't detect the total RAM, don't restrict highmem processes.
1219 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001220 } else if c.totalRAM <= 16*1024*1024*1024 {
1221 // Less than 16GB of ram, restrict to 1 highmem processes
1222 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001223 } else if c.totalRAM <= 32*1024*1024*1024 {
1224 // Less than 32GB of ram, restrict to 2 highmem processes
1225 return 2
1226 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1227 // If less than 8GB total RAM per process, reduce the number of highmem processes
1228 return p
1229 }
1230 // No restriction on highmem processes
1231 return parallel
1232}
1233
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001234func (c *configImpl) TotalRAM() uint64 {
1235 return c.totalRAM
1236}
1237
Kousik Kumarec478642020-09-21 13:39:24 -04001238// ForceUseGoma determines whether we should override Goma deprecation
1239// and use Goma for the current build or not.
1240func (c *configImpl) ForceUseGoma() bool {
1241 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1242 v = strings.TrimSpace(v)
1243 if v != "" && v != "false" {
1244 return true
1245 }
1246 }
1247 return false
1248}
1249
Dan Willemsen1e704462016-08-21 15:17:17 -07001250func (c *configImpl) UseGoma() bool {
1251 if v, ok := c.environ.Get("USE_GOMA"); ok {
1252 v = strings.TrimSpace(v)
1253 if v != "" && v != "false" {
1254 return true
1255 }
1256 }
1257 return false
1258}
1259
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001260func (c *configImpl) StartGoma() bool {
1261 if !c.UseGoma() {
1262 return false
1263 }
1264
1265 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1266 v = strings.TrimSpace(v)
1267 if v != "" && v != "false" {
1268 return false
1269 }
1270 }
1271 return true
1272}
1273
Ramy Medhatbbf25672019-07-17 12:30:04 +00001274func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001275 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001276 v = strings.TrimSpace(v)
1277 if v != "" && v != "false" {
1278 return true
1279 }
1280 }
1281 return false
1282}
1283
Chris Parsonsef615e52022-08-18 22:04:11 -04001284func (c *configImpl) BazelBuildEnabled() bool {
MarkDacekb78465d2022-10-18 20:10:16 +00001285 return c.bazelProdMode || c.bazelDevMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001286}
1287
Ramy Medhatbbf25672019-07-17 12:30:04 +00001288func (c *configImpl) StartRBE() bool {
1289 if !c.UseRBE() {
1290 return false
1291 }
1292
1293 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1294 v = strings.TrimSpace(v)
1295 if v != "" && v != "false" {
1296 return false
1297 }
1298 }
1299 return true
1300}
1301
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001302func (c *configImpl) rbeProxyLogsDir() string {
1303 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001304 if v, ok := c.environ.Get(f); ok {
1305 return v
1306 }
1307 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001308 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1309 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001310}
1311
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001312func (c *configImpl) shouldCleanupRBELogsDir() bool {
1313 // Perform a log directory cleanup only when the log directory
1314 // is auto created by the build rather than user-specified.
1315 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1316 if _, ok := c.environ.Get(f); ok {
1317 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001318 }
1319 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001320 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001321}
1322
1323func (c *configImpl) rbeExecRoot() string {
1324 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1325 if v, ok := c.environ.Get(f); ok {
1326 return v
1327 }
1328 }
1329 wd, err := os.Getwd()
1330 if err != nil {
1331 return ""
1332 }
1333 return wd
1334}
1335
1336func (c *configImpl) rbeDir() string {
1337 if v, ok := c.environ.Get("RBE_DIR"); ok {
1338 return v
1339 }
1340 return "prebuilts/remoteexecution-client/live/"
1341}
1342
1343func (c *configImpl) rbeReproxy() string {
1344 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1345 if v, ok := c.environ.Get(f); ok {
1346 return v
1347 }
1348 }
1349 return filepath.Join(c.rbeDir(), "reproxy")
1350}
1351
1352func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001353 credFlags := []string{
1354 "use_application_default_credentials",
1355 "use_gce_credentials",
1356 "credential_file",
1357 "use_google_prod_creds",
1358 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001359 for _, cf := range credFlags {
1360 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1361 if v, ok := c.environ.Get(f); ok {
1362 v = strings.TrimSpace(v)
1363 if v != "" && v != "false" && v != "0" {
1364 return "RBE_" + cf, v
1365 }
1366 }
1367 }
1368 }
1369 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001370}
1371
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001372func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1373 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1374 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1375
1376 name := filepath.Join(dir, base)
1377 if len(name) < maxNameLen {
1378 return name, nil
1379 }
1380
1381 name = filepath.Join("/tmp", base)
1382 if len(name) < maxNameLen {
1383 return name, nil
1384 }
1385
1386 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1387}
1388
Kousik Kumar7bc78192022-04-27 14:52:56 -04001389// IsGooglerEnvironment returns true if the current build is running
1390// on a Google developer machine and false otherwise.
1391func (c *configImpl) IsGooglerEnvironment() bool {
1392 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1393 if v, ok := c.environ.Get(cf); ok {
1394 return v == "googler"
1395 }
1396 return false
1397}
1398
1399// GoogleProdCredsExist determine whether credentials exist on the
1400// Googler machine to use remote execution.
1401func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001402 if googleProdCredsExistCache {
1403 return googleProdCredsExistCache
1404 }
Kousik Kumar7bc78192022-04-27 14:52:56 -04001405 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1406 return false
1407 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001408 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001409 return true
1410}
1411
1412// UseRemoteBuild indicates whether to use a remote build acceleration system
1413// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001414func (c *configImpl) UseRemoteBuild() bool {
1415 return c.UseGoma() || c.UseRBE()
1416}
1417
Kousik Kumar7bc78192022-04-27 14:52:56 -04001418// StubbyExists checks whether the stubby binary exists on the machine running
1419// the build.
1420func (c *configImpl) StubbyExists() bool {
1421 if _, err := exec.LookPath("stubby"); err != nil {
1422 return false
1423 }
1424 return true
1425}
1426
Dan Willemsen1e704462016-08-21 15:17:17 -07001427// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001428// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001429// still limited by Parallel()
1430func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001431 if !c.UseRemoteBuild() {
1432 return 0
1433 }
1434 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1435 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001436 }
1437 return 500
1438}
1439
1440func (c *configImpl) SetKatiArgs(args []string) {
1441 c.katiArgs = args
1442}
1443
1444func (c *configImpl) SetNinjaArgs(args []string) {
1445 c.ninjaArgs = args
1446}
1447
1448func (c *configImpl) SetKatiSuffix(suffix string) {
1449 c.katiSuffix = suffix
1450}
1451
Dan Willemsene0879fc2017-08-04 15:06:27 -07001452func (c *configImpl) LastKatiSuffixFile() string {
1453 return filepath.Join(c.OutDir(), "last_kati_suffix")
1454}
1455
1456func (c *configImpl) HasKatiSuffix() bool {
1457 return c.katiSuffix != ""
1458}
1459
Dan Willemsen1e704462016-08-21 15:17:17 -07001460func (c *configImpl) KatiEnvFile() string {
1461 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1462}
1463
Dan Willemsen29971232018-09-26 14:58:30 -07001464func (c *configImpl) KatiBuildNinjaFile() string {
1465 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001466}
1467
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001468func (c *configImpl) KatiPackageNinjaFile() string {
1469 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1470}
1471
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001472func (c *configImpl) SoongVarsFile() string {
1473 return filepath.Join(c.SoongOutDir(), "soong.variables")
1474}
1475
Dan Willemsen1e704462016-08-21 15:17:17 -07001476func (c *configImpl) SoongNinjaFile() string {
1477 return filepath.Join(c.SoongOutDir(), "build.ninja")
1478}
1479
1480func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001481 if c.katiSuffix == "" {
1482 return filepath.Join(c.OutDir(), "combined.ninja")
1483 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001484 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1485}
1486
1487func (c *configImpl) SoongAndroidMk() string {
1488 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1489}
1490
1491func (c *configImpl) SoongMakeVarsMk() string {
1492 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1493}
1494
Dan Willemsenf052f782017-05-18 15:29:04 -07001495func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001496 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001497}
1498
Dan Willemsen02781d52017-05-12 19:28:13 -07001499func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001500 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1501}
1502
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001503func (c *configImpl) KatiPackageMkDir() string {
1504 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1505}
1506
Dan Willemsenf052f782017-05-18 15:29:04 -07001507func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001508 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001509}
1510
1511func (c *configImpl) HostOut() string {
1512 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1513}
1514
1515// This probably needs to be multi-valued, so not exporting it for now
1516func (c *configImpl) hostCrossOut() string {
1517 if runtime.GOOS == "linux" {
1518 return filepath.Join(c.hostOutRoot(), "windows-x86")
1519 } else {
1520 return ""
1521 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001522}
1523
Dan Willemsen1e704462016-08-21 15:17:17 -07001524func (c *configImpl) HostPrebuiltTag() string {
1525 if runtime.GOOS == "linux" {
1526 return "linux-x86"
1527 } else if runtime.GOOS == "darwin" {
1528 return "darwin-x86"
1529 } else {
1530 panic("Unsupported OS")
1531 }
1532}
Dan Willemsenf173d592017-04-27 14:28:00 -07001533
Dan Willemsen8122bd52017-10-12 20:20:41 -07001534func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001535 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1536 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001537 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1538 if _, err := os.Stat(asan); err == nil {
1539 return asan
1540 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001541 }
1542 }
1543 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1544}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001545
1546func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1547 c.brokenDupRules = val
1548}
1549
1550func (c *configImpl) BuildBrokenDupRules() bool {
1551 return c.brokenDupRules
1552}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001553
Dan Willemsen25e6f092019-04-09 10:22:43 -07001554func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1555 c.brokenUsesNetwork = val
1556}
1557
1558func (c *configImpl) BuildBrokenUsesNetwork() bool {
1559 return c.brokenUsesNetwork
1560}
1561
Dan Willemsene3336352020-01-02 19:10:38 -08001562func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1563 c.brokenNinjaEnvVars = val
1564}
1565
1566func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1567 return c.brokenNinjaEnvVars
1568}
1569
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001570func (c *configImpl) SetTargetDeviceDir(dir string) {
1571 c.targetDeviceDir = dir
1572}
1573
1574func (c *configImpl) TargetDeviceDir() string {
1575 return c.targetDeviceDir
1576}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001577
Patrice Arruda219eef32020-06-01 17:29:30 +00001578func (c *configImpl) BuildDateTime() string {
1579 return c.buildDateTime
1580}
1581
1582func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001583 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001584}
Patrice Arruda83842d72020-12-08 19:42:08 +00001585
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001586// LogsDir returns the absolute path to the logs directory where build log and
1587// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001588// directory. If the argument dist is specified, the logs directory
1589// is <dist_dir>/logs.
1590func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001591 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001592 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001593 // 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 -05001594 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001595 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001596 absDir, err := filepath.Abs(dir)
1597 if err != nil {
1598 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1599 os.Exit(1)
1600 }
1601 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001602}
1603
1604// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1605// where the bazel profiles are located.
1606func (c *configImpl) BazelMetricsDir() string {
1607 return filepath.Join(c.LogsDir(), "bazel_metrics")
1608}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001609
Chris Parsons53f68ae2022-03-03 12:01:40 -05001610// MkFileMetrics returns the file path for make-related metrics.
1611func (c *configImpl) MkMetrics() string {
1612 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1613}
1614
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001615func (c *configImpl) SetEmptyNinjaFile(v bool) {
1616 c.emptyNinjaFile = v
1617}
1618
1619func (c *configImpl) EmptyNinjaFile() bool {
1620 return c.emptyNinjaFile
1621}
Yu Liu6e13b402021-07-27 14:29:06 -07001622
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001623func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1624 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1625}
1626
Chris Parsons9402ca82023-02-23 17:28:06 -05001627func (c *configImpl) IsPersistentBazelEnabled() bool {
1628 return c.Environment().IsEnvTrue("USE_PERSISTENT_BAZEL")
1629}
1630
MarkDacekd06db5d2022-11-29 00:47:59 +00001631func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1632 return c.bazelForceEnabledModules
1633}
1634
MarkDacekd0e7cd32022-12-02 22:22:40 +00001635func (c *configImpl) SkipMetricsUpload() bool {
1636 return c.skipMetricsUpload
1637}
1638
MarkDacek6614d9c2022-12-07 21:57:38 +00001639// Returns a Time object if one was passed via a command-line flag.
1640// Otherwise returns the passed default.
1641func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1642 if c.buildStartedTime == 0 {
1643 return defaultTime
1644 }
1645 return time.UnixMilli(c.buildStartedTime)
1646}
1647
Yu Liu6e13b402021-07-27 14:29:06 -07001648func GetMetricsUploader(topDir string, env *Environment) string {
1649 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1650 metricsUploader := filepath.Join(topDir, p)
1651 if _, err := os.Stat(metricsUploader); err == nil {
1652 return metricsUploader
1653 }
1654 }
1655
1656 return ""
1657}