blob: 8874209049b1c396d8a4da9d281107d586534b8c [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 (
48 rbeRandPrefix int
49)
50
51func init() {
52 rand.Seed(time.Now().UnixNano())
53 rbeRandPrefix = rand.Intn(1000)
54}
55
Dan Willemsen1e704462016-08-21 15:17:17 -070056type Config struct{ *configImpl }
57
58type configImpl struct {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020059 // Some targets that are implemented in soong_build
60 // (bp2build, json-module-graph) are not here and have their own bits below.
Colin Cross28f527c2019-11-26 16:19:04 -080061 arguments []string
62 goma bool
63 environ *Environment
64 distDir string
65 buildDateTime string
Dan Willemsen1e704462016-08-21 15:17:17 -070066
67 // From the arguments
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020068 parallel int
69 keepGoing int
70 verbose bool
71 checkbuild bool
72 dist bool
73 jsonModuleGraph bool
74 bp2build bool
Lukacs T. Berki3a821692021-09-06 17:08:02 +020075 queryview bool
Chris Parsons53f68ae2022-03-03 12:01:40 -050076 reportMkMetrics bool // Collect and report mk2bp migration progress metrics.
Lukacs T. Berkic6012f32021-09-06 18:31:46 +020077 soongDocs bool
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020078 skipConfig bool
79 skipKati bool
80 skipKatiNinja bool
81 skipSoong bool
82 skipNinja bool
83 skipSoongTests bool
Dan Willemsen1e704462016-08-21 15:17:17 -070084
85 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070086 katiArgs []string
87 ninjaArgs []string
88 katiSuffix string
89 targetDevice string
90 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +000091 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -070092
Dan Willemsen2bb82d02019-12-27 09:35:42 -080093 // Autodetected
94 totalRAM uint64
95
Dan Willemsene3336352020-01-02 19:10:38 -080096 brokenDupRules bool
97 brokenUsesNetwork bool
98 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -070099
100 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000101
102 useBazel bool
103
104 // During Bazel execution, Bazel cannot write outside OUT_DIR.
105 // So if DIST_DIR is set to an external dir (outside of OUT_DIR), we need to rig it temporarily and then migrate files at the end of the build.
106 riggedDistDirForBazel string
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700107
108 // Set by multiproduct_kati
109 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700110
111 metricsUploader string
Dan Willemsen1e704462016-08-21 15:17:17 -0700112}
113
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800114const srcDirFileCheck = "build/soong/root.bp"
115
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700116var buildFiles = []string{"Android.mk", "Android.bp"}
117
Patrice Arruda13848222019-04-22 17:12:02 -0700118type BuildAction uint
119
120const (
121 // Builds all of the modules and their dependencies of a specified directory, relative to the root
122 // directory of the source tree.
123 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
124
125 // Builds all of the modules and their dependencies of a list of specified directories. All specified
126 // directories are relative to the root directory of the source tree.
127 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700128
129 // Build a list of specified modules. If none was specified, simply build the whole source tree.
130 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700131)
132
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400133type bazelBuildMode int
134
135// Bazel-related build modes.
136const (
137 // Don't use bazel at all.
138 noBazel bazelBuildMode = iota
139
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400140 // Generate synthetic build files and incorporate these files into a build which
141 // partially uses Bazel. Build metadata may come from Android.bp or BUILD files.
142 mixedBuild
143)
144
Patrice Arruda13848222019-04-22 17:12:02 -0700145// checkTopDir validates that the current directory is at the root directory of the source tree.
146func checkTopDir(ctx Context) {
147 if _, err := os.Stat(srcDirFileCheck); err != nil {
148 if os.IsNotExist(err) {
149 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
150 }
151 ctx.Fatalln("Error verifying tree state:", err)
152 }
153}
154
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500155// fetchEnvConfig optionally fetches environment config from an
156// experiments system to control Soong features dynamically.
157func fetchEnvConfig(ctx Context, config *configImpl, envConfigName string) error {
David Goldsmith62243a32022-04-08 13:42:04 +0000158 configName := envConfigName + "." + jsonSuffix
159 expConfigFetcher := &smpb.ExpConfigFetcher{}
160 defer func() {
161 ctx.Metrics.ExpConfigFetcher(expConfigFetcher)
162 }()
163
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500164 s, err := os.Stat(configFetcher)
165 if err != nil {
166 if os.IsNotExist(err) {
167 return nil
168 }
169 return err
170 }
171 if s.Mode()&0111 == 0 {
David Goldsmith62243a32022-04-08 13:42:04 +0000172 status := smpb.ExpConfigFetcher_ERROR
173 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500174 return fmt.Errorf("configuration fetcher binary %v is not executable: %v", configFetcher, s.Mode())
175 }
176
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500177 tCtx, cancel := context.WithTimeout(ctx, envConfigFetchTimeout)
178 defer cancel()
David Goldsmith62243a32022-04-08 13:42:04 +0000179 fetchStart := time.Now()
180 cmd := exec.CommandContext(tCtx, configFetcher, "-output_config_dir", config.OutDir(),
181 "-output_config_name", configName)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500182 if err := cmd.Start(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000183 status := smpb.ExpConfigFetcher_ERROR
184 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500185 return err
186 }
187
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500188 if err := cmd.Wait(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000189 status := smpb.ExpConfigFetcher_ERROR
190 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500191 return err
192 }
David Goldsmith62243a32022-04-08 13:42:04 +0000193 fetchEnd := time.Now()
194 expConfigFetcher.Micros = proto.Uint64(uint64(fetchEnd.Sub(fetchStart).Microseconds()))
195 outConfigFilePath := filepath.Join(config.OutDir(), configName)
196 expConfigFetcher.Filename = proto.String(outConfigFilePath)
197 if _, err := os.Stat(outConfigFilePath); err == nil {
198 status := smpb.ExpConfigFetcher_CONFIG
199 expConfigFetcher.Status = &status
200 } else {
201 status := smpb.ExpConfigFetcher_NO_CONFIG
202 expConfigFetcher.Status = &status
203 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500204 return nil
205}
206
207func loadEnvConfig(ctx Context, config *configImpl) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500208 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
209 if bc == "" {
210 return nil
211 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500212
213 if err := fetchEnvConfig(ctx, config, bc); err != nil {
Kousik Kumar595fb1c2022-06-24 16:49:52 +0000214 ctx.Verbosef("Failed to fetch config file: %v\n", err)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500215 }
216
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500217 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500218 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500219 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500220 envConfigDir,
221 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500222 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500223 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
224 envVarsJSON, err := ioutil.ReadFile(cfgFile)
225 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500226 continue
227 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500228 ctx.Verbosef("Loading config file %v\n", cfgFile)
229 var envVars map[string]map[string]string
230 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
231 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
232 continue
233 }
234 for k, v := range envVars["env"] {
235 if os.Getenv(k) != "" {
236 continue
237 }
238 config.environ.Set(k, v)
239 }
240 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
241 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500242 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500243
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500244 return nil
245}
246
Dan Willemsen1e704462016-08-21 15:17:17 -0700247func NewConfig(ctx Context, args ...string) Config {
248 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000249 environ: OsEnvironment(),
250 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700251 }
252
Patrice Arruda90109172020-07-28 18:07:27 +0000253 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700254 ret.parallel = runtime.NumCPU() + 2
255 ret.keepGoing = 1
256
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800257 ret.totalRAM = detectTotalRAM(ctx)
258
Dan Willemsen9b587492017-07-10 22:13:00 -0700259 ret.parseArgs(ctx, args)
260
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800261 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700262 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
263 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
264 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800265 outDir := "out"
266 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
267 if wd, err := os.Getwd(); err != nil {
268 ctx.Fatalln("Failed to get working directory:", err)
269 } else {
270 outDir = filepath.Join(baseDir, filepath.Base(wd))
271 }
272 }
273 ret.environ.Set("OUT_DIR", outDir)
274 }
275
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500276 // loadEnvConfig needs to know what the OUT_DIR is, so it should
277 // be called after we determine the appropriate out directory.
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500278 if err := loadEnvConfig(ctx, ret); err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500279 ctx.Fatalln("Failed to parse env config files: %v", err)
280 }
281
Dan Willemsen2d31a442018-10-20 21:33:41 -0700282 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
283 ret.distDir = filepath.Clean(distDir)
284 } else {
285 ret.distDir = filepath.Join(ret.OutDir(), "dist")
286 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700287
Spandan Das05063612021-06-25 01:39:04 +0000288 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
289 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
290 }
291
Dan Willemsen1e704462016-08-21 15:17:17 -0700292 ret.environ.Unset(
293 // We're already using it
294 "USE_SOONG_UI",
295
296 // We should never use GOROOT/GOPATH from the shell environment
297 "GOROOT",
298 "GOPATH",
299
300 // These should only come from Soong, not the environment.
301 "CLANG",
302 "CLANG_CXX",
303 "CCC_CC",
304 "CCC_CXX",
305
306 // Used by the goma compiler wrapper, but should only be set by
307 // gomacc
308 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800309
310 // We handle this above
311 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700312
Dan Willemsen2d31a442018-10-20 21:33:41 -0700313 // This is handled above too, and set for individual commands later
314 "DIST_DIR",
315
Dan Willemsen68a09852017-04-18 13:56:57 -0700316 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000317 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700318 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700319 "DISPLAY",
320 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700321 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700322 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700323
324 // Drop make flags
325 "MAKEFLAGS",
326 "MAKELEVEL",
327 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700328
329 // Set in envsetup.sh, reset in makefiles
330 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700331
332 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
333 "ANDROID_BUILD_TOP",
334 "ANDROID_HOST_OUT",
335 "ANDROID_PRODUCT_OUT",
336 "ANDROID_HOST_OUT_TESTCASES",
337 "ANDROID_TARGET_OUT_TESTCASES",
338 "ANDROID_TOOLCHAIN",
339 "ANDROID_TOOLCHAIN_2ND_ARCH",
340 "ANDROID_DEV_SCRIPTS",
341 "ANDROID_EMULATOR_PREBUILTS",
342 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700343 )
344
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400345 if ret.UseGoma() || ret.ForceUseGoma() {
346 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
347 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400348 }
349
Dan Willemsen1e704462016-08-21 15:17:17 -0700350 // Tell python not to spam the source tree with .pyc files.
351 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
352
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400353 tmpDir := absPath(ctx, ret.TempDir())
354 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800355
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700356 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
357 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
358 "llvm-binutils-stable/llvm-symbolizer")
359 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
360
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800361 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700362 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800363
Yu Liu6e13b402021-07-27 14:29:06 -0700364 srcDir := absPath(ctx, ".")
365 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700366 ctx.Println("You are building in a directory whose absolute path contains a space character:")
367 ctx.Println()
368 ctx.Printf("%q\n", srcDir)
369 ctx.Println()
370 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700371 }
372
Yu Liu6e13b402021-07-27 14:29:06 -0700373 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
374
Dan Willemsendb8457c2017-05-12 16:38:17 -0700375 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700376 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
377 ctx.Println()
378 ctx.Printf("%q\n", outDir)
379 ctx.Println()
380 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700381 }
382
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000383 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700384 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
385 ctx.Println()
386 ctx.Printf("%q\n", distDir)
387 ctx.Println()
388 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700389 }
390
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700391 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000392 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
393 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100394 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800395 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700396 javaHome := func() string {
397 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
398 return override
399 }
Colin Cross59c1e6a2022-03-04 13:37:19 -0800400 if ret.environ.IsEnvTrue("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN") {
401 return java17Home
402 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000403 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
404 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 +0100405 }
Pete Gillinabbcdda2019-10-28 16:15:33 +0000406 return java11Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700407 }()
408 absJavaHome := absPath(ctx, javaHome)
409
Dan Willemsened869522018-01-08 14:58:46 -0800410 ret.configureLocale(ctx)
411
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700412 newPath := []string{filepath.Join(absJavaHome, "bin")}
413 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
414 newPath = append(newPath, path)
415 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100416
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700417 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
418 ret.environ.Set("JAVA_HOME", absJavaHome)
419 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000420 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
421 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100422 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700423 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
424
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800425 outDir := ret.OutDir()
426 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800427 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800428 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800429 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800430 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800431 }
Colin Cross28f527c2019-11-26 16:19:04 -0800432
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800433 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
434
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400435 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400436 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400437 ret.environ.Set(k, v)
438 }
439 }
440
Patrice Arruda83842d72020-12-08 19:42:08 +0000441 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800442 if err := os.RemoveAll(bpd); err != nil {
443 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
444 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000445
446 ret.useBazel = ret.environ.IsEnvTrue("USE_BAZEL")
447
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800448 if ret.UseBazel() {
449 if err := os.MkdirAll(bpd, 0777); err != nil {
450 ctx.Fatalf("Failed to create bazel profile directory %q: %v", bpd, err)
451 }
452 }
453
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000454 if ret.UseBazel() {
455 ret.riggedDistDirForBazel = filepath.Join(ret.OutDir(), "dist")
456 } else {
457 // Not rigged
458 ret.riggedDistDirForBazel = ret.distDir
459 }
460
Patrice Arruda96850362020-08-11 20:41:11 +0000461 c := Config{ret}
462 storeConfigMetrics(ctx, c)
463 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700464}
465
Patrice Arruda13848222019-04-22 17:12:02 -0700466// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
467// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700468func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
469 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700470}
471
Patrice Arruda96850362020-08-11 20:41:11 +0000472// storeConfigMetrics selects a set of configuration information and store in
473// the metrics system for further analysis.
474func storeConfigMetrics(ctx Context, config Config) {
475 if ctx.Metrics == nil {
476 return
477 }
478
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400479 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000480
481 s := &smpb.SystemResourceInfo{
482 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
483 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
484 }
485 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000486}
487
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400488func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700489 c := &smpb.BuildConfig{
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400490 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
491 UseGoma: proto.Bool(config.UseGoma()),
492 UseRbe: proto.Bool(config.UseRBE()),
493 BazelAsNinja: proto.Bool(config.UseBazel()),
494 BazelMixedBuild: proto.Bool(config.bazelBuildMode() == mixedBuild),
495 }
Yu Liue737a992021-10-04 13:21:41 -0700496 c.Targets = append(c.Targets, config.arguments...)
497
498 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400499}
500
Patrice Arruda13848222019-04-22 17:12:02 -0700501// getConfigArgs processes the command arguments based on the build action and creates a set of new
502// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700503func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700504 // The next block of code verifies that the current directory is the root directory of the source
505 // tree. It then finds the relative path of dir based on the root directory of the source tree
506 // and verify that dir is inside of the source tree.
507 checkTopDir(ctx)
508 topDir, err := os.Getwd()
509 if err != nil {
510 ctx.Fatalf("Error retrieving top directory: %v", err)
511 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700512 dir, err = filepath.EvalSymlinks(dir)
513 if err != nil {
514 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
515 }
Patrice Arruda13848222019-04-22 17:12:02 -0700516 dir, err = filepath.Abs(dir)
517 if err != nil {
518 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
519 }
520 relDir, err := filepath.Rel(topDir, dir)
521 if err != nil {
522 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
523 }
524 // If there are ".." in the path, it's not in the source tree.
525 if strings.Contains(relDir, "..") {
526 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
527 }
528
529 configArgs := args[:]
530
531 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
532 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
533 targetNamePrefix := "MODULES-IN-"
534 if inList("GET-INSTALL-PATH", configArgs) {
535 targetNamePrefix = "GET-INSTALL-PATH-IN-"
536 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
537 }
538
Patrice Arruda13848222019-04-22 17:12:02 -0700539 var targets []string
540
541 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700542 case BUILD_MODULES:
543 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700544 case BUILD_MODULES_IN_A_DIRECTORY:
545 // If dir is the root source tree, all the modules are built of the source tree are built so
546 // no need to find the build file.
547 if topDir == dir {
548 break
549 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700550
Patrice Arruda13848222019-04-22 17:12:02 -0700551 buildFile := findBuildFile(ctx, relDir)
552 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700553 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700554 }
Patrice Arruda13848222019-04-22 17:12:02 -0700555 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
556 case BUILD_MODULES_IN_DIRECTORIES:
557 newConfigArgs, dirs := splitArgs(configArgs)
558 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700559 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700560 }
561
562 // Tidy only override all other specified targets.
563 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
564 if tidyOnly == "true" || tidyOnly == "1" {
565 configArgs = append(configArgs, "tidy_only")
566 } else {
567 configArgs = append(configArgs, targets...)
568 }
569
570 return configArgs
571}
572
573// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
574func convertToTarget(dir string, targetNamePrefix string) string {
575 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
576}
577
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700578// hasBuildFile returns true if dir contains an Android build file.
579func hasBuildFile(ctx Context, dir string) bool {
580 for _, buildFile := range buildFiles {
581 _, err := os.Stat(filepath.Join(dir, buildFile))
582 if err == nil {
583 return true
584 }
585 if !os.IsNotExist(err) {
586 ctx.Fatalf("Error retrieving the build file stats: %v", err)
587 }
588 }
589 return false
590}
591
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700592// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
593// in the current and any sub directory of dir. If a build file is not found, traverse the path
594// up by one directory and repeat again until either a build file is found or reached to the root
595// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
596// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700597func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700598 // If the string is empty or ".", assume it is top directory of the source tree.
599 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700600 return ""
601 }
602
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700603 found := false
604 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
605 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
606 if err != nil {
607 return err
608 }
609 if found {
610 return filepath.SkipDir
611 }
612 if info.IsDir() {
613 return nil
614 }
615 for _, buildFile := range buildFiles {
616 if info.Name() == buildFile {
617 found = true
618 return filepath.SkipDir
619 }
620 }
621 return nil
622 })
623 if err != nil {
624 ctx.Fatalf("Error finding Android build file: %v", err)
625 }
626
627 if found {
628 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700629 }
630 }
631
632 return ""
633}
634
635// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
636func splitArgs(args []string) (newArgs []string, dirs []string) {
637 specialArgs := map[string]bool{
638 "showcommands": true,
639 "snod": true,
640 "dist": true,
641 "checkbuild": true,
642 }
643
644 newArgs = []string{}
645 dirs = []string{}
646
647 for _, arg := range args {
648 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
649 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
650 newArgs = append(newArgs, arg)
651 continue
652 }
653
654 if _, ok := specialArgs[arg]; ok {
655 newArgs = append(newArgs, arg)
656 continue
657 }
658
659 dirs = append(dirs, arg)
660 }
661
662 return newArgs, dirs
663}
664
665// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
666// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
667// source root tree where the build action command was invoked. Each directory is validated if the
668// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700669func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700670 for _, dir := range dirs {
671 // The directory may have specified specific modules to build. ":" is the separator to separate
672 // the directory and the list of modules.
673 s := strings.Split(dir, ":")
674 l := len(s)
675 if l > 2 { // more than one ":" was specified.
676 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
677 }
678
679 dir = filepath.Join(relDir, s[0])
680 if _, err := os.Stat(dir); err != nil {
681 ctx.Fatalf("couldn't find directory %s", dir)
682 }
683
684 // Verify that if there are any targets specified after ":". Each target is separated by ",".
685 var newTargets []string
686 if l == 2 && s[1] != "" {
687 newTargets = strings.Split(s[1], ",")
688 if inList("", newTargets) {
689 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
690 }
691 }
692
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700693 // If there are specified targets to build in dir, an android build file must exist for the one
694 // shot build. For the non-targets case, find the appropriate build file and build all the
695 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700696 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700697 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700698 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
699 }
700 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700701 buildFile := findBuildFile(ctx, dir)
702 if buildFile == "" {
703 ctx.Fatalf("Build file not found for %s directory", dir)
704 }
705 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700706 }
707
Patrice Arruda13848222019-04-22 17:12:02 -0700708 targets = append(targets, newTargets...)
709 }
710
Dan Willemsence41e942019-07-29 23:39:30 -0700711 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700712}
713
Dan Willemsen9b587492017-07-10 22:13:00 -0700714func (c *configImpl) parseArgs(ctx Context, args []string) {
715 for i := 0; i < len(args); i++ {
716 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100717 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700718 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200719 } else if arg == "--empty-ninja-file" {
720 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100721 } else if arg == "--skip-ninja" {
722 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700723 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700724 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
725 // but it does run a Kati ninja file if the .kati_enabled marker file was created
726 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000727 c.skipConfig = true
728 c.skipKati = true
729 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100730 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000731 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100732 } else if arg == "--soong-only" {
733 c.skipKati = true
734 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200735 } else if arg == "--config-only" {
736 c.skipKati = true
737 c.skipKatiNinja = true
738 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700739 } else if arg == "--skip-config" {
740 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700741 } else if arg == "--skip-soong-tests" {
742 c.skipSoongTests = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500743 } else if arg == "--mk-metrics" {
744 c.reportMkMetrics = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700745 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700746 parseArgNum := func(def int) int {
747 if len(arg) > 2 {
748 p, err := strconv.ParseUint(arg[2:], 10, 31)
749 if err != nil {
750 ctx.Fatalf("Failed to parse %q: %v", arg, err)
751 }
752 return int(p)
753 } else if i+1 < len(args) {
754 p, err := strconv.ParseUint(args[i+1], 10, 31)
755 if err == nil {
756 i++
757 return int(p)
758 }
759 }
760 return def
761 }
762
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700763 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700764 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700765 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700766 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700767 } else {
768 ctx.Fatalln("Unknown option:", arg)
769 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700770 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700771 if k == "OUT_DIR" {
772 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
773 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700774 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700775 } else if arg == "dist" {
776 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200777 } else if arg == "json-module-graph" {
778 c.jsonModuleGraph = true
779 } else if arg == "bp2build" {
780 c.bp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200781 } else if arg == "queryview" {
782 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200783 } else if arg == "soong_docs" {
784 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700785 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700786 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800787 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700788 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700789 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700790 }
791 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700792}
793
Dan Willemsened869522018-01-08 14:58:46 -0800794func (c *configImpl) configureLocale(ctx Context) {
795 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
796 output, err := cmd.Output()
797
798 var locales []string
799 if err == nil {
800 locales = strings.Split(string(output), "\n")
801 } else {
802 // If we're unable to list the locales, let's assume en_US.UTF-8
803 locales = []string{"en_US.UTF-8"}
804 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
805 }
806
807 // gettext uses LANGUAGE, which is passed directly through
808
809 // For LANG and LC_*, only preserve the evaluated version of
810 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800811 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800812 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800813 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800814 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800815 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800816 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800817 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800818 }
819
820 c.environ.UnsetWithPrefix("LC_")
821
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800822 if userLang != "" {
823 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800824 }
825
826 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
827 // for others)
828 if inList("C.UTF-8", locales) {
829 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500830 } else if inList("C.utf8", locales) {
831 // These normalize to the same thing
832 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800833 } else if inList("en_US.UTF-8", locales) {
834 c.environ.Set("LANG", "en_US.UTF-8")
835 } else if inList("en_US.utf8", locales) {
836 // These normalize to the same thing
837 c.environ.Set("LANG", "en_US.UTF-8")
838 } else {
839 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
840 }
841}
842
Dan Willemsen1e704462016-08-21 15:17:17 -0700843func (c *configImpl) Environment() *Environment {
844 return c.environ
845}
846
847func (c *configImpl) Arguments() []string {
848 return c.arguments
849}
850
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200851func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200852 if len(c.Arguments()) > 0 {
853 // Explicit targets requested that are not special targets like b2pbuild
854 // or the JSON module graph
855 return true
856 }
857
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200858 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200859 // Command line was empty, the default Ninja target is built
860 return true
861 }
862
Liz Kammer88677422021-12-15 15:03:19 -0500863 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
864 if c.Dist() && !c.Bp2Build() {
865 return true
866 }
867
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200868 // build.ninja doesn't need to be generated
869 return false
870}
871
Dan Willemsen1e704462016-08-21 15:17:17 -0700872func (c *configImpl) OutDir() string {
873 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700874 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700875 }
876 return "out"
877}
878
Dan Willemsen8a073a82017-02-04 17:30:44 -0800879func (c *configImpl) DistDir() string {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000880 if c.UseBazel() {
881 return c.riggedDistDirForBazel
882 } else {
883 return c.distDir
884 }
885}
886
887func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700888 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800889}
890
Dan Willemsen1e704462016-08-21 15:17:17 -0700891func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000892 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700893 return c.arguments
894 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700895 return c.ninjaArgs
896}
897
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500898func (c *configImpl) BazelOutDir() string {
899 return filepath.Join(c.OutDir(), "bazel")
900}
901
Dan Willemsen1e704462016-08-21 15:17:17 -0700902func (c *configImpl) SoongOutDir() string {
903 return filepath.Join(c.OutDir(), "soong")
904}
905
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200906func (c *configImpl) PrebuiltOS() string {
907 switch runtime.GOOS {
908 case "linux":
909 return "linux-x86"
910 case "darwin":
911 return "darwin-x86"
912 default:
913 panic("Unknown GOOS")
914 }
915}
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100916
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200917func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -0700918 if c.SkipKatiNinja() {
919 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
920 } else {
921 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
922 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200923}
924
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200925func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100926 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200927}
928
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200929func (c *configImpl) UsedEnvFile(tag string) string {
930 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
931}
932
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200933func (c *configImpl) Bp2BuildMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100934 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200935}
936
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200937func (c *configImpl) SoongDocsHtml() string {
938 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
939}
940
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200941func (c *configImpl) QueryviewMarkerFile() string {
942 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
943}
944
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200945func (c *configImpl) ModuleGraphFile() string {
946 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
947}
948
kgui67007242022-01-25 13:50:25 +0800949func (c *configImpl) ModuleActionsFile() string {
950 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
951}
952
Jeff Gastonefc1b412017-03-29 17:29:06 -0700953func (c *configImpl) TempDir() string {
954 return shared.TempDirForOutDir(c.SoongOutDir())
955}
956
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700957func (c *configImpl) FileListDir() string {
958 return filepath.Join(c.OutDir(), ".module_paths")
959}
960
Dan Willemsen1e704462016-08-21 15:17:17 -0700961func (c *configImpl) KatiSuffix() string {
962 if c.katiSuffix != "" {
963 return c.katiSuffix
964 }
965 panic("SetKatiSuffix has not been called")
966}
967
Colin Cross37193492017-11-16 17:55:00 -0800968// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
969// user is interested in additional checks at the expense of build time.
970func (c *configImpl) Checkbuild() bool {
971 return c.checkbuild
972}
973
Dan Willemsen8a073a82017-02-04 17:30:44 -0800974func (c *configImpl) Dist() bool {
975 return c.dist
976}
977
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200978func (c *configImpl) JsonModuleGraph() bool {
979 return c.jsonModuleGraph
980}
981
982func (c *configImpl) Bp2Build() bool {
983 return c.bp2build
984}
985
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200986func (c *configImpl) Queryview() bool {
987 return c.queryview
988}
989
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200990func (c *configImpl) SoongDocs() bool {
991 return c.soongDocs
992}
993
Dan Willemsen1e704462016-08-21 15:17:17 -0700994func (c *configImpl) IsVerbose() bool {
995 return c.verbose
996}
997
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000998func (c *configImpl) SkipKati() bool {
999 return c.skipKati
1000}
1001
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001002func (c *configImpl) SkipKatiNinja() bool {
1003 return c.skipKatiNinja
1004}
1005
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001006func (c *configImpl) SkipSoong() bool {
1007 return c.skipSoong
1008}
1009
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001010func (c *configImpl) SkipNinja() bool {
1011 return c.skipNinja
1012}
1013
Anton Hansson5a7861a2021-06-04 10:09:01 +01001014func (c *configImpl) SetSkipNinja(v bool) {
1015 c.skipNinja = v
1016}
1017
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001018func (c *configImpl) SkipConfig() bool {
1019 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001020}
1021
Dan Willemsen1e704462016-08-21 15:17:17 -07001022func (c *configImpl) TargetProduct() string {
1023 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1024 return v
1025 }
1026 panic("TARGET_PRODUCT is not defined")
1027}
1028
Dan Willemsen02781d52017-05-12 19:28:13 -07001029func (c *configImpl) TargetDevice() string {
1030 return c.targetDevice
1031}
1032
1033func (c *configImpl) SetTargetDevice(device string) {
1034 c.targetDevice = device
1035}
1036
1037func (c *configImpl) TargetBuildVariant() string {
1038 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1039 return v
1040 }
1041 panic("TARGET_BUILD_VARIANT is not defined")
1042}
1043
Dan Willemsen1e704462016-08-21 15:17:17 -07001044func (c *configImpl) KatiArgs() []string {
1045 return c.katiArgs
1046}
1047
1048func (c *configImpl) Parallel() int {
1049 return c.parallel
1050}
1051
Colin Cross8b8bec32019-11-15 13:18:43 -08001052func (c *configImpl) HighmemParallel() int {
1053 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1054 return i
1055 }
1056
1057 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1058 parallel := c.Parallel()
1059 if c.UseRemoteBuild() {
1060 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1061 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1062 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1063 // Return 1/16th of the size of the local pool, rounding up.
1064 return (parallel + 15) / 16
1065 } else if c.totalRAM == 0 {
1066 // Couldn't detect the total RAM, don't restrict highmem processes.
1067 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001068 } else if c.totalRAM <= 16*1024*1024*1024 {
1069 // Less than 16GB of ram, restrict to 1 highmem processes
1070 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001071 } else if c.totalRAM <= 32*1024*1024*1024 {
1072 // Less than 32GB of ram, restrict to 2 highmem processes
1073 return 2
1074 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1075 // If less than 8GB total RAM per process, reduce the number of highmem processes
1076 return p
1077 }
1078 // No restriction on highmem processes
1079 return parallel
1080}
1081
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001082func (c *configImpl) TotalRAM() uint64 {
1083 return c.totalRAM
1084}
1085
Kousik Kumarec478642020-09-21 13:39:24 -04001086// ForceUseGoma determines whether we should override Goma deprecation
1087// and use Goma for the current build or not.
1088func (c *configImpl) ForceUseGoma() bool {
1089 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1090 v = strings.TrimSpace(v)
1091 if v != "" && v != "false" {
1092 return true
1093 }
1094 }
1095 return false
1096}
1097
Dan Willemsen1e704462016-08-21 15:17:17 -07001098func (c *configImpl) UseGoma() bool {
1099 if v, ok := c.environ.Get("USE_GOMA"); ok {
1100 v = strings.TrimSpace(v)
1101 if v != "" && v != "false" {
1102 return true
1103 }
1104 }
1105 return false
1106}
1107
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001108func (c *configImpl) StartGoma() bool {
1109 if !c.UseGoma() {
1110 return false
1111 }
1112
1113 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1114 v = strings.TrimSpace(v)
1115 if v != "" && v != "false" {
1116 return false
1117 }
1118 }
1119 return true
1120}
1121
Ramy Medhatbbf25672019-07-17 12:30:04 +00001122func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001123 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001124 v = strings.TrimSpace(v)
1125 if v != "" && v != "false" {
1126 return true
1127 }
1128 }
1129 return false
1130}
1131
Patrice Arruda0c1c4562020-11-11 13:01:25 -08001132func (c *configImpl) UseBazel() bool {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001133 return c.useBazel
Patrice Arruda0c1c4562020-11-11 13:01:25 -08001134}
1135
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001136func (c *configImpl) bazelBuildMode() bazelBuildMode {
1137 if c.Environment().IsEnvTrue("USE_BAZEL_ANALYSIS") {
1138 return mixedBuild
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001139 } else {
1140 return noBazel
1141 }
1142}
1143
Ramy Medhatbbf25672019-07-17 12:30:04 +00001144func (c *configImpl) StartRBE() bool {
1145 if !c.UseRBE() {
1146 return false
1147 }
1148
1149 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1150 v = strings.TrimSpace(v)
1151 if v != "" && v != "false" {
1152 return false
1153 }
1154 }
1155 return true
1156}
1157
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001158func (c *configImpl) rbeProxyLogsDir() string {
1159 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001160 if v, ok := c.environ.Get(f); ok {
1161 return v
1162 }
1163 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001164 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1165 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001166}
1167
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001168func (c *configImpl) shouldCleanupRBELogsDir() bool {
1169 // Perform a log directory cleanup only when the log directory
1170 // is auto created by the build rather than user-specified.
1171 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1172 if _, ok := c.environ.Get(f); ok {
1173 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001174 }
1175 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001176 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001177}
1178
1179func (c *configImpl) rbeExecRoot() string {
1180 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1181 if v, ok := c.environ.Get(f); ok {
1182 return v
1183 }
1184 }
1185 wd, err := os.Getwd()
1186 if err != nil {
1187 return ""
1188 }
1189 return wd
1190}
1191
1192func (c *configImpl) rbeDir() string {
1193 if v, ok := c.environ.Get("RBE_DIR"); ok {
1194 return v
1195 }
1196 return "prebuilts/remoteexecution-client/live/"
1197}
1198
1199func (c *configImpl) rbeReproxy() string {
1200 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1201 if v, ok := c.environ.Get(f); ok {
1202 return v
1203 }
1204 }
1205 return filepath.Join(c.rbeDir(), "reproxy")
1206}
1207
1208func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001209 credFlags := []string{
1210 "use_application_default_credentials",
1211 "use_gce_credentials",
1212 "credential_file",
1213 "use_google_prod_creds",
1214 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001215 for _, cf := range credFlags {
1216 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1217 if v, ok := c.environ.Get(f); ok {
1218 v = strings.TrimSpace(v)
1219 if v != "" && v != "false" && v != "0" {
1220 return "RBE_" + cf, v
1221 }
1222 }
1223 }
1224 }
1225 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001226}
1227
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001228func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1229 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1230 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1231
1232 name := filepath.Join(dir, base)
1233 if len(name) < maxNameLen {
1234 return name, nil
1235 }
1236
1237 name = filepath.Join("/tmp", base)
1238 if len(name) < maxNameLen {
1239 return name, nil
1240 }
1241
1242 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1243}
1244
Kousik Kumar7bc78192022-04-27 14:52:56 -04001245// IsGooglerEnvironment returns true if the current build is running
1246// on a Google developer machine and false otherwise.
1247func (c *configImpl) IsGooglerEnvironment() bool {
1248 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1249 if v, ok := c.environ.Get(cf); ok {
1250 return v == "googler"
1251 }
1252 return false
1253}
1254
1255// GoogleProdCredsExist determine whether credentials exist on the
1256// Googler machine to use remote execution.
1257func (c *configImpl) GoogleProdCredsExist() bool {
1258 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1259 return false
1260 }
1261 return true
1262}
1263
1264// UseRemoteBuild indicates whether to use a remote build acceleration system
1265// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001266func (c *configImpl) UseRemoteBuild() bool {
1267 return c.UseGoma() || c.UseRBE()
1268}
1269
Kousik Kumar7bc78192022-04-27 14:52:56 -04001270// StubbyExists checks whether the stubby binary exists on the machine running
1271// the build.
1272func (c *configImpl) StubbyExists() bool {
1273 if _, err := exec.LookPath("stubby"); err != nil {
1274 return false
1275 }
1276 return true
1277}
1278
Dan Willemsen1e704462016-08-21 15:17:17 -07001279// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001280// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001281// still limited by Parallel()
1282func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001283 if !c.UseRemoteBuild() {
1284 return 0
1285 }
1286 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1287 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001288 }
1289 return 500
1290}
1291
1292func (c *configImpl) SetKatiArgs(args []string) {
1293 c.katiArgs = args
1294}
1295
1296func (c *configImpl) SetNinjaArgs(args []string) {
1297 c.ninjaArgs = args
1298}
1299
1300func (c *configImpl) SetKatiSuffix(suffix string) {
1301 c.katiSuffix = suffix
1302}
1303
Dan Willemsene0879fc2017-08-04 15:06:27 -07001304func (c *configImpl) LastKatiSuffixFile() string {
1305 return filepath.Join(c.OutDir(), "last_kati_suffix")
1306}
1307
1308func (c *configImpl) HasKatiSuffix() bool {
1309 return c.katiSuffix != ""
1310}
1311
Dan Willemsen1e704462016-08-21 15:17:17 -07001312func (c *configImpl) KatiEnvFile() string {
1313 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1314}
1315
Dan Willemsen29971232018-09-26 14:58:30 -07001316func (c *configImpl) KatiBuildNinjaFile() string {
1317 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001318}
1319
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001320func (c *configImpl) KatiPackageNinjaFile() string {
1321 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1322}
1323
Dan Willemsen1e704462016-08-21 15:17:17 -07001324func (c *configImpl) SoongNinjaFile() string {
1325 return filepath.Join(c.SoongOutDir(), "build.ninja")
1326}
1327
1328func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001329 if c.katiSuffix == "" {
1330 return filepath.Join(c.OutDir(), "combined.ninja")
1331 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001332 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1333}
1334
1335func (c *configImpl) SoongAndroidMk() string {
1336 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1337}
1338
1339func (c *configImpl) SoongMakeVarsMk() string {
1340 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1341}
1342
Dan Willemsenf052f782017-05-18 15:29:04 -07001343func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001344 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001345}
1346
Dan Willemsen02781d52017-05-12 19:28:13 -07001347func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001348 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1349}
1350
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001351func (c *configImpl) KatiPackageMkDir() string {
1352 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1353}
1354
Dan Willemsenf052f782017-05-18 15:29:04 -07001355func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001356 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001357}
1358
1359func (c *configImpl) HostOut() string {
1360 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1361}
1362
1363// This probably needs to be multi-valued, so not exporting it for now
1364func (c *configImpl) hostCrossOut() string {
1365 if runtime.GOOS == "linux" {
1366 return filepath.Join(c.hostOutRoot(), "windows-x86")
1367 } else {
1368 return ""
1369 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001370}
1371
Dan Willemsen1e704462016-08-21 15:17:17 -07001372func (c *configImpl) HostPrebuiltTag() string {
1373 if runtime.GOOS == "linux" {
1374 return "linux-x86"
1375 } else if runtime.GOOS == "darwin" {
1376 return "darwin-x86"
1377 } else {
1378 panic("Unsupported OS")
1379 }
1380}
Dan Willemsenf173d592017-04-27 14:28:00 -07001381
Dan Willemsen8122bd52017-10-12 20:20:41 -07001382func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001383 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1384 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001385 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1386 if _, err := os.Stat(asan); err == nil {
1387 return asan
1388 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001389 }
1390 }
1391 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1392}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001393
1394func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1395 c.brokenDupRules = val
1396}
1397
1398func (c *configImpl) BuildBrokenDupRules() bool {
1399 return c.brokenDupRules
1400}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001401
Dan Willemsen25e6f092019-04-09 10:22:43 -07001402func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1403 c.brokenUsesNetwork = val
1404}
1405
1406func (c *configImpl) BuildBrokenUsesNetwork() bool {
1407 return c.brokenUsesNetwork
1408}
1409
Dan Willemsene3336352020-01-02 19:10:38 -08001410func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1411 c.brokenNinjaEnvVars = val
1412}
1413
1414func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1415 return c.brokenNinjaEnvVars
1416}
1417
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001418func (c *configImpl) SetTargetDeviceDir(dir string) {
1419 c.targetDeviceDir = dir
1420}
1421
1422func (c *configImpl) TargetDeviceDir() string {
1423 return c.targetDeviceDir
1424}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001425
Patrice Arruda219eef32020-06-01 17:29:30 +00001426func (c *configImpl) BuildDateTime() string {
1427 return c.buildDateTime
1428}
1429
1430func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001431 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001432}
Patrice Arruda83842d72020-12-08 19:42:08 +00001433
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001434// LogsDir returns the absolute path to the logs directory where build log and
1435// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001436// directory. If the argument dist is specified, the logs directory
1437// is <dist_dir>/logs.
1438func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001439 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001440 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001441 // 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 -05001442 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001443 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001444 absDir, err := filepath.Abs(dir)
1445 if err != nil {
1446 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1447 os.Exit(1)
1448 }
1449 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001450}
1451
1452// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1453// where the bazel profiles are located.
1454func (c *configImpl) BazelMetricsDir() string {
1455 return filepath.Join(c.LogsDir(), "bazel_metrics")
1456}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001457
Chris Parsons53f68ae2022-03-03 12:01:40 -05001458// MkFileMetrics returns the file path for make-related metrics.
1459func (c *configImpl) MkMetrics() string {
1460 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1461}
1462
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001463func (c *configImpl) SetEmptyNinjaFile(v bool) {
1464 c.emptyNinjaFile = v
1465}
1466
1467func (c *configImpl) EmptyNinjaFile() bool {
1468 return c.emptyNinjaFile
1469}
Yu Liu6e13b402021-07-27 14:29:06 -07001470
1471func GetMetricsUploader(topDir string, env *Environment) string {
1472 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1473 metricsUploader := filepath.Join(topDir, p)
1474 if _, err := os.Stat(metricsUploader); err == nil {
1475 return metricsUploader
1476 }
1477 }
1478
1479 return ""
1480}