blob: 89de01acd03fae5f453adb4508be17e53055f2db [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
MarkDacekf47e1422023-04-19 16:47:36 +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
81 multitreeBuild bool // This is a multitree build.
82 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
90 buildStartedTime int64 // For metrics-upload-only - manually specify a build-started time
91 buildFromTextStub bool
MarkDacekd33c2fd2023-05-04 20:40:04 +000092 ensureAllowlistIntegrity bool // For CI builds - make sure modules are mixed-built
93 bazelExitCode int32 // For b-runs - necessary for updating NonZeroExit
Dan Willemsen1e704462016-08-21 15:17:17 -070094
95 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070096 katiArgs []string
97 ninjaArgs []string
98 katiSuffix string
99 targetDevice string
100 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +0000101 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -0700102
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800103 // Autodetected
104 totalRAM uint64
105
Dan Willemsene3336352020-01-02 19:10:38 -0800106 brokenDupRules bool
107 brokenUsesNetwork bool
108 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -0700109
110 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000111
MarkDacekb78465d2022-10-18 20:10:16 +0000112 bazelProdMode bool
113 bazelDevMode bool
114 bazelStagingMode bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000115
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700116 // Set by multiproduct_kati
117 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700118
119 metricsUploader string
MarkDacekd06db5d2022-11-29 00:47:59 +0000120
121 bazelForceEnabledModules string
Spandan Dasc5763832022-11-08 18:42:16 +0000122
Sam Delmerico98a73292023-02-21 11:50:29 -0500123 includeTags []string
124 sourceRootDirs []string
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900125
126 // Data source to write ninja weight list
127 ninjaWeightListSource NinjaWeightListSource
Dan Willemsen1e704462016-08-21 15:17:17 -0700128}
129
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900130type NinjaWeightListSource uint
131
132const (
133 // ninja doesn't use weight list.
134 NOT_USED NinjaWeightListSource = iota
135 // ninja uses weight list based on previous builds by ninja log
136 NINJA_LOG
137 // ninja thinks every task has the same weight.
138 EVENLY_DISTRIBUTED
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900139 // ninja uses an external custom weight list
140 EXTERNAL_FILE
Jeongik Chae114e602023-03-19 00:12:39 +0900141 // ninja uses a prioritized module list from Soong
142 HINT_FROM_SOONG
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900143)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800144const srcDirFileCheck = "build/soong/root.bp"
145
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700146var buildFiles = []string{"Android.mk", "Android.bp"}
147
Patrice Arruda13848222019-04-22 17:12:02 -0700148type BuildAction uint
149
150const (
151 // Builds all of the modules and their dependencies of a specified directory, relative to the root
152 // directory of the source tree.
153 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
154
155 // Builds all of the modules and their dependencies of a list of specified directories. All specified
156 // directories are relative to the root directory of the source tree.
157 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700158
159 // Build a list of specified modules. If none was specified, simply build the whole source tree.
160 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700161)
162
163// checkTopDir validates that the current directory is at the root directory of the source tree.
164func checkTopDir(ctx Context) {
165 if _, err := os.Stat(srcDirFileCheck); err != nil {
166 if os.IsNotExist(err) {
167 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
168 }
169 ctx.Fatalln("Error verifying tree state:", err)
170 }
171}
172
Kousik Kumarc8818332023-01-16 16:33:05 +0000173// fetchEnvConfig optionally fetches a configuration file that can then subsequently be
174// loaded into Soong environment to control certain aspects of build behavior (e.g., enabling RBE).
175// If a configuration file already exists on disk, the fetch is run in the background
176// so as to NOT block the rest of the build execution.
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500177func fetchEnvConfig(ctx Context, config *configImpl, envConfigName string) error {
David Goldsmith62243a32022-04-08 13:42:04 +0000178 configName := envConfigName + "." + jsonSuffix
Kousik Kumarc75e1292022-07-07 02:20:51 +0000179 expConfigFetcher := &smpb.ExpConfigFetcher{Filename: &configName}
David Goldsmith62243a32022-04-08 13:42:04 +0000180 defer func() {
181 ctx.Metrics.ExpConfigFetcher(expConfigFetcher)
182 }()
Kousik Kumarc75e1292022-07-07 02:20:51 +0000183 if !config.GoogleProdCredsExist() {
184 status := smpb.ExpConfigFetcher_MISSING_GCERT
185 expConfigFetcher.Status = &status
186 return nil
187 }
David Goldsmith62243a32022-04-08 13:42:04 +0000188
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500189 s, err := os.Stat(configFetcher)
190 if err != nil {
191 if os.IsNotExist(err) {
192 return nil
193 }
194 return err
195 }
196 if s.Mode()&0111 == 0 {
David Goldsmith62243a32022-04-08 13:42:04 +0000197 status := smpb.ExpConfigFetcher_ERROR
198 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500199 return fmt.Errorf("configuration fetcher binary %v is not executable: %v", configFetcher, s.Mode())
200 }
201
Kousik Kumarc8818332023-01-16 16:33:05 +0000202 configExists := false
203 outConfigFilePath := filepath.Join(config.OutDir(), configName)
204 if _, err := os.Stat(outConfigFilePath); err == nil {
205 configExists = true
206 }
207
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500208 tCtx, cancel := context.WithTimeout(ctx, envConfigFetchTimeout)
David Goldsmith62243a32022-04-08 13:42:04 +0000209 fetchStart := time.Now()
210 cmd := exec.CommandContext(tCtx, configFetcher, "-output_config_dir", config.OutDir(),
211 "-output_config_name", configName)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500212 if err := cmd.Start(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000213 status := smpb.ExpConfigFetcher_ERROR
214 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500215 return err
216 }
217
Kousik Kumarc8818332023-01-16 16:33:05 +0000218 fetchCfg := func() error {
219 if err := cmd.Wait(); err != nil {
220 status := smpb.ExpConfigFetcher_ERROR
221 expConfigFetcher.Status = &status
222 return err
223 }
224 fetchEnd := time.Now()
225 expConfigFetcher.Micros = proto.Uint64(uint64(fetchEnd.Sub(fetchStart).Microseconds()))
226 expConfigFetcher.Filename = proto.String(outConfigFilePath)
227
228 if _, err := os.Stat(outConfigFilePath); err != nil {
229 status := smpb.ExpConfigFetcher_NO_CONFIG
230 expConfigFetcher.Status = &status
231 return err
232 }
David Goldsmith62243a32022-04-08 13:42:04 +0000233 status := smpb.ExpConfigFetcher_CONFIG
234 expConfigFetcher.Status = &status
Kousik Kumarc8818332023-01-16 16:33:05 +0000235 return nil
David Goldsmith62243a32022-04-08 13:42:04 +0000236 }
Kousik Kumarc8818332023-01-16 16:33:05 +0000237
238 // If a config file does not exist, wait for the config file to be fetched. Otherwise
239 // fetch the config file in the background and return immediately.
240 if !configExists {
241 defer cancel()
242 return fetchCfg()
243 }
244
245 go func() {
246 defer cancel()
247 if err := fetchCfg(); err != nil {
248 ctx.Verbosef("Failed to fetch config file %v: %v\n", configName, err)
249 }
250 }()
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500251 return nil
252}
253
MarkDacek7901e582023-01-09 19:48:01 +0000254func loadEnvConfig(ctx Context, config *configImpl, bc string) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500255 if bc == "" {
256 return nil
257 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500258
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500259 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500260 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500261 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500262 envConfigDir,
263 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500264 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500265 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
266 envVarsJSON, err := ioutil.ReadFile(cfgFile)
267 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500268 continue
269 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500270 ctx.Verbosef("Loading config file %v\n", cfgFile)
271 var envVars map[string]map[string]string
272 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
273 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
274 continue
275 }
276 for k, v := range envVars["env"] {
277 if os.Getenv(k) != "" {
278 continue
279 }
280 config.environ.Set(k, v)
281 }
282 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
283 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500284 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500285
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500286 return nil
287}
288
Chris Parsonsb6e96902022-10-31 20:08:45 -0400289func defaultBazelProdMode(cfg *configImpl) bool {
MarkDacekd06db5d2022-11-29 00:47:59 +0000290 // Environment flag to disable Bazel for users which experience
Chris Parsonsb6e96902022-10-31 20:08:45 -0400291 // broken bazel-handled builds, or significant performance regressions.
292 if cfg.IsBazelMixedBuildForceDisabled() {
293 return false
294 }
295 // Darwin-host builds are currently untested with Bazel.
296 if runtime.GOOS == "darwin" {
297 return false
298 }
Chris Parsons035e03a2022-11-01 14:25:45 -0400299 return true
Chris Parsonsb6e96902022-10-31 20:08:45 -0400300}
301
MarkDacekd33c2fd2023-05-04 20:40:04 +0000302func UploadOnlyConfig(ctx Context, args ...string) Config {
MarkDacek6614d9c2022-12-07 21:57:38 +0000303 ret := &configImpl{
304 environ: OsEnvironment(),
305 sandboxConfig: &SandboxConfig{},
306 }
MarkDacekd33c2fd2023-05-04 20:40:04 +0000307 ret.parseArgs(ctx, args)
MarkDacek7901e582023-01-09 19:48:01 +0000308 srcDir := absPath(ctx, ".")
309 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
310 if err := loadEnvConfig(ctx, ret, bc); err != nil {
311 ctx.Fatalln("Failed to parse env config files: %v", err)
312 }
313 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
MarkDacek6614d9c2022-12-07 21:57:38 +0000314 return Config{ret}
315}
316
Dan Willemsen1e704462016-08-21 15:17:17 -0700317func NewConfig(ctx Context, args ...string) Config {
318 ret := &configImpl{
Chris Parsonsfddeaff2023-05-17 21:53:34 +0000319 environ: OsEnvironment(),
320 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700321 }
322
Patrice Arruda90109172020-07-28 18:07:27 +0000323 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700324 ret.parallel = runtime.NumCPU() + 2
325 ret.keepGoing = 1
326
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800327 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700328 ret.parseArgs(ctx, args)
Jeongik Chae114e602023-03-19 00:12:39 +0900329
330 if ret.ninjaWeightListSource == HINT_FROM_SOONG {
331 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "true")
332 }
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800333 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700334 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
335 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
336 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800337 outDir := "out"
338 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
339 if wd, err := os.Getwd(); err != nil {
340 ctx.Fatalln("Failed to get working directory:", err)
341 } else {
342 outDir = filepath.Join(baseDir, filepath.Base(wd))
343 }
344 }
345 ret.environ.Set("OUT_DIR", outDir)
346 }
347
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500348 // loadEnvConfig needs to know what the OUT_DIR is, so it should
349 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000350 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
351
352 if bc != "" {
353 if err := fetchEnvConfig(ctx, ret, bc); err != nil {
354 ctx.Verbosef("Failed to fetch config file: %v\n", err)
Kousik Kumarc8818332023-01-16 16:33:05 +0000355 }
356 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000357 ctx.Fatalln("Failed to parse env config files: %v", err)
358 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500359 }
360
Dan Willemsen2d31a442018-10-20 21:33:41 -0700361 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
362 ret.distDir = filepath.Clean(distDir)
363 } else {
364 ret.distDir = filepath.Join(ret.OutDir(), "dist")
365 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700366
Spandan Das05063612021-06-25 01:39:04 +0000367 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
368 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
369 }
370
Dan Willemsen1e704462016-08-21 15:17:17 -0700371 ret.environ.Unset(
372 // We're already using it
373 "USE_SOONG_UI",
374
375 // We should never use GOROOT/GOPATH from the shell environment
376 "GOROOT",
377 "GOPATH",
378
379 // These should only come from Soong, not the environment.
380 "CLANG",
381 "CLANG_CXX",
382 "CCC_CC",
383 "CCC_CXX",
384
385 // Used by the goma compiler wrapper, but should only be set by
386 // gomacc
387 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800388
389 // We handle this above
390 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700391
Dan Willemsen2d31a442018-10-20 21:33:41 -0700392 // This is handled above too, and set for individual commands later
393 "DIST_DIR",
394
Dan Willemsen68a09852017-04-18 13:56:57 -0700395 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000396 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700397 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700398 "DISPLAY",
399 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000400 "JAVAC",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700401 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700402 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700403
404 // Drop make flags
405 "MAKEFLAGS",
406 "MAKELEVEL",
407 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700408
409 // Set in envsetup.sh, reset in makefiles
410 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700411
412 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
413 "ANDROID_BUILD_TOP",
414 "ANDROID_HOST_OUT",
415 "ANDROID_PRODUCT_OUT",
416 "ANDROID_HOST_OUT_TESTCASES",
417 "ANDROID_TARGET_OUT_TESTCASES",
418 "ANDROID_TOOLCHAIN",
419 "ANDROID_TOOLCHAIN_2ND_ARCH",
420 "ANDROID_DEV_SCRIPTS",
421 "ANDROID_EMULATOR_PREBUILTS",
422 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700423 )
424
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400425 if ret.UseGoma() || ret.ForceUseGoma() {
426 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
427 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400428 }
429
Dan Willemsen1e704462016-08-21 15:17:17 -0700430 // Tell python not to spam the source tree with .pyc files.
431 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
432
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400433 tmpDir := absPath(ctx, ret.TempDir())
434 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800435
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700436 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
437 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
438 "llvm-binutils-stable/llvm-symbolizer")
439 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
440
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800441 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700442 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800443
Yu Liu6e13b402021-07-27 14:29:06 -0700444 srcDir := absPath(ctx, ".")
445 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700446 ctx.Println("You are building in a directory whose absolute path contains a space character:")
447 ctx.Println()
448 ctx.Printf("%q\n", srcDir)
449 ctx.Println()
450 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700451 }
452
Yu Liu6e13b402021-07-27 14:29:06 -0700453 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
454
Dan Willemsendb8457c2017-05-12 16:38:17 -0700455 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700456 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
457 ctx.Println()
458 ctx.Printf("%q\n", outDir)
459 ctx.Println()
460 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700461 }
462
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000463 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700464 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
465 ctx.Println()
466 ctx.Printf("%q\n", distDir)
467 ctx.Println()
468 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700469 }
470
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700471 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000472 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
473 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100474 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800475 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700476 javaHome := func() string {
477 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
478 return override
479 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000480 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
481 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 +0100482 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000483 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
484 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
485 }
486 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700487 }()
488 absJavaHome := absPath(ctx, javaHome)
489
Dan Willemsened869522018-01-08 14:58:46 -0800490 ret.configureLocale(ctx)
491
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700492 newPath := []string{filepath.Join(absJavaHome, "bin")}
493 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
494 newPath = append(newPath, path)
495 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100496
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700497 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
498 ret.environ.Set("JAVA_HOME", absJavaHome)
499 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000500 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
501 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100502 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700503 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
504
LaMont Jones52a72432023-03-09 18:19:35 +0000505 if ret.MultitreeBuild() {
506 ret.environ.Set("MULTITREE_BUILD", "true")
507 }
508
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800509 outDir := ret.OutDir()
510 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800511 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800512 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800513 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800514 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800515 }
Colin Cross28f527c2019-11-26 16:19:04 -0800516
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800517 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
518
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400519 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400520 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400521 ret.environ.Set(k, v)
522 }
523 }
524
Jihoon Kang1bff0342023-01-17 20:40:22 +0000525 if ret.BuildFromTextStub() {
526 // TODO(b/271443071): support hidden api check for from-text stub build
527 ret.environ.Set("UNSAFE_DISABLE_HIDDENAPI_FLAGS", "true")
528 }
529
Patrice Arruda83842d72020-12-08 19:42:08 +0000530 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800531 if err := os.RemoveAll(bpd); err != nil {
532 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
533 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000534
Patrice Arruda96850362020-08-11 20:41:11 +0000535 c := Config{ret}
536 storeConfigMetrics(ctx, c)
537 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700538}
539
Patrice Arruda13848222019-04-22 17:12:02 -0700540// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
541// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700542func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
543 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700544}
545
Patrice Arruda96850362020-08-11 20:41:11 +0000546// storeConfigMetrics selects a set of configuration information and store in
547// the metrics system for further analysis.
548func storeConfigMetrics(ctx Context, config Config) {
549 if ctx.Metrics == nil {
550 return
551 }
552
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400553 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000554
555 s := &smpb.SystemResourceInfo{
556 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
557 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
558 }
559 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000560}
561
Jeongik Cha8d63d562023-03-17 03:52:13 +0900562func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900563 switch s {
564 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900565 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900566 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900567 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900568 case EXTERNAL_FILE:
569 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900570 case HINT_FROM_SOONG:
571 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900572 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900573 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900574 }
575}
576
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400577func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700578 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400579 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
580 UseGoma: proto.Bool(config.UseGoma()),
581 UseRbe: proto.Bool(config.UseRBE()),
582 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
583 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900584 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400585 }
Yu Liue737a992021-10-04 13:21:41 -0700586 c.Targets = append(c.Targets, config.arguments...)
587
588 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400589}
590
Patrice Arruda13848222019-04-22 17:12:02 -0700591// getConfigArgs processes the command arguments based on the build action and creates a set of new
592// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700593func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700594 // The next block of code verifies that the current directory is the root directory of the source
595 // tree. It then finds the relative path of dir based on the root directory of the source tree
596 // and verify that dir is inside of the source tree.
597 checkTopDir(ctx)
598 topDir, err := os.Getwd()
599 if err != nil {
600 ctx.Fatalf("Error retrieving top directory: %v", err)
601 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700602 dir, err = filepath.EvalSymlinks(dir)
603 if err != nil {
604 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
605 }
Patrice Arruda13848222019-04-22 17:12:02 -0700606 dir, err = filepath.Abs(dir)
607 if err != nil {
608 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
609 }
610 relDir, err := filepath.Rel(topDir, dir)
611 if err != nil {
612 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
613 }
614 // If there are ".." in the path, it's not in the source tree.
615 if strings.Contains(relDir, "..") {
616 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
617 }
618
619 configArgs := args[:]
620
621 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
622 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
623 targetNamePrefix := "MODULES-IN-"
624 if inList("GET-INSTALL-PATH", configArgs) {
625 targetNamePrefix = "GET-INSTALL-PATH-IN-"
626 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
627 }
628
Patrice Arruda13848222019-04-22 17:12:02 -0700629 var targets []string
630
631 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700632 case BUILD_MODULES:
633 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700634 case BUILD_MODULES_IN_A_DIRECTORY:
635 // If dir is the root source tree, all the modules are built of the source tree are built so
636 // no need to find the build file.
637 if topDir == dir {
638 break
639 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700640
Patrice Arruda13848222019-04-22 17:12:02 -0700641 buildFile := findBuildFile(ctx, relDir)
642 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700643 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700644 }
Patrice Arruda13848222019-04-22 17:12:02 -0700645 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
646 case BUILD_MODULES_IN_DIRECTORIES:
647 newConfigArgs, dirs := splitArgs(configArgs)
648 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700649 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700650 }
651
652 // Tidy only override all other specified targets.
653 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
654 if tidyOnly == "true" || tidyOnly == "1" {
655 configArgs = append(configArgs, "tidy_only")
656 } else {
657 configArgs = append(configArgs, targets...)
658 }
659
660 return configArgs
661}
662
663// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
664func convertToTarget(dir string, targetNamePrefix string) string {
665 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
666}
667
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700668// hasBuildFile returns true if dir contains an Android build file.
669func hasBuildFile(ctx Context, dir string) bool {
670 for _, buildFile := range buildFiles {
671 _, err := os.Stat(filepath.Join(dir, buildFile))
672 if err == nil {
673 return true
674 }
675 if !os.IsNotExist(err) {
676 ctx.Fatalf("Error retrieving the build file stats: %v", err)
677 }
678 }
679 return false
680}
681
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700682// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
683// in the current and any sub directory of dir. If a build file is not found, traverse the path
684// up by one directory and repeat again until either a build file is found or reached to the root
685// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
686// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700687func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700688 // If the string is empty or ".", assume it is top directory of the source tree.
689 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700690 return ""
691 }
692
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700693 found := false
694 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
695 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
696 if err != nil {
697 return err
698 }
699 if found {
700 return filepath.SkipDir
701 }
702 if info.IsDir() {
703 return nil
704 }
705 for _, buildFile := range buildFiles {
706 if info.Name() == buildFile {
707 found = true
708 return filepath.SkipDir
709 }
710 }
711 return nil
712 })
713 if err != nil {
714 ctx.Fatalf("Error finding Android build file: %v", err)
715 }
716
717 if found {
718 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700719 }
720 }
721
722 return ""
723}
724
725// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
726func splitArgs(args []string) (newArgs []string, dirs []string) {
727 specialArgs := map[string]bool{
728 "showcommands": true,
729 "snod": true,
730 "dist": true,
731 "checkbuild": true,
732 }
733
734 newArgs = []string{}
735 dirs = []string{}
736
737 for _, arg := range args {
738 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
739 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
740 newArgs = append(newArgs, arg)
741 continue
742 }
743
744 if _, ok := specialArgs[arg]; ok {
745 newArgs = append(newArgs, arg)
746 continue
747 }
748
749 dirs = append(dirs, arg)
750 }
751
752 return newArgs, dirs
753}
754
755// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
756// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
757// source root tree where the build action command was invoked. Each directory is validated if the
758// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700759func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700760 for _, dir := range dirs {
761 // The directory may have specified specific modules to build. ":" is the separator to separate
762 // the directory and the list of modules.
763 s := strings.Split(dir, ":")
764 l := len(s)
765 if l > 2 { // more than one ":" was specified.
766 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
767 }
768
769 dir = filepath.Join(relDir, s[0])
770 if _, err := os.Stat(dir); err != nil {
771 ctx.Fatalf("couldn't find directory %s", dir)
772 }
773
774 // Verify that if there are any targets specified after ":". Each target is separated by ",".
775 var newTargets []string
776 if l == 2 && s[1] != "" {
777 newTargets = strings.Split(s[1], ",")
778 if inList("", newTargets) {
779 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
780 }
781 }
782
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700783 // If there are specified targets to build in dir, an android build file must exist for the one
784 // shot build. For the non-targets case, find the appropriate build file and build all the
785 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700786 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700787 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700788 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
789 }
790 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700791 buildFile := findBuildFile(ctx, dir)
792 if buildFile == "" {
793 ctx.Fatalf("Build file not found for %s directory", dir)
794 }
795 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700796 }
797
Patrice Arruda13848222019-04-22 17:12:02 -0700798 targets = append(targets, newTargets...)
799 }
800
Dan Willemsence41e942019-07-29 23:39:30 -0700801 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700802}
803
Dan Willemsen9b587492017-07-10 22:13:00 -0700804func (c *configImpl) parseArgs(ctx Context, args []string) {
805 for i := 0; i < len(args); i++ {
806 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100807 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700808 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200809 } else if arg == "--empty-ninja-file" {
810 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100811 } else if arg == "--skip-ninja" {
812 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700813 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700814 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
815 // but it does run a Kati ninja file if the .kati_enabled marker file was created
816 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000817 c.skipConfig = true
818 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100819 } else if arg == "--soong-only" {
820 c.skipKati = true
821 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200822 } else if arg == "--config-only" {
823 c.skipKati = true
824 c.skipKatiNinja = true
825 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700826 } else if arg == "--skip-config" {
827 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700828 } else if arg == "--skip-soong-tests" {
829 c.skipSoongTests = true
MarkDacekd0e7cd32022-12-02 22:22:40 +0000830 } else if arg == "--skip-metrics-upload" {
831 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500832 } else if arg == "--mk-metrics" {
833 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000834 } else if arg == "--multitree-build" {
835 c.multitreeBuild = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400836 } else if arg == "--bazel-mode" {
837 c.bazelProdMode = true
838 } else if arg == "--bazel-mode-dev" {
839 c.bazelDevMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000840 } else if arg == "--bazel-mode-staging" {
841 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000842 } else if arg == "--search-api-dir" {
843 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900844 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
845 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
846 if source == "ninja_log" {
847 c.ninjaWeightListSource = NINJA_LOG
848 } else if source == "evenly_distributed" {
849 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
850 } else if source == "not_used" {
851 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900852 } else if source == "soong" {
853 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900854 } else if strings.HasPrefix(source, "file,") {
855 c.ninjaWeightListSource = EXTERNAL_FILE
856 filePath := strings.TrimPrefix(source, "file,")
857 err := validateNinjaWeightList(filePath)
858 if err != nil {
859 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
860 }
861 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
862 if err != nil {
863 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
864 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900865 } else {
866 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
867 }
Jihoon Kang1bff0342023-01-17 20:40:22 +0000868 } else if arg == "--build-from-text-stub" {
869 c.buildFromTextStub = true
MarkDacekb96561e2022-12-02 04:34:43 +0000870 } else if strings.HasPrefix(arg, "--build-command=") {
871 buildCmd := strings.TrimPrefix(arg, "--build-command=")
872 // remove quotations
873 buildCmd = strings.TrimPrefix(buildCmd, "\"")
874 buildCmd = strings.TrimSuffix(buildCmd, "\"")
875 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000876 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
877 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
MarkDacek6614d9c2022-12-07 21:57:38 +0000878 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
879 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
880 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
881 if err == nil {
882 c.buildStartedTime = val
883 } else {
884 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
885 }
MarkDacekf47e1422023-04-19 16:47:36 +0000886 } else if arg == "--ensure-allowlist-integrity" {
887 c.ensureAllowlistIntegrity = true
MarkDacekd33c2fd2023-05-04 20:40:04 +0000888 } else if strings.HasPrefix(arg, "--bazel-exit-code=") {
889 bazelExitCodeStr := strings.TrimPrefix(arg, "--bazel-exit-code=")
890 val, err := strconv.Atoi(bazelExitCodeStr)
891 if err == nil {
892 c.bazelExitCode = int32(val)
893 } else {
894 ctx.Fatalf("Error parsing bazel-exit-code", err)
895 }
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700896 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700897 parseArgNum := func(def int) int {
898 if len(arg) > 2 {
899 p, err := strconv.ParseUint(arg[2:], 10, 31)
900 if err != nil {
901 ctx.Fatalf("Failed to parse %q: %v", arg, err)
902 }
903 return int(p)
904 } else if i+1 < len(args) {
905 p, err := strconv.ParseUint(args[i+1], 10, 31)
906 if err == nil {
907 i++
908 return int(p)
909 }
910 }
911 return def
912 }
913
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700914 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700915 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700916 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700917 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700918 } else {
919 ctx.Fatalln("Unknown option:", arg)
920 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700921 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700922 if k == "OUT_DIR" {
923 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
924 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700925 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700926 } else if arg == "dist" {
927 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200928 } else if arg == "json-module-graph" {
929 c.jsonModuleGraph = true
930 } else if arg == "bp2build" {
931 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000932 } else if arg == "api_bp2build" {
933 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200934 } else if arg == "queryview" {
935 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200936 } else if arg == "soong_docs" {
937 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700938 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700939 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800940 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700941 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700942 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700943 }
944 }
Chris Parsonsb6e96902022-10-31 20:08:45 -0400945 if (!c.bazelProdMode) && (!c.bazelDevMode) && (!c.bazelStagingMode) {
946 c.bazelProdMode = defaultBazelProdMode(c)
947 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700948}
949
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900950func validateNinjaWeightList(weightListFilePath string) (err error) {
951 data, err := os.ReadFile(weightListFilePath)
952 if err != nil {
953 return
954 }
955 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
956 for _, line := range lines {
957 fields := strings.Split(line, ",")
958 if len(fields) != 2 {
959 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
960 }
961 _, err = strconv.Atoi(fields[1])
962 if err != nil {
963 return
964 }
965 }
966 return
967}
968
Dan Willemsened869522018-01-08 14:58:46 -0800969func (c *configImpl) configureLocale(ctx Context) {
970 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
971 output, err := cmd.Output()
972
973 var locales []string
974 if err == nil {
975 locales = strings.Split(string(output), "\n")
976 } else {
977 // If we're unable to list the locales, let's assume en_US.UTF-8
978 locales = []string{"en_US.UTF-8"}
979 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
980 }
981
982 // gettext uses LANGUAGE, which is passed directly through
983
984 // For LANG and LC_*, only preserve the evaluated version of
985 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800986 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800987 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800988 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800989 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800990 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800991 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800992 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800993 }
994
995 c.environ.UnsetWithPrefix("LC_")
996
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800997 if userLang != "" {
998 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800999 }
1000
1001 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
1002 // for others)
1003 if inList("C.UTF-8", locales) {
1004 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -05001005 } else if inList("C.utf8", locales) {
1006 // These normalize to the same thing
1007 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -08001008 } else if inList("en_US.UTF-8", locales) {
1009 c.environ.Set("LANG", "en_US.UTF-8")
1010 } else if inList("en_US.utf8", locales) {
1011 // These normalize to the same thing
1012 c.environ.Set("LANG", "en_US.UTF-8")
1013 } else {
1014 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
1015 }
1016}
1017
Dan Willemsen1e704462016-08-21 15:17:17 -07001018func (c *configImpl) Environment() *Environment {
1019 return c.environ
1020}
1021
1022func (c *configImpl) Arguments() []string {
1023 return c.arguments
1024}
1025
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001026func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001027 if len(c.Arguments()) > 0 {
1028 // Explicit targets requested that are not special targets like b2pbuild
1029 // or the JSON module graph
1030 return true
1031 }
1032
Spandan Das5af0bd32022-09-28 20:43:08 +00001033 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001034 // Command line was empty, the default Ninja target is built
1035 return true
1036 }
1037
Liz Kammer88677422021-12-15 15:03:19 -05001038 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
1039 if c.Dist() && !c.Bp2Build() {
1040 return true
1041 }
1042
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001043 // build.ninja doesn't need to be generated
1044 return false
1045}
1046
Dan Willemsen1e704462016-08-21 15:17:17 -07001047func (c *configImpl) OutDir() string {
1048 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -07001049 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -07001050 }
1051 return "out"
1052}
1053
Dan Willemsen8a073a82017-02-04 17:30:44 -08001054func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -04001055 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001056}
1057
1058func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -07001059 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -08001060}
1061
Dan Willemsen1e704462016-08-21 15:17:17 -07001062func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001063 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001064 return c.arguments
1065 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001066 return c.ninjaArgs
1067}
1068
Jingwen Chen7c6089a2020-11-02 02:56:20 -05001069func (c *configImpl) BazelOutDir() string {
1070 return filepath.Join(c.OutDir(), "bazel")
1071}
1072
Liz Kammer2af5ea82022-11-11 14:21:03 -05001073func (c *configImpl) bazelOutputBase() string {
1074 return filepath.Join(c.BazelOutDir(), "output")
1075}
1076
Dan Willemsen1e704462016-08-21 15:17:17 -07001077func (c *configImpl) SoongOutDir() string {
1078 return filepath.Join(c.OutDir(), "soong")
1079}
1080
Spandan Das394aa322022-11-03 17:02:10 +00001081func (c *configImpl) ApiSurfacesOutDir() string {
1082 return filepath.Join(c.OutDir(), "api_surfaces")
1083}
1084
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001085func (c *configImpl) PrebuiltOS() string {
1086 switch runtime.GOOS {
1087 case "linux":
1088 return "linux-x86"
1089 case "darwin":
1090 return "darwin-x86"
1091 default:
1092 panic("Unknown GOOS")
1093 }
1094}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001095
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001096func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001097 if c.SkipKatiNinja() {
1098 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1099 } else {
1100 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1101 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001102}
1103
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001104func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001105 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001106}
1107
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001108func (c *configImpl) UsedEnvFile(tag string) string {
1109 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1110}
1111
Lukacs T. Berkic541cd22022-10-26 07:26:50 +00001112func (c *configImpl) Bp2BuildFilesMarkerFile() string {
1113 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
1114}
1115
1116func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001117 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +02001118}
1119
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001120func (c *configImpl) SoongDocsHtml() string {
1121 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1122}
1123
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001124func (c *configImpl) QueryviewMarkerFile() string {
1125 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1126}
1127
Spandan Das5af0bd32022-09-28 20:43:08 +00001128func (c *configImpl) ApiBp2buildMarkerFile() string {
1129 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
1130}
1131
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001132func (c *configImpl) ModuleGraphFile() string {
1133 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1134}
1135
kgui67007242022-01-25 13:50:25 +08001136func (c *configImpl) ModuleActionsFile() string {
1137 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1138}
1139
Jeff Gastonefc1b412017-03-29 17:29:06 -07001140func (c *configImpl) TempDir() string {
1141 return shared.TempDirForOutDir(c.SoongOutDir())
1142}
1143
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001144func (c *configImpl) FileListDir() string {
1145 return filepath.Join(c.OutDir(), ".module_paths")
1146}
1147
Dan Willemsen1e704462016-08-21 15:17:17 -07001148func (c *configImpl) KatiSuffix() string {
1149 if c.katiSuffix != "" {
1150 return c.katiSuffix
1151 }
1152 panic("SetKatiSuffix has not been called")
1153}
1154
Colin Cross37193492017-11-16 17:55:00 -08001155// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1156// user is interested in additional checks at the expense of build time.
1157func (c *configImpl) Checkbuild() bool {
1158 return c.checkbuild
1159}
1160
Dan Willemsen8a073a82017-02-04 17:30:44 -08001161func (c *configImpl) Dist() bool {
1162 return c.dist
1163}
1164
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001165func (c *configImpl) JsonModuleGraph() bool {
1166 return c.jsonModuleGraph
1167}
1168
1169func (c *configImpl) Bp2Build() bool {
1170 return c.bp2build
1171}
1172
Spandan Das5af0bd32022-09-28 20:43:08 +00001173func (c *configImpl) ApiBp2build() bool {
1174 return c.apiBp2build
1175}
1176
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001177func (c *configImpl) Queryview() bool {
1178 return c.queryview
1179}
1180
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001181func (c *configImpl) SoongDocs() bool {
1182 return c.soongDocs
1183}
1184
Dan Willemsen1e704462016-08-21 15:17:17 -07001185func (c *configImpl) IsVerbose() bool {
1186 return c.verbose
1187}
1188
LaMont Jones52a72432023-03-09 18:19:35 +00001189func (c *configImpl) MultitreeBuild() bool {
1190 return c.multitreeBuild
1191}
1192
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001193func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1194 return c.ninjaWeightListSource
1195}
1196
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001197func (c *configImpl) SkipKati() bool {
1198 return c.skipKati
1199}
1200
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001201func (c *configImpl) SkipKatiNinja() bool {
1202 return c.skipKatiNinja
1203}
1204
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001205func (c *configImpl) SkipSoong() bool {
1206 return c.skipSoong
1207}
1208
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001209func (c *configImpl) SkipNinja() bool {
1210 return c.skipNinja
1211}
1212
Anton Hansson5a7861a2021-06-04 10:09:01 +01001213func (c *configImpl) SetSkipNinja(v bool) {
1214 c.skipNinja = v
1215}
1216
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001217func (c *configImpl) SkipConfig() bool {
1218 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001219}
1220
Jihoon Kang1bff0342023-01-17 20:40:22 +00001221func (c *configImpl) BuildFromTextStub() bool {
1222 return c.buildFromTextStub
1223}
1224
Dan Willemsen1e704462016-08-21 15:17:17 -07001225func (c *configImpl) TargetProduct() string {
1226 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1227 return v
1228 }
1229 panic("TARGET_PRODUCT is not defined")
1230}
1231
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001232func (c *configImpl) TargetProductOrErr() (string, error) {
1233 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1234 return v, nil
1235 }
1236 return "", fmt.Errorf("TARGET_PRODUCT is not defined")
1237}
1238
Dan Willemsen02781d52017-05-12 19:28:13 -07001239func (c *configImpl) TargetDevice() string {
1240 return c.targetDevice
1241}
1242
1243func (c *configImpl) SetTargetDevice(device string) {
1244 c.targetDevice = device
1245}
1246
1247func (c *configImpl) TargetBuildVariant() string {
1248 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1249 return v
1250 }
1251 panic("TARGET_BUILD_VARIANT is not defined")
1252}
1253
Dan Willemsen1e704462016-08-21 15:17:17 -07001254func (c *configImpl) KatiArgs() []string {
1255 return c.katiArgs
1256}
1257
1258func (c *configImpl) Parallel() int {
1259 return c.parallel
1260}
1261
Sam Delmerico98a73292023-02-21 11:50:29 -05001262func (c *configImpl) GetSourceRootDirs() []string {
1263 return c.sourceRootDirs
1264}
1265
1266func (c *configImpl) SetSourceRootDirs(i []string) {
1267 c.sourceRootDirs = i
1268}
1269
Spandan Dasc5763832022-11-08 18:42:16 +00001270func (c *configImpl) GetIncludeTags() []string {
1271 return c.includeTags
1272}
1273
1274func (c *configImpl) SetIncludeTags(i []string) {
1275 c.includeTags = i
1276}
1277
MarkDacek6614d9c2022-12-07 21:57:38 +00001278func (c *configImpl) GetLogsPrefix() string {
1279 return c.logsPrefix
1280}
1281
1282func (c *configImpl) SetLogsPrefix(prefix string) {
1283 c.logsPrefix = prefix
1284}
1285
Colin Cross8b8bec32019-11-15 13:18:43 -08001286func (c *configImpl) HighmemParallel() int {
1287 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1288 return i
1289 }
1290
1291 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1292 parallel := c.Parallel()
1293 if c.UseRemoteBuild() {
1294 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1295 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1296 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1297 // Return 1/16th of the size of the local pool, rounding up.
1298 return (parallel + 15) / 16
1299 } else if c.totalRAM == 0 {
1300 // Couldn't detect the total RAM, don't restrict highmem processes.
1301 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001302 } else if c.totalRAM <= 16*1024*1024*1024 {
1303 // Less than 16GB of ram, restrict to 1 highmem processes
1304 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001305 } else if c.totalRAM <= 32*1024*1024*1024 {
1306 // Less than 32GB of ram, restrict to 2 highmem processes
1307 return 2
1308 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1309 // If less than 8GB total RAM per process, reduce the number of highmem processes
1310 return p
1311 }
1312 // No restriction on highmem processes
1313 return parallel
1314}
1315
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001316func (c *configImpl) TotalRAM() uint64 {
1317 return c.totalRAM
1318}
1319
Kousik Kumarec478642020-09-21 13:39:24 -04001320// ForceUseGoma determines whether we should override Goma deprecation
1321// and use Goma for the current build or not.
1322func (c *configImpl) ForceUseGoma() bool {
1323 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1324 v = strings.TrimSpace(v)
1325 if v != "" && v != "false" {
1326 return true
1327 }
1328 }
1329 return false
1330}
1331
Dan Willemsen1e704462016-08-21 15:17:17 -07001332func (c *configImpl) UseGoma() bool {
1333 if v, ok := c.environ.Get("USE_GOMA"); ok {
1334 v = strings.TrimSpace(v)
1335 if v != "" && v != "false" {
1336 return true
1337 }
1338 }
1339 return false
1340}
1341
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001342func (c *configImpl) StartGoma() bool {
1343 if !c.UseGoma() {
1344 return false
1345 }
1346
1347 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1348 v = strings.TrimSpace(v)
1349 if v != "" && v != "false" {
1350 return false
1351 }
1352 }
1353 return true
1354}
1355
Ramy Medhatbbf25672019-07-17 12:30:04 +00001356func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001357 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001358 v = strings.TrimSpace(v)
1359 if v != "" && v != "false" {
1360 return true
1361 }
1362 }
1363 return false
1364}
1365
Chris Parsonsef615e52022-08-18 22:04:11 -04001366func (c *configImpl) BazelBuildEnabled() bool {
MarkDacekb78465d2022-10-18 20:10:16 +00001367 return c.bazelProdMode || c.bazelDevMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001368}
1369
Ramy Medhatbbf25672019-07-17 12:30:04 +00001370func (c *configImpl) StartRBE() bool {
1371 if !c.UseRBE() {
1372 return false
1373 }
1374
1375 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1376 v = strings.TrimSpace(v)
1377 if v != "" && v != "false" {
1378 return false
1379 }
1380 }
1381 return true
1382}
1383
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001384func (c *configImpl) rbeProxyLogsDir() string {
1385 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001386 if v, ok := c.environ.Get(f); ok {
1387 return v
1388 }
1389 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001390 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1391 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001392}
1393
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001394func (c *configImpl) rbeCacheDir() string {
1395 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1396 if v, ok := c.environ.Get(f); ok {
1397 return v
1398 }
1399 }
1400 return shared.JoinPath(c.SoongOutDir(), "rbe")
1401}
1402
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001403func (c *configImpl) shouldCleanupRBELogsDir() bool {
1404 // Perform a log directory cleanup only when the log directory
1405 // is auto created by the build rather than user-specified.
1406 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1407 if _, ok := c.environ.Get(f); ok {
1408 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001409 }
1410 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001411 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001412}
1413
1414func (c *configImpl) rbeExecRoot() string {
1415 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1416 if v, ok := c.environ.Get(f); ok {
1417 return v
1418 }
1419 }
1420 wd, err := os.Getwd()
1421 if err != nil {
1422 return ""
1423 }
1424 return wd
1425}
1426
1427func (c *configImpl) rbeDir() string {
1428 if v, ok := c.environ.Get("RBE_DIR"); ok {
1429 return v
1430 }
1431 return "prebuilts/remoteexecution-client/live/"
1432}
1433
1434func (c *configImpl) rbeReproxy() string {
1435 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1436 if v, ok := c.environ.Get(f); ok {
1437 return v
1438 }
1439 }
1440 return filepath.Join(c.rbeDir(), "reproxy")
1441}
1442
1443func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001444 credFlags := []string{
1445 "use_application_default_credentials",
1446 "use_gce_credentials",
1447 "credential_file",
1448 "use_google_prod_creds",
1449 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001450 for _, cf := range credFlags {
1451 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1452 if v, ok := c.environ.Get(f); ok {
1453 v = strings.TrimSpace(v)
1454 if v != "" && v != "false" && v != "0" {
1455 return "RBE_" + cf, v
1456 }
1457 }
1458 }
1459 }
1460 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001461}
1462
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001463func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1464 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1465 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1466
1467 name := filepath.Join(dir, base)
1468 if len(name) < maxNameLen {
1469 return name, nil
1470 }
1471
1472 name = filepath.Join("/tmp", base)
1473 if len(name) < maxNameLen {
1474 return name, nil
1475 }
1476
1477 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1478}
1479
Kousik Kumar7bc78192022-04-27 14:52:56 -04001480// IsGooglerEnvironment returns true if the current build is running
1481// on a Google developer machine and false otherwise.
1482func (c *configImpl) IsGooglerEnvironment() bool {
1483 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1484 if v, ok := c.environ.Get(cf); ok {
1485 return v == "googler"
1486 }
1487 return false
1488}
1489
1490// GoogleProdCredsExist determine whether credentials exist on the
1491// Googler machine to use remote execution.
1492func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001493 if googleProdCredsExistCache {
1494 return googleProdCredsExistCache
1495 }
Kousik Kumar7bc78192022-04-27 14:52:56 -04001496 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1497 return false
1498 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001499 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001500 return true
1501}
1502
1503// UseRemoteBuild indicates whether to use a remote build acceleration system
1504// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001505func (c *configImpl) UseRemoteBuild() bool {
1506 return c.UseGoma() || c.UseRBE()
1507}
1508
Kousik Kumar7bc78192022-04-27 14:52:56 -04001509// StubbyExists checks whether the stubby binary exists on the machine running
1510// the build.
1511func (c *configImpl) StubbyExists() bool {
1512 if _, err := exec.LookPath("stubby"); err != nil {
1513 return false
1514 }
1515 return true
1516}
1517
Dan Willemsen1e704462016-08-21 15:17:17 -07001518// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001519// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001520// still limited by Parallel()
1521func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001522 if !c.UseRemoteBuild() {
1523 return 0
1524 }
1525 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1526 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001527 }
1528 return 500
1529}
1530
1531func (c *configImpl) SetKatiArgs(args []string) {
1532 c.katiArgs = args
1533}
1534
1535func (c *configImpl) SetNinjaArgs(args []string) {
1536 c.ninjaArgs = args
1537}
1538
1539func (c *configImpl) SetKatiSuffix(suffix string) {
1540 c.katiSuffix = suffix
1541}
1542
Dan Willemsene0879fc2017-08-04 15:06:27 -07001543func (c *configImpl) LastKatiSuffixFile() string {
1544 return filepath.Join(c.OutDir(), "last_kati_suffix")
1545}
1546
1547func (c *configImpl) HasKatiSuffix() bool {
1548 return c.katiSuffix != ""
1549}
1550
Dan Willemsen1e704462016-08-21 15:17:17 -07001551func (c *configImpl) KatiEnvFile() string {
1552 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1553}
1554
Dan Willemsen29971232018-09-26 14:58:30 -07001555func (c *configImpl) KatiBuildNinjaFile() string {
1556 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001557}
1558
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001559func (c *configImpl) KatiPackageNinjaFile() string {
1560 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1561}
1562
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001563func (c *configImpl) SoongVarsFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001564 targetProduct, err := c.TargetProductOrErr()
1565 if err != nil {
1566 return filepath.Join(c.SoongOutDir(), "soong.variables")
1567 } else {
1568 return filepath.Join(c.SoongOutDir(), "soong."+targetProduct+".variables")
1569 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001570}
1571
Dan Willemsen1e704462016-08-21 15:17:17 -07001572func (c *configImpl) SoongNinjaFile() string {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +09001573 targetProduct, err := c.TargetProductOrErr()
1574 if err != nil {
1575 return filepath.Join(c.SoongOutDir(), "build.ninja")
1576 } else {
1577 return filepath.Join(c.SoongOutDir(), "build."+targetProduct+".ninja")
1578 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001579}
1580
1581func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001582 if c.katiSuffix == "" {
1583 return filepath.Join(c.OutDir(), "combined.ninja")
1584 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001585 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1586}
1587
1588func (c *configImpl) SoongAndroidMk() string {
1589 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1590}
1591
1592func (c *configImpl) SoongMakeVarsMk() string {
1593 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1594}
1595
Dan Willemsenf052f782017-05-18 15:29:04 -07001596func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001597 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001598}
1599
Dan Willemsen02781d52017-05-12 19:28:13 -07001600func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001601 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1602}
1603
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001604func (c *configImpl) KatiPackageMkDir() string {
1605 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1606}
1607
Dan Willemsenf052f782017-05-18 15:29:04 -07001608func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001609 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001610}
1611
1612func (c *configImpl) HostOut() string {
1613 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1614}
1615
1616// This probably needs to be multi-valued, so not exporting it for now
1617func (c *configImpl) hostCrossOut() string {
1618 if runtime.GOOS == "linux" {
1619 return filepath.Join(c.hostOutRoot(), "windows-x86")
1620 } else {
1621 return ""
1622 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001623}
1624
Dan Willemsen1e704462016-08-21 15:17:17 -07001625func (c *configImpl) HostPrebuiltTag() string {
1626 if runtime.GOOS == "linux" {
1627 return "linux-x86"
1628 } else if runtime.GOOS == "darwin" {
1629 return "darwin-x86"
1630 } else {
1631 panic("Unsupported OS")
1632 }
1633}
Dan Willemsenf173d592017-04-27 14:28:00 -07001634
Dan Willemsen8122bd52017-10-12 20:20:41 -07001635func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001636 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1637 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001638 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1639 if _, err := os.Stat(asan); err == nil {
1640 return asan
1641 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001642 }
1643 }
1644 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1645}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001646
1647func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1648 c.brokenDupRules = val
1649}
1650
1651func (c *configImpl) BuildBrokenDupRules() bool {
1652 return c.brokenDupRules
1653}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001654
Dan Willemsen25e6f092019-04-09 10:22:43 -07001655func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1656 c.brokenUsesNetwork = val
1657}
1658
1659func (c *configImpl) BuildBrokenUsesNetwork() bool {
1660 return c.brokenUsesNetwork
1661}
1662
Dan Willemsene3336352020-01-02 19:10:38 -08001663func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1664 c.brokenNinjaEnvVars = val
1665}
1666
1667func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1668 return c.brokenNinjaEnvVars
1669}
1670
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001671func (c *configImpl) SetTargetDeviceDir(dir string) {
1672 c.targetDeviceDir = dir
1673}
1674
1675func (c *configImpl) TargetDeviceDir() string {
1676 return c.targetDeviceDir
1677}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001678
Patrice Arruda219eef32020-06-01 17:29:30 +00001679func (c *configImpl) BuildDateTime() string {
1680 return c.buildDateTime
1681}
1682
1683func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001684 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001685}
Patrice Arruda83842d72020-12-08 19:42:08 +00001686
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001687// LogsDir returns the absolute path to the logs directory where build log and
1688// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001689// directory. If the argument dist is specified, the logs directory
1690// is <dist_dir>/logs.
1691func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001692 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001693 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001694 // 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 -05001695 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001696 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001697 absDir, err := filepath.Abs(dir)
1698 if err != nil {
1699 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1700 os.Exit(1)
1701 }
1702 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001703}
1704
1705// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1706// where the bazel profiles are located.
1707func (c *configImpl) BazelMetricsDir() string {
1708 return filepath.Join(c.LogsDir(), "bazel_metrics")
1709}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001710
Chris Parsons53f68ae2022-03-03 12:01:40 -05001711// MkFileMetrics returns the file path for make-related metrics.
1712func (c *configImpl) MkMetrics() string {
1713 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1714}
1715
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001716func (c *configImpl) SetEmptyNinjaFile(v bool) {
1717 c.emptyNinjaFile = v
1718}
1719
1720func (c *configImpl) EmptyNinjaFile() bool {
1721 return c.emptyNinjaFile
1722}
Yu Liu6e13b402021-07-27 14:29:06 -07001723
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001724func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1725 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1726}
1727
Chris Parsons9402ca82023-02-23 17:28:06 -05001728func (c *configImpl) IsPersistentBazelEnabled() bool {
1729 return c.Environment().IsEnvTrue("USE_PERSISTENT_BAZEL")
1730}
1731
MarkDacekd06db5d2022-11-29 00:47:59 +00001732func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1733 return c.bazelForceEnabledModules
1734}
1735
MarkDacekd0e7cd32022-12-02 22:22:40 +00001736func (c *configImpl) SkipMetricsUpload() bool {
1737 return c.skipMetricsUpload
1738}
1739
MarkDacekf47e1422023-04-19 16:47:36 +00001740func (c *configImpl) EnsureAllowlistIntegrity() bool {
1741 return c.ensureAllowlistIntegrity
1742}
1743
MarkDacek6614d9c2022-12-07 21:57:38 +00001744// Returns a Time object if one was passed via a command-line flag.
1745// Otherwise returns the passed default.
1746func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1747 if c.buildStartedTime == 0 {
1748 return defaultTime
1749 }
1750 return time.UnixMilli(c.buildStartedTime)
1751}
1752
MarkDacekd33c2fd2023-05-04 20:40:04 +00001753func (c *configImpl) BazelExitCode() int32 {
1754 return c.bazelExitCode
1755}
1756
Yu Liu6e13b402021-07-27 14:29:06 -07001757func GetMetricsUploader(topDir string, env *Environment) string {
1758 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1759 metricsUploader := filepath.Join(topDir, p)
1760 if _, err := os.Stat(metricsUploader); err == nil {
1761 return metricsUploader
1762 }
1763 }
1764
1765 return ""
1766}