blob: 6b6ce7154fc4088f137d5dfb74357b83a99ccab6 [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{
Jeongik Chaf5c872f2023-04-14 00:17:47 +0900319 environ: OsEnvironment(),
320 sandboxConfig: &SandboxConfig{},
321 ninjaWeightListSource: HINT_FROM_SOONG,
Dan Willemsen1e704462016-08-21 15:17:17 -0700322 }
323
Patrice Arruda90109172020-07-28 18:07:27 +0000324 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700325 ret.parallel = runtime.NumCPU() + 2
326 ret.keepGoing = 1
327
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800328 ret.totalRAM = detectTotalRAM(ctx)
Dan Willemsen9b587492017-07-10 22:13:00 -0700329 ret.parseArgs(ctx, args)
Jeongik Chae114e602023-03-19 00:12:39 +0900330
331 if ret.ninjaWeightListSource == HINT_FROM_SOONG {
332 ret.environ.Set("SOONG_GENERATES_NINJA_HINT", "true")
333 }
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800334 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700335 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
336 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
337 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800338 outDir := "out"
339 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
340 if wd, err := os.Getwd(); err != nil {
341 ctx.Fatalln("Failed to get working directory:", err)
342 } else {
343 outDir = filepath.Join(baseDir, filepath.Base(wd))
344 }
345 }
346 ret.environ.Set("OUT_DIR", outDir)
347 }
348
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500349 // loadEnvConfig needs to know what the OUT_DIR is, so it should
350 // be called after we determine the appropriate out directory.
MarkDacek7901e582023-01-09 19:48:01 +0000351 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
352
353 if bc != "" {
354 if err := fetchEnvConfig(ctx, ret, bc); err != nil {
355 ctx.Verbosef("Failed to fetch config file: %v\n", err)
Kousik Kumarc8818332023-01-16 16:33:05 +0000356 }
357 if err := loadEnvConfig(ctx, ret, bc); err != nil {
MarkDacek7901e582023-01-09 19:48:01 +0000358 ctx.Fatalln("Failed to parse env config files: %v", err)
359 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500360 }
361
Dan Willemsen2d31a442018-10-20 21:33:41 -0700362 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
363 ret.distDir = filepath.Clean(distDir)
364 } else {
365 ret.distDir = filepath.Join(ret.OutDir(), "dist")
366 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700367
Spandan Das05063612021-06-25 01:39:04 +0000368 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
369 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
370 }
371
Dan Willemsen1e704462016-08-21 15:17:17 -0700372 ret.environ.Unset(
373 // We're already using it
374 "USE_SOONG_UI",
375
376 // We should never use GOROOT/GOPATH from the shell environment
377 "GOROOT",
378 "GOPATH",
379
380 // These should only come from Soong, not the environment.
381 "CLANG",
382 "CLANG_CXX",
383 "CCC_CC",
384 "CCC_CXX",
385
386 // Used by the goma compiler wrapper, but should only be set by
387 // gomacc
388 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800389
390 // We handle this above
391 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700392
Dan Willemsen2d31a442018-10-20 21:33:41 -0700393 // This is handled above too, and set for individual commands later
394 "DIST_DIR",
395
Dan Willemsen68a09852017-04-18 13:56:57 -0700396 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000397 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700398 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700399 "DISPLAY",
400 "GREP_OPTIONS",
Nathan Egge7b067fb2023-02-17 17:54:31 +0000401 "JAVAC",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700402 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700403 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700404
405 // Drop make flags
406 "MAKEFLAGS",
407 "MAKELEVEL",
408 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700409
410 // Set in envsetup.sh, reset in makefiles
411 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700412
413 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
414 "ANDROID_BUILD_TOP",
415 "ANDROID_HOST_OUT",
416 "ANDROID_PRODUCT_OUT",
417 "ANDROID_HOST_OUT_TESTCASES",
418 "ANDROID_TARGET_OUT_TESTCASES",
419 "ANDROID_TOOLCHAIN",
420 "ANDROID_TOOLCHAIN_2ND_ARCH",
421 "ANDROID_DEV_SCRIPTS",
422 "ANDROID_EMULATOR_PREBUILTS",
423 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700424 )
425
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400426 if ret.UseGoma() || ret.ForceUseGoma() {
427 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
428 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400429 }
430
Dan Willemsen1e704462016-08-21 15:17:17 -0700431 // Tell python not to spam the source tree with .pyc files.
432 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
433
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400434 tmpDir := absPath(ctx, ret.TempDir())
435 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800436
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700437 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
438 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
439 "llvm-binutils-stable/llvm-symbolizer")
440 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
441
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800442 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700443 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800444
Yu Liu6e13b402021-07-27 14:29:06 -0700445 srcDir := absPath(ctx, ".")
446 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700447 ctx.Println("You are building in a directory whose absolute path contains a space character:")
448 ctx.Println()
449 ctx.Printf("%q\n", srcDir)
450 ctx.Println()
451 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700452 }
453
Yu Liu6e13b402021-07-27 14:29:06 -0700454 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
455
Dan Willemsendb8457c2017-05-12 16:38:17 -0700456 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700457 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
458 ctx.Println()
459 ctx.Printf("%q\n", outDir)
460 ctx.Println()
461 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700462 }
463
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000464 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700465 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
466 ctx.Println()
467 ctx.Printf("%q\n", distDir)
468 ctx.Println()
469 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700470 }
471
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700472 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000473 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
474 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100475 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800476 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700477 javaHome := func() string {
478 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
479 return override
480 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000481 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
482 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 +0100483 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000484 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
485 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
486 }
487 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700488 }()
489 absJavaHome := absPath(ctx, javaHome)
490
Dan Willemsened869522018-01-08 14:58:46 -0800491 ret.configureLocale(ctx)
492
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700493 newPath := []string{filepath.Join(absJavaHome, "bin")}
494 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
495 newPath = append(newPath, path)
496 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100497
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700498 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
499 ret.environ.Set("JAVA_HOME", absJavaHome)
500 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000501 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
502 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100503 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700504 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
505
LaMont Jones52a72432023-03-09 18:19:35 +0000506 if ret.MultitreeBuild() {
507 ret.environ.Set("MULTITREE_BUILD", "true")
508 }
509
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800510 outDir := ret.OutDir()
511 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800512 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800513 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800514 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800515 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800516 }
Colin Cross28f527c2019-11-26 16:19:04 -0800517
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800518 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
519
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400520 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400521 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400522 ret.environ.Set(k, v)
523 }
524 }
525
Jihoon Kang1bff0342023-01-17 20:40:22 +0000526 if ret.BuildFromTextStub() {
527 // TODO(b/271443071): support hidden api check for from-text stub build
528 ret.environ.Set("UNSAFE_DISABLE_HIDDENAPI_FLAGS", "true")
529 }
530
Patrice Arruda83842d72020-12-08 19:42:08 +0000531 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800532 if err := os.RemoveAll(bpd); err != nil {
533 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
534 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000535
Patrice Arruda96850362020-08-11 20:41:11 +0000536 c := Config{ret}
537 storeConfigMetrics(ctx, c)
538 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700539}
540
Patrice Arruda13848222019-04-22 17:12:02 -0700541// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
542// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700543func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
544 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700545}
546
Patrice Arruda96850362020-08-11 20:41:11 +0000547// storeConfigMetrics selects a set of configuration information and store in
548// the metrics system for further analysis.
549func storeConfigMetrics(ctx Context, config Config) {
550 if ctx.Metrics == nil {
551 return
552 }
553
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400554 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000555
556 s := &smpb.SystemResourceInfo{
557 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
558 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
559 }
560 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000561}
562
Jeongik Cha8d63d562023-03-17 03:52:13 +0900563func getNinjaWeightListSourceInMetric(s NinjaWeightListSource) *smpb.BuildConfig_NinjaWeightListSource {
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900564 switch s {
565 case NINJA_LOG:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900566 return smpb.BuildConfig_NINJA_LOG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900567 case EVENLY_DISTRIBUTED:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900568 return smpb.BuildConfig_EVENLY_DISTRIBUTED.Enum()
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900569 case EXTERNAL_FILE:
570 return smpb.BuildConfig_EXTERNAL_FILE.Enum()
Jeongik Chae114e602023-03-19 00:12:39 +0900571 case HINT_FROM_SOONG:
572 return smpb.BuildConfig_HINT_FROM_SOONG.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900573 default:
Jeongik Cha8d63d562023-03-17 03:52:13 +0900574 return smpb.BuildConfig_NOT_USED.Enum()
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900575 }
576}
577
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400578func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700579 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400580 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
581 UseGoma: proto.Bool(config.UseGoma()),
582 UseRbe: proto.Bool(config.UseRBE()),
583 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
584 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900585 NinjaWeightListSource: getNinjaWeightListSourceInMetric(config.NinjaWeightListSource()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400586 }
Yu Liue737a992021-10-04 13:21:41 -0700587 c.Targets = append(c.Targets, config.arguments...)
588
589 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400590}
591
Patrice Arruda13848222019-04-22 17:12:02 -0700592// getConfigArgs processes the command arguments based on the build action and creates a set of new
593// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700594func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700595 // The next block of code verifies that the current directory is the root directory of the source
596 // tree. It then finds the relative path of dir based on the root directory of the source tree
597 // and verify that dir is inside of the source tree.
598 checkTopDir(ctx)
599 topDir, err := os.Getwd()
600 if err != nil {
601 ctx.Fatalf("Error retrieving top directory: %v", err)
602 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700603 dir, err = filepath.EvalSymlinks(dir)
604 if err != nil {
605 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
606 }
Patrice Arruda13848222019-04-22 17:12:02 -0700607 dir, err = filepath.Abs(dir)
608 if err != nil {
609 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
610 }
611 relDir, err := filepath.Rel(topDir, dir)
612 if err != nil {
613 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
614 }
615 // If there are ".." in the path, it's not in the source tree.
616 if strings.Contains(relDir, "..") {
617 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
618 }
619
620 configArgs := args[:]
621
622 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
623 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
624 targetNamePrefix := "MODULES-IN-"
625 if inList("GET-INSTALL-PATH", configArgs) {
626 targetNamePrefix = "GET-INSTALL-PATH-IN-"
627 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
628 }
629
Patrice Arruda13848222019-04-22 17:12:02 -0700630 var targets []string
631
632 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700633 case BUILD_MODULES:
634 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700635 case BUILD_MODULES_IN_A_DIRECTORY:
636 // If dir is the root source tree, all the modules are built of the source tree are built so
637 // no need to find the build file.
638 if topDir == dir {
639 break
640 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700641
Patrice Arruda13848222019-04-22 17:12:02 -0700642 buildFile := findBuildFile(ctx, relDir)
643 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700644 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700645 }
Patrice Arruda13848222019-04-22 17:12:02 -0700646 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
647 case BUILD_MODULES_IN_DIRECTORIES:
648 newConfigArgs, dirs := splitArgs(configArgs)
649 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700650 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700651 }
652
653 // Tidy only override all other specified targets.
654 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
655 if tidyOnly == "true" || tidyOnly == "1" {
656 configArgs = append(configArgs, "tidy_only")
657 } else {
658 configArgs = append(configArgs, targets...)
659 }
660
661 return configArgs
662}
663
664// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
665func convertToTarget(dir string, targetNamePrefix string) string {
666 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
667}
668
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700669// hasBuildFile returns true if dir contains an Android build file.
670func hasBuildFile(ctx Context, dir string) bool {
671 for _, buildFile := range buildFiles {
672 _, err := os.Stat(filepath.Join(dir, buildFile))
673 if err == nil {
674 return true
675 }
676 if !os.IsNotExist(err) {
677 ctx.Fatalf("Error retrieving the build file stats: %v", err)
678 }
679 }
680 return false
681}
682
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700683// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
684// in the current and any sub directory of dir. If a build file is not found, traverse the path
685// up by one directory and repeat again until either a build file is found or reached to the root
686// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
687// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700688func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700689 // If the string is empty or ".", assume it is top directory of the source tree.
690 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700691 return ""
692 }
693
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700694 found := false
695 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
696 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
697 if err != nil {
698 return err
699 }
700 if found {
701 return filepath.SkipDir
702 }
703 if info.IsDir() {
704 return nil
705 }
706 for _, buildFile := range buildFiles {
707 if info.Name() == buildFile {
708 found = true
709 return filepath.SkipDir
710 }
711 }
712 return nil
713 })
714 if err != nil {
715 ctx.Fatalf("Error finding Android build file: %v", err)
716 }
717
718 if found {
719 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700720 }
721 }
722
723 return ""
724}
725
726// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
727func splitArgs(args []string) (newArgs []string, dirs []string) {
728 specialArgs := map[string]bool{
729 "showcommands": true,
730 "snod": true,
731 "dist": true,
732 "checkbuild": true,
733 }
734
735 newArgs = []string{}
736 dirs = []string{}
737
738 for _, arg := range args {
739 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
740 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
741 newArgs = append(newArgs, arg)
742 continue
743 }
744
745 if _, ok := specialArgs[arg]; ok {
746 newArgs = append(newArgs, arg)
747 continue
748 }
749
750 dirs = append(dirs, arg)
751 }
752
753 return newArgs, dirs
754}
755
756// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
757// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
758// source root tree where the build action command was invoked. Each directory is validated if the
759// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700760func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700761 for _, dir := range dirs {
762 // The directory may have specified specific modules to build. ":" is the separator to separate
763 // the directory and the list of modules.
764 s := strings.Split(dir, ":")
765 l := len(s)
766 if l > 2 { // more than one ":" was specified.
767 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
768 }
769
770 dir = filepath.Join(relDir, s[0])
771 if _, err := os.Stat(dir); err != nil {
772 ctx.Fatalf("couldn't find directory %s", dir)
773 }
774
775 // Verify that if there are any targets specified after ":". Each target is separated by ",".
776 var newTargets []string
777 if l == 2 && s[1] != "" {
778 newTargets = strings.Split(s[1], ",")
779 if inList("", newTargets) {
780 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
781 }
782 }
783
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700784 // If there are specified targets to build in dir, an android build file must exist for the one
785 // shot build. For the non-targets case, find the appropriate build file and build all the
786 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700787 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700788 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700789 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
790 }
791 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700792 buildFile := findBuildFile(ctx, dir)
793 if buildFile == "" {
794 ctx.Fatalf("Build file not found for %s directory", dir)
795 }
796 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700797 }
798
Patrice Arruda13848222019-04-22 17:12:02 -0700799 targets = append(targets, newTargets...)
800 }
801
Dan Willemsence41e942019-07-29 23:39:30 -0700802 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700803}
804
Dan Willemsen9b587492017-07-10 22:13:00 -0700805func (c *configImpl) parseArgs(ctx Context, args []string) {
806 for i := 0; i < len(args); i++ {
807 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100808 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700809 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200810 } else if arg == "--empty-ninja-file" {
811 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100812 } else if arg == "--skip-ninja" {
813 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700814 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700815 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
816 // but it does run a Kati ninja file if the .kati_enabled marker file was created
817 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000818 c.skipConfig = true
819 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100820 } else if arg == "--soong-only" {
821 c.skipKati = true
822 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200823 } else if arg == "--config-only" {
824 c.skipKati = true
825 c.skipKatiNinja = true
826 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700827 } else if arg == "--skip-config" {
828 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700829 } else if arg == "--skip-soong-tests" {
830 c.skipSoongTests = true
MarkDacekd0e7cd32022-12-02 22:22:40 +0000831 } else if arg == "--skip-metrics-upload" {
832 c.skipMetricsUpload = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500833 } else if arg == "--mk-metrics" {
834 c.reportMkMetrics = true
LaMont Jones52a72432023-03-09 18:19:35 +0000835 } else if arg == "--multitree-build" {
836 c.multitreeBuild = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400837 } else if arg == "--bazel-mode" {
838 c.bazelProdMode = true
839 } else if arg == "--bazel-mode-dev" {
840 c.bazelDevMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000841 } else if arg == "--bazel-mode-staging" {
842 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000843 } else if arg == "--search-api-dir" {
844 c.searchApiDir = true
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900845 } else if strings.HasPrefix(arg, "--ninja_weight_source=") {
846 source := strings.TrimPrefix(arg, "--ninja_weight_source=")
847 if source == "ninja_log" {
848 c.ninjaWeightListSource = NINJA_LOG
849 } else if source == "evenly_distributed" {
850 c.ninjaWeightListSource = EVENLY_DISTRIBUTED
851 } else if source == "not_used" {
852 c.ninjaWeightListSource = NOT_USED
Jeongik Chae114e602023-03-19 00:12:39 +0900853 } else if source == "soong" {
854 c.ninjaWeightListSource = HINT_FROM_SOONG
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900855 } else if strings.HasPrefix(source, "file,") {
856 c.ninjaWeightListSource = EXTERNAL_FILE
857 filePath := strings.TrimPrefix(source, "file,")
858 err := validateNinjaWeightList(filePath)
859 if err != nil {
860 ctx.Fatalf("Malformed weight list from %s: %s", filePath, err)
861 }
862 _, err = copyFile(filePath, filepath.Join(c.OutDir(), ".ninja_weight_list"))
863 if err != nil {
864 ctx.Fatalf("Error to copy ninja weight list from %s: %s", filePath, err)
865 }
Jeongik Cha0cf44d52023-03-15 00:10:45 +0900866 } else {
867 ctx.Fatalf("unknown option for ninja_weight_source: %s", source)
868 }
Jihoon Kang1bff0342023-01-17 20:40:22 +0000869 } else if arg == "--build-from-text-stub" {
870 c.buildFromTextStub = true
MarkDacekb96561e2022-12-02 04:34:43 +0000871 } else if strings.HasPrefix(arg, "--build-command=") {
872 buildCmd := strings.TrimPrefix(arg, "--build-command=")
873 // remove quotations
874 buildCmd = strings.TrimPrefix(buildCmd, "\"")
875 buildCmd = strings.TrimSuffix(buildCmd, "\"")
876 ctx.Metrics.SetBuildCommand([]string{buildCmd})
MarkDacekd06db5d2022-11-29 00:47:59 +0000877 } else if strings.HasPrefix(arg, "--bazel-force-enabled-modules=") {
878 c.bazelForceEnabledModules = strings.TrimPrefix(arg, "--bazel-force-enabled-modules=")
MarkDacek6614d9c2022-12-07 21:57:38 +0000879 } else if strings.HasPrefix(arg, "--build-started-time-unix-millis=") {
880 buildTimeStr := strings.TrimPrefix(arg, "--build-started-time-unix-millis=")
881 val, err := strconv.ParseInt(buildTimeStr, 10, 64)
882 if err == nil {
883 c.buildStartedTime = val
884 } else {
885 ctx.Fatalf("Error parsing build-time-started-unix-millis", err)
886 }
MarkDacekf47e1422023-04-19 16:47:36 +0000887 } else if arg == "--ensure-allowlist-integrity" {
888 c.ensureAllowlistIntegrity = true
MarkDacekd33c2fd2023-05-04 20:40:04 +0000889 } else if strings.HasPrefix(arg, "--bazel-exit-code=") {
890 bazelExitCodeStr := strings.TrimPrefix(arg, "--bazel-exit-code=")
891 val, err := strconv.Atoi(bazelExitCodeStr)
892 if err == nil {
893 c.bazelExitCode = int32(val)
894 } else {
895 ctx.Fatalf("Error parsing bazel-exit-code", err)
896 }
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700897 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700898 parseArgNum := func(def int) int {
899 if len(arg) > 2 {
900 p, err := strconv.ParseUint(arg[2:], 10, 31)
901 if err != nil {
902 ctx.Fatalf("Failed to parse %q: %v", arg, err)
903 }
904 return int(p)
905 } else if i+1 < len(args) {
906 p, err := strconv.ParseUint(args[i+1], 10, 31)
907 if err == nil {
908 i++
909 return int(p)
910 }
911 }
912 return def
913 }
914
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700915 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700916 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700917 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700918 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700919 } else {
920 ctx.Fatalln("Unknown option:", arg)
921 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700922 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700923 if k == "OUT_DIR" {
924 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
925 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700926 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700927 } else if arg == "dist" {
928 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200929 } else if arg == "json-module-graph" {
930 c.jsonModuleGraph = true
931 } else if arg == "bp2build" {
932 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000933 } else if arg == "api_bp2build" {
934 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200935 } else if arg == "queryview" {
936 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200937 } else if arg == "soong_docs" {
938 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700939 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700940 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800941 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700942 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700943 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700944 }
945 }
Chris Parsonsb6e96902022-10-31 20:08:45 -0400946 if (!c.bazelProdMode) && (!c.bazelDevMode) && (!c.bazelStagingMode) {
947 c.bazelProdMode = defaultBazelProdMode(c)
948 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700949}
950
Jeongik Cha518f3ea2023-03-19 00:12:39 +0900951func validateNinjaWeightList(weightListFilePath string) (err error) {
952 data, err := os.ReadFile(weightListFilePath)
953 if err != nil {
954 return
955 }
956 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
957 for _, line := range lines {
958 fields := strings.Split(line, ",")
959 if len(fields) != 2 {
960 return fmt.Errorf("wrong format, each line should have two fields, but '%s'", line)
961 }
962 _, err = strconv.Atoi(fields[1])
963 if err != nil {
964 return
965 }
966 }
967 return
968}
969
Dan Willemsened869522018-01-08 14:58:46 -0800970func (c *configImpl) configureLocale(ctx Context) {
971 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
972 output, err := cmd.Output()
973
974 var locales []string
975 if err == nil {
976 locales = strings.Split(string(output), "\n")
977 } else {
978 // If we're unable to list the locales, let's assume en_US.UTF-8
979 locales = []string{"en_US.UTF-8"}
980 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
981 }
982
983 // gettext uses LANGUAGE, which is passed directly through
984
985 // For LANG and LC_*, only preserve the evaluated version of
986 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800987 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800988 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800989 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800990 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800991 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800992 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800993 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800994 }
995
996 c.environ.UnsetWithPrefix("LC_")
997
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800998 if userLang != "" {
999 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -08001000 }
1001
1002 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
1003 // for others)
1004 if inList("C.UTF-8", locales) {
1005 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -05001006 } else if inList("C.utf8", locales) {
1007 // These normalize to the same thing
1008 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -08001009 } else if inList("en_US.UTF-8", locales) {
1010 c.environ.Set("LANG", "en_US.UTF-8")
1011 } else if inList("en_US.utf8", locales) {
1012 // These normalize to the same thing
1013 c.environ.Set("LANG", "en_US.UTF-8")
1014 } else {
1015 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
1016 }
1017}
1018
Dan Willemsen1e704462016-08-21 15:17:17 -07001019func (c *configImpl) Environment() *Environment {
1020 return c.environ
1021}
1022
1023func (c *configImpl) Arguments() []string {
1024 return c.arguments
1025}
1026
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001027func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001028 if len(c.Arguments()) > 0 {
1029 // Explicit targets requested that are not special targets like b2pbuild
1030 // or the JSON module graph
1031 return true
1032 }
1033
Spandan Das5af0bd32022-09-28 20:43:08 +00001034 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001035 // Command line was empty, the default Ninja target is built
1036 return true
1037 }
1038
Liz Kammer88677422021-12-15 15:03:19 -05001039 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
1040 if c.Dist() && !c.Bp2Build() {
1041 return true
1042 }
1043
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001044 // build.ninja doesn't need to be generated
1045 return false
1046}
1047
Dan Willemsen1e704462016-08-21 15:17:17 -07001048func (c *configImpl) OutDir() string {
1049 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -07001050 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -07001051 }
1052 return "out"
1053}
1054
Dan Willemsen8a073a82017-02-04 17:30:44 -08001055func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -04001056 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001057}
1058
1059func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -07001060 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -08001061}
1062
Dan Willemsen1e704462016-08-21 15:17:17 -07001063func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001064 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001065 return c.arguments
1066 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001067 return c.ninjaArgs
1068}
1069
Jingwen Chen7c6089a2020-11-02 02:56:20 -05001070func (c *configImpl) BazelOutDir() string {
1071 return filepath.Join(c.OutDir(), "bazel")
1072}
1073
Liz Kammer2af5ea82022-11-11 14:21:03 -05001074func (c *configImpl) bazelOutputBase() string {
1075 return filepath.Join(c.BazelOutDir(), "output")
1076}
1077
Dan Willemsen1e704462016-08-21 15:17:17 -07001078func (c *configImpl) SoongOutDir() string {
1079 return filepath.Join(c.OutDir(), "soong")
1080}
1081
Spandan Das394aa322022-11-03 17:02:10 +00001082func (c *configImpl) ApiSurfacesOutDir() string {
1083 return filepath.Join(c.OutDir(), "api_surfaces")
1084}
1085
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001086func (c *configImpl) PrebuiltOS() string {
1087 switch runtime.GOOS {
1088 case "linux":
1089 return "linux-x86"
1090 case "darwin":
1091 return "darwin-x86"
1092 default:
1093 panic("Unknown GOOS")
1094 }
1095}
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001096
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001097func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -07001098 if c.SkipKatiNinja() {
1099 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
1100 } else {
1101 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
1102 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +02001103}
1104
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001105func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001106 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +02001107}
1108
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +02001109func (c *configImpl) UsedEnvFile(tag string) string {
1110 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
1111}
1112
Lukacs T. Berkic541cd22022-10-26 07:26:50 +00001113func (c *configImpl) Bp2BuildFilesMarkerFile() string {
1114 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
1115}
1116
1117func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +01001118 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +02001119}
1120
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001121func (c *configImpl) SoongDocsHtml() string {
1122 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
1123}
1124
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001125func (c *configImpl) QueryviewMarkerFile() string {
1126 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
1127}
1128
Spandan Das5af0bd32022-09-28 20:43:08 +00001129func (c *configImpl) ApiBp2buildMarkerFile() string {
1130 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
1131}
1132
Lukacs T. Berkie571dc32021-08-25 14:14:13 +02001133func (c *configImpl) ModuleGraphFile() string {
1134 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
1135}
1136
kgui67007242022-01-25 13:50:25 +08001137func (c *configImpl) ModuleActionsFile() string {
1138 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
1139}
1140
Jeff Gastonefc1b412017-03-29 17:29:06 -07001141func (c *configImpl) TempDir() string {
1142 return shared.TempDirForOutDir(c.SoongOutDir())
1143}
1144
Jeff Gastonb64fc1c2017-08-04 12:30:12 -07001145func (c *configImpl) FileListDir() string {
1146 return filepath.Join(c.OutDir(), ".module_paths")
1147}
1148
Dan Willemsen1e704462016-08-21 15:17:17 -07001149func (c *configImpl) KatiSuffix() string {
1150 if c.katiSuffix != "" {
1151 return c.katiSuffix
1152 }
1153 panic("SetKatiSuffix has not been called")
1154}
1155
Colin Cross37193492017-11-16 17:55:00 -08001156// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
1157// user is interested in additional checks at the expense of build time.
1158func (c *configImpl) Checkbuild() bool {
1159 return c.checkbuild
1160}
1161
Dan Willemsen8a073a82017-02-04 17:30:44 -08001162func (c *configImpl) Dist() bool {
1163 return c.dist
1164}
1165
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001166func (c *configImpl) JsonModuleGraph() bool {
1167 return c.jsonModuleGraph
1168}
1169
1170func (c *configImpl) Bp2Build() bool {
1171 return c.bp2build
1172}
1173
Spandan Das5af0bd32022-09-28 20:43:08 +00001174func (c *configImpl) ApiBp2build() bool {
1175 return c.apiBp2build
1176}
1177
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001178func (c *configImpl) Queryview() bool {
1179 return c.queryview
1180}
1181
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001182func (c *configImpl) SoongDocs() bool {
1183 return c.soongDocs
1184}
1185
Dan Willemsen1e704462016-08-21 15:17:17 -07001186func (c *configImpl) IsVerbose() bool {
1187 return c.verbose
1188}
1189
LaMont Jones52a72432023-03-09 18:19:35 +00001190func (c *configImpl) MultitreeBuild() bool {
1191 return c.multitreeBuild
1192}
1193
Jeongik Cha0cf44d52023-03-15 00:10:45 +09001194func (c *configImpl) NinjaWeightListSource() NinjaWeightListSource {
1195 return c.ninjaWeightListSource
1196}
1197
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001198func (c *configImpl) SkipKati() bool {
1199 return c.skipKati
1200}
1201
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001202func (c *configImpl) SkipKatiNinja() bool {
1203 return c.skipKatiNinja
1204}
1205
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001206func (c *configImpl) SkipSoong() bool {
1207 return c.skipSoong
1208}
1209
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001210func (c *configImpl) SkipNinja() bool {
1211 return c.skipNinja
1212}
1213
Anton Hansson5a7861a2021-06-04 10:09:01 +01001214func (c *configImpl) SetSkipNinja(v bool) {
1215 c.skipNinja = v
1216}
1217
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001218func (c *configImpl) SkipConfig() bool {
1219 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001220}
1221
Jihoon Kang1bff0342023-01-17 20:40:22 +00001222func (c *configImpl) BuildFromTextStub() bool {
1223 return c.buildFromTextStub
1224}
1225
Dan Willemsen1e704462016-08-21 15:17:17 -07001226func (c *configImpl) TargetProduct() string {
1227 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1228 return v
1229 }
1230 panic("TARGET_PRODUCT is not defined")
1231}
1232
Dan Willemsen02781d52017-05-12 19:28:13 -07001233func (c *configImpl) TargetDevice() string {
1234 return c.targetDevice
1235}
1236
1237func (c *configImpl) SetTargetDevice(device string) {
1238 c.targetDevice = device
1239}
1240
1241func (c *configImpl) TargetBuildVariant() string {
1242 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1243 return v
1244 }
1245 panic("TARGET_BUILD_VARIANT is not defined")
1246}
1247
Dan Willemsen1e704462016-08-21 15:17:17 -07001248func (c *configImpl) KatiArgs() []string {
1249 return c.katiArgs
1250}
1251
1252func (c *configImpl) Parallel() int {
1253 return c.parallel
1254}
1255
Sam Delmerico98a73292023-02-21 11:50:29 -05001256func (c *configImpl) GetSourceRootDirs() []string {
1257 return c.sourceRootDirs
1258}
1259
1260func (c *configImpl) SetSourceRootDirs(i []string) {
1261 c.sourceRootDirs = i
1262}
1263
Spandan Dasc5763832022-11-08 18:42:16 +00001264func (c *configImpl) GetIncludeTags() []string {
1265 return c.includeTags
1266}
1267
1268func (c *configImpl) SetIncludeTags(i []string) {
1269 c.includeTags = i
1270}
1271
MarkDacek6614d9c2022-12-07 21:57:38 +00001272func (c *configImpl) GetLogsPrefix() string {
1273 return c.logsPrefix
1274}
1275
1276func (c *configImpl) SetLogsPrefix(prefix string) {
1277 c.logsPrefix = prefix
1278}
1279
Colin Cross8b8bec32019-11-15 13:18:43 -08001280func (c *configImpl) HighmemParallel() int {
1281 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1282 return i
1283 }
1284
1285 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1286 parallel := c.Parallel()
1287 if c.UseRemoteBuild() {
1288 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1289 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1290 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1291 // Return 1/16th of the size of the local pool, rounding up.
1292 return (parallel + 15) / 16
1293 } else if c.totalRAM == 0 {
1294 // Couldn't detect the total RAM, don't restrict highmem processes.
1295 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001296 } else if c.totalRAM <= 16*1024*1024*1024 {
1297 // Less than 16GB of ram, restrict to 1 highmem processes
1298 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001299 } else if c.totalRAM <= 32*1024*1024*1024 {
1300 // Less than 32GB of ram, restrict to 2 highmem processes
1301 return 2
1302 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1303 // If less than 8GB total RAM per process, reduce the number of highmem processes
1304 return p
1305 }
1306 // No restriction on highmem processes
1307 return parallel
1308}
1309
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001310func (c *configImpl) TotalRAM() uint64 {
1311 return c.totalRAM
1312}
1313
Kousik Kumarec478642020-09-21 13:39:24 -04001314// ForceUseGoma determines whether we should override Goma deprecation
1315// and use Goma for the current build or not.
1316func (c *configImpl) ForceUseGoma() bool {
1317 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1318 v = strings.TrimSpace(v)
1319 if v != "" && v != "false" {
1320 return true
1321 }
1322 }
1323 return false
1324}
1325
Dan Willemsen1e704462016-08-21 15:17:17 -07001326func (c *configImpl) UseGoma() bool {
1327 if v, ok := c.environ.Get("USE_GOMA"); ok {
1328 v = strings.TrimSpace(v)
1329 if v != "" && v != "false" {
1330 return true
1331 }
1332 }
1333 return false
1334}
1335
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001336func (c *configImpl) StartGoma() bool {
1337 if !c.UseGoma() {
1338 return false
1339 }
1340
1341 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1342 v = strings.TrimSpace(v)
1343 if v != "" && v != "false" {
1344 return false
1345 }
1346 }
1347 return true
1348}
1349
Ramy Medhatbbf25672019-07-17 12:30:04 +00001350func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001351 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001352 v = strings.TrimSpace(v)
1353 if v != "" && v != "false" {
1354 return true
1355 }
1356 }
1357 return false
1358}
1359
Chris Parsonsef615e52022-08-18 22:04:11 -04001360func (c *configImpl) BazelBuildEnabled() bool {
MarkDacekb78465d2022-10-18 20:10:16 +00001361 return c.bazelProdMode || c.bazelDevMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001362}
1363
Ramy Medhatbbf25672019-07-17 12:30:04 +00001364func (c *configImpl) StartRBE() bool {
1365 if !c.UseRBE() {
1366 return false
1367 }
1368
1369 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1370 v = strings.TrimSpace(v)
1371 if v != "" && v != "false" {
1372 return false
1373 }
1374 }
1375 return true
1376}
1377
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001378func (c *configImpl) rbeProxyLogsDir() string {
1379 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001380 if v, ok := c.environ.Get(f); ok {
1381 return v
1382 }
1383 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001384 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1385 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001386}
1387
Ramy Medhatc8f6cc22023-03-31 09:50:34 -04001388func (c *configImpl) rbeCacheDir() string {
1389 for _, f := range []string{"RBE_cache_dir", "FLAG_cache_dir"} {
1390 if v, ok := c.environ.Get(f); ok {
1391 return v
1392 }
1393 }
1394 return shared.JoinPath(c.SoongOutDir(), "rbe")
1395}
1396
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001397func (c *configImpl) shouldCleanupRBELogsDir() bool {
1398 // Perform a log directory cleanup only when the log directory
1399 // is auto created by the build rather than user-specified.
1400 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1401 if _, ok := c.environ.Get(f); ok {
1402 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001403 }
1404 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001405 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001406}
1407
1408func (c *configImpl) rbeExecRoot() string {
1409 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1410 if v, ok := c.environ.Get(f); ok {
1411 return v
1412 }
1413 }
1414 wd, err := os.Getwd()
1415 if err != nil {
1416 return ""
1417 }
1418 return wd
1419}
1420
1421func (c *configImpl) rbeDir() string {
1422 if v, ok := c.environ.Get("RBE_DIR"); ok {
1423 return v
1424 }
1425 return "prebuilts/remoteexecution-client/live/"
1426}
1427
1428func (c *configImpl) rbeReproxy() string {
1429 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1430 if v, ok := c.environ.Get(f); ok {
1431 return v
1432 }
1433 }
1434 return filepath.Join(c.rbeDir(), "reproxy")
1435}
1436
1437func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001438 credFlags := []string{
1439 "use_application_default_credentials",
1440 "use_gce_credentials",
1441 "credential_file",
1442 "use_google_prod_creds",
1443 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001444 for _, cf := range credFlags {
1445 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1446 if v, ok := c.environ.Get(f); ok {
1447 v = strings.TrimSpace(v)
1448 if v != "" && v != "false" && v != "0" {
1449 return "RBE_" + cf, v
1450 }
1451 }
1452 }
1453 }
1454 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001455}
1456
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001457func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1458 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1459 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1460
1461 name := filepath.Join(dir, base)
1462 if len(name) < maxNameLen {
1463 return name, nil
1464 }
1465
1466 name = filepath.Join("/tmp", base)
1467 if len(name) < maxNameLen {
1468 return name, nil
1469 }
1470
1471 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1472}
1473
Kousik Kumar7bc78192022-04-27 14:52:56 -04001474// IsGooglerEnvironment returns true if the current build is running
1475// on a Google developer machine and false otherwise.
1476func (c *configImpl) IsGooglerEnvironment() bool {
1477 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1478 if v, ok := c.environ.Get(cf); ok {
1479 return v == "googler"
1480 }
1481 return false
1482}
1483
1484// GoogleProdCredsExist determine whether credentials exist on the
1485// Googler machine to use remote execution.
1486func (c *configImpl) GoogleProdCredsExist() bool {
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001487 if googleProdCredsExistCache {
1488 return googleProdCredsExistCache
1489 }
Kousik Kumar7bc78192022-04-27 14:52:56 -04001490 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1491 return false
1492 }
Kevin Dagostino096ab2f2023-03-03 19:47:17 +00001493 googleProdCredsExistCache = true
Kousik Kumar7bc78192022-04-27 14:52:56 -04001494 return true
1495}
1496
1497// UseRemoteBuild indicates whether to use a remote build acceleration system
1498// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001499func (c *configImpl) UseRemoteBuild() bool {
1500 return c.UseGoma() || c.UseRBE()
1501}
1502
Kousik Kumar7bc78192022-04-27 14:52:56 -04001503// StubbyExists checks whether the stubby binary exists on the machine running
1504// the build.
1505func (c *configImpl) StubbyExists() bool {
1506 if _, err := exec.LookPath("stubby"); err != nil {
1507 return false
1508 }
1509 return true
1510}
1511
Dan Willemsen1e704462016-08-21 15:17:17 -07001512// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001513// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001514// still limited by Parallel()
1515func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001516 if !c.UseRemoteBuild() {
1517 return 0
1518 }
1519 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1520 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001521 }
1522 return 500
1523}
1524
1525func (c *configImpl) SetKatiArgs(args []string) {
1526 c.katiArgs = args
1527}
1528
1529func (c *configImpl) SetNinjaArgs(args []string) {
1530 c.ninjaArgs = args
1531}
1532
1533func (c *configImpl) SetKatiSuffix(suffix string) {
1534 c.katiSuffix = suffix
1535}
1536
Dan Willemsene0879fc2017-08-04 15:06:27 -07001537func (c *configImpl) LastKatiSuffixFile() string {
1538 return filepath.Join(c.OutDir(), "last_kati_suffix")
1539}
1540
1541func (c *configImpl) HasKatiSuffix() bool {
1542 return c.katiSuffix != ""
1543}
1544
Dan Willemsen1e704462016-08-21 15:17:17 -07001545func (c *configImpl) KatiEnvFile() string {
1546 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1547}
1548
Dan Willemsen29971232018-09-26 14:58:30 -07001549func (c *configImpl) KatiBuildNinjaFile() string {
1550 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001551}
1552
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001553func (c *configImpl) KatiPackageNinjaFile() string {
1554 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1555}
1556
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001557func (c *configImpl) SoongVarsFile() string {
1558 return filepath.Join(c.SoongOutDir(), "soong.variables")
1559}
1560
Dan Willemsen1e704462016-08-21 15:17:17 -07001561func (c *configImpl) SoongNinjaFile() string {
1562 return filepath.Join(c.SoongOutDir(), "build.ninja")
1563}
1564
1565func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001566 if c.katiSuffix == "" {
1567 return filepath.Join(c.OutDir(), "combined.ninja")
1568 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001569 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1570}
1571
1572func (c *configImpl) SoongAndroidMk() string {
1573 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1574}
1575
1576func (c *configImpl) SoongMakeVarsMk() string {
1577 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1578}
1579
Dan Willemsenf052f782017-05-18 15:29:04 -07001580func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001581 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001582}
1583
Dan Willemsen02781d52017-05-12 19:28:13 -07001584func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001585 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1586}
1587
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001588func (c *configImpl) KatiPackageMkDir() string {
1589 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1590}
1591
Dan Willemsenf052f782017-05-18 15:29:04 -07001592func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001593 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001594}
1595
1596func (c *configImpl) HostOut() string {
1597 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1598}
1599
1600// This probably needs to be multi-valued, so not exporting it for now
1601func (c *configImpl) hostCrossOut() string {
1602 if runtime.GOOS == "linux" {
1603 return filepath.Join(c.hostOutRoot(), "windows-x86")
1604 } else {
1605 return ""
1606 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001607}
1608
Dan Willemsen1e704462016-08-21 15:17:17 -07001609func (c *configImpl) HostPrebuiltTag() string {
1610 if runtime.GOOS == "linux" {
1611 return "linux-x86"
1612 } else if runtime.GOOS == "darwin" {
1613 return "darwin-x86"
1614 } else {
1615 panic("Unsupported OS")
1616 }
1617}
Dan Willemsenf173d592017-04-27 14:28:00 -07001618
Dan Willemsen8122bd52017-10-12 20:20:41 -07001619func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001620 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1621 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001622 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1623 if _, err := os.Stat(asan); err == nil {
1624 return asan
1625 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001626 }
1627 }
1628 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1629}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001630
1631func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1632 c.brokenDupRules = val
1633}
1634
1635func (c *configImpl) BuildBrokenDupRules() bool {
1636 return c.brokenDupRules
1637}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001638
Dan Willemsen25e6f092019-04-09 10:22:43 -07001639func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1640 c.brokenUsesNetwork = val
1641}
1642
1643func (c *configImpl) BuildBrokenUsesNetwork() bool {
1644 return c.brokenUsesNetwork
1645}
1646
Dan Willemsene3336352020-01-02 19:10:38 -08001647func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1648 c.brokenNinjaEnvVars = val
1649}
1650
1651func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1652 return c.brokenNinjaEnvVars
1653}
1654
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001655func (c *configImpl) SetTargetDeviceDir(dir string) {
1656 c.targetDeviceDir = dir
1657}
1658
1659func (c *configImpl) TargetDeviceDir() string {
1660 return c.targetDeviceDir
1661}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001662
Patrice Arruda219eef32020-06-01 17:29:30 +00001663func (c *configImpl) BuildDateTime() string {
1664 return c.buildDateTime
1665}
1666
1667func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001668 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001669}
Patrice Arruda83842d72020-12-08 19:42:08 +00001670
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001671// LogsDir returns the absolute path to the logs directory where build log and
1672// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001673// directory. If the argument dist is specified, the logs directory
1674// is <dist_dir>/logs.
1675func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001676 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001677 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001678 // 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 -05001679 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001680 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001681 absDir, err := filepath.Abs(dir)
1682 if err != nil {
1683 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1684 os.Exit(1)
1685 }
1686 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001687}
1688
1689// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1690// where the bazel profiles are located.
1691func (c *configImpl) BazelMetricsDir() string {
1692 return filepath.Join(c.LogsDir(), "bazel_metrics")
1693}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001694
Chris Parsons53f68ae2022-03-03 12:01:40 -05001695// MkFileMetrics returns the file path for make-related metrics.
1696func (c *configImpl) MkMetrics() string {
1697 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1698}
1699
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001700func (c *configImpl) SetEmptyNinjaFile(v bool) {
1701 c.emptyNinjaFile = v
1702}
1703
1704func (c *configImpl) EmptyNinjaFile() bool {
1705 return c.emptyNinjaFile
1706}
Yu Liu6e13b402021-07-27 14:29:06 -07001707
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001708func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1709 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1710}
1711
Chris Parsons9402ca82023-02-23 17:28:06 -05001712func (c *configImpl) IsPersistentBazelEnabled() bool {
1713 return c.Environment().IsEnvTrue("USE_PERSISTENT_BAZEL")
1714}
1715
MarkDacekd06db5d2022-11-29 00:47:59 +00001716func (c *configImpl) BazelModulesForceEnabledByFlag() string {
1717 return c.bazelForceEnabledModules
1718}
1719
MarkDacekd0e7cd32022-12-02 22:22:40 +00001720func (c *configImpl) SkipMetricsUpload() bool {
1721 return c.skipMetricsUpload
1722}
1723
MarkDacekf47e1422023-04-19 16:47:36 +00001724func (c *configImpl) EnsureAllowlistIntegrity() bool {
1725 return c.ensureAllowlistIntegrity
1726}
1727
MarkDacek6614d9c2022-12-07 21:57:38 +00001728// Returns a Time object if one was passed via a command-line flag.
1729// Otherwise returns the passed default.
1730func (c *configImpl) BuildStartedTimeOrDefault(defaultTime time.Time) time.Time {
1731 if c.buildStartedTime == 0 {
1732 return defaultTime
1733 }
1734 return time.UnixMilli(c.buildStartedTime)
1735}
1736
MarkDacekd33c2fd2023-05-04 20:40:04 +00001737func (c *configImpl) BazelExitCode() int32 {
1738 return c.bazelExitCode
1739}
1740
Yu Liu6e13b402021-07-27 14:29:06 -07001741func GetMetricsUploader(topDir string, env *Environment) string {
1742 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1743 metricsUploader := filepath.Join(topDir, p)
1744 if _, err := os.Stat(metricsUploader); err == nil {
1745 return metricsUploader
1746 }
1747 }
1748
1749 return ""
1750}