blob: 36119f0f1cf5f4eecd13f7637e375ab98c1603a1 [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
Spandan Das5af0bd32022-09-28 20:43:08 +000074 apiBp2build bool // Generate BUILD files for Soong modules that contribute APIs
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020075 bp2build bool
Lukacs T. Berki3a821692021-09-06 17:08:02 +020076 queryview bool
Chris Parsons53f68ae2022-03-03 12:01:40 -050077 reportMkMetrics bool // Collect and report mk2bp migration progress metrics.
Lukacs T. Berkic6012f32021-09-06 18:31:46 +020078 soongDocs bool
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020079 skipConfig bool
80 skipKati bool
81 skipKatiNinja bool
82 skipSoong bool
83 skipNinja bool
84 skipSoongTests bool
Dan Willemsen1e704462016-08-21 15:17:17 -070085
86 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070087 katiArgs []string
88 ninjaArgs []string
89 katiSuffix string
90 targetDevice string
91 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +000092 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -070093
Dan Willemsen2bb82d02019-12-27 09:35:42 -080094 // Autodetected
95 totalRAM uint64
96
Dan Willemsene3336352020-01-02 19:10:38 -080097 brokenDupRules bool
98 brokenUsesNetwork bool
99 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -0700100
101 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000102
MarkDacekb78465d2022-10-18 20:10:16 +0000103 bazelProdMode bool
104 bazelDevMode bool
105 bazelStagingMode bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000106
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700107 // Set by multiproduct_kati
108 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700109
110 metricsUploader string
Dan Willemsen1e704462016-08-21 15:17:17 -0700111}
112
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800113const srcDirFileCheck = "build/soong/root.bp"
114
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700115var buildFiles = []string{"Android.mk", "Android.bp"}
116
Patrice Arruda13848222019-04-22 17:12:02 -0700117type BuildAction uint
118
119const (
120 // Builds all of the modules and their dependencies of a specified directory, relative to the root
121 // directory of the source tree.
122 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
123
124 // Builds all of the modules and their dependencies of a list of specified directories. All specified
125 // directories are relative to the root directory of the source tree.
126 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700127
128 // Build a list of specified modules. If none was specified, simply build the whole source tree.
129 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700130)
131
132// checkTopDir validates that the current directory is at the root directory of the source tree.
133func checkTopDir(ctx Context) {
134 if _, err := os.Stat(srcDirFileCheck); err != nil {
135 if os.IsNotExist(err) {
136 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
137 }
138 ctx.Fatalln("Error verifying tree state:", err)
139 }
140}
141
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500142// fetchEnvConfig optionally fetches environment config from an
143// experiments system to control Soong features dynamically.
144func fetchEnvConfig(ctx Context, config *configImpl, envConfigName string) error {
David Goldsmith62243a32022-04-08 13:42:04 +0000145 configName := envConfigName + "." + jsonSuffix
Kousik Kumarc75e1292022-07-07 02:20:51 +0000146 expConfigFetcher := &smpb.ExpConfigFetcher{Filename: &configName}
David Goldsmith62243a32022-04-08 13:42:04 +0000147 defer func() {
148 ctx.Metrics.ExpConfigFetcher(expConfigFetcher)
149 }()
Kousik Kumarc75e1292022-07-07 02:20:51 +0000150 if !config.GoogleProdCredsExist() {
151 status := smpb.ExpConfigFetcher_MISSING_GCERT
152 expConfigFetcher.Status = &status
153 return nil
154 }
David Goldsmith62243a32022-04-08 13:42:04 +0000155
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500156 s, err := os.Stat(configFetcher)
157 if err != nil {
158 if os.IsNotExist(err) {
159 return nil
160 }
161 return err
162 }
163 if s.Mode()&0111 == 0 {
David Goldsmith62243a32022-04-08 13:42:04 +0000164 status := smpb.ExpConfigFetcher_ERROR
165 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500166 return fmt.Errorf("configuration fetcher binary %v is not executable: %v", configFetcher, s.Mode())
167 }
168
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500169 tCtx, cancel := context.WithTimeout(ctx, envConfigFetchTimeout)
170 defer cancel()
David Goldsmith62243a32022-04-08 13:42:04 +0000171 fetchStart := time.Now()
172 cmd := exec.CommandContext(tCtx, configFetcher, "-output_config_dir", config.OutDir(),
173 "-output_config_name", configName)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500174 if err := cmd.Start(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000175 status := smpb.ExpConfigFetcher_ERROR
176 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500177 return err
178 }
179
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500180 if err := cmd.Wait(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000181 status := smpb.ExpConfigFetcher_ERROR
182 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500183 return err
184 }
David Goldsmith62243a32022-04-08 13:42:04 +0000185 fetchEnd := time.Now()
186 expConfigFetcher.Micros = proto.Uint64(uint64(fetchEnd.Sub(fetchStart).Microseconds()))
187 outConfigFilePath := filepath.Join(config.OutDir(), configName)
188 expConfigFetcher.Filename = proto.String(outConfigFilePath)
189 if _, err := os.Stat(outConfigFilePath); err == nil {
190 status := smpb.ExpConfigFetcher_CONFIG
191 expConfigFetcher.Status = &status
192 } else {
193 status := smpb.ExpConfigFetcher_NO_CONFIG
194 expConfigFetcher.Status = &status
195 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500196 return nil
197}
198
199func loadEnvConfig(ctx Context, config *configImpl) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500200 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
201 if bc == "" {
202 return nil
203 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500204
205 if err := fetchEnvConfig(ctx, config, bc); err != nil {
Kousik Kumar595fb1c2022-06-24 16:49:52 +0000206 ctx.Verbosef("Failed to fetch config file: %v\n", err)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500207 }
208
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500209 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500210 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500211 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500212 envConfigDir,
213 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500214 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500215 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
216 envVarsJSON, err := ioutil.ReadFile(cfgFile)
217 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500218 continue
219 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500220 ctx.Verbosef("Loading config file %v\n", cfgFile)
221 var envVars map[string]map[string]string
222 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
223 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
224 continue
225 }
226 for k, v := range envVars["env"] {
227 if os.Getenv(k) != "" {
228 continue
229 }
230 config.environ.Set(k, v)
231 }
232 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
233 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500234 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500235
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500236 return nil
237}
238
Dan Willemsen1e704462016-08-21 15:17:17 -0700239func NewConfig(ctx Context, args ...string) Config {
240 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000241 environ: OsEnvironment(),
242 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700243 }
244
Patrice Arruda90109172020-07-28 18:07:27 +0000245 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700246 ret.parallel = runtime.NumCPU() + 2
247 ret.keepGoing = 1
248
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800249 ret.totalRAM = detectTotalRAM(ctx)
250
Dan Willemsen9b587492017-07-10 22:13:00 -0700251 ret.parseArgs(ctx, args)
252
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800253 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700254 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
255 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
256 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800257 outDir := "out"
258 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
259 if wd, err := os.Getwd(); err != nil {
260 ctx.Fatalln("Failed to get working directory:", err)
261 } else {
262 outDir = filepath.Join(baseDir, filepath.Base(wd))
263 }
264 }
265 ret.environ.Set("OUT_DIR", outDir)
266 }
267
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500268 // loadEnvConfig needs to know what the OUT_DIR is, so it should
269 // be called after we determine the appropriate out directory.
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500270 if err := loadEnvConfig(ctx, ret); err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500271 ctx.Fatalln("Failed to parse env config files: %v", err)
272 }
273
Dan Willemsen2d31a442018-10-20 21:33:41 -0700274 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
275 ret.distDir = filepath.Clean(distDir)
276 } else {
277 ret.distDir = filepath.Join(ret.OutDir(), "dist")
278 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700279
Spandan Das05063612021-06-25 01:39:04 +0000280 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
281 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
282 }
283
Dan Willemsen1e704462016-08-21 15:17:17 -0700284 ret.environ.Unset(
285 // We're already using it
286 "USE_SOONG_UI",
287
288 // We should never use GOROOT/GOPATH from the shell environment
289 "GOROOT",
290 "GOPATH",
291
292 // These should only come from Soong, not the environment.
293 "CLANG",
294 "CLANG_CXX",
295 "CCC_CC",
296 "CCC_CXX",
297
298 // Used by the goma compiler wrapper, but should only be set by
299 // gomacc
300 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800301
302 // We handle this above
303 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700304
Dan Willemsen2d31a442018-10-20 21:33:41 -0700305 // This is handled above too, and set for individual commands later
306 "DIST_DIR",
307
Dan Willemsen68a09852017-04-18 13:56:57 -0700308 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000309 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700310 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700311 "DISPLAY",
312 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700313 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700314 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700315
316 // Drop make flags
317 "MAKEFLAGS",
318 "MAKELEVEL",
319 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700320
321 // Set in envsetup.sh, reset in makefiles
322 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700323
324 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
325 "ANDROID_BUILD_TOP",
326 "ANDROID_HOST_OUT",
327 "ANDROID_PRODUCT_OUT",
328 "ANDROID_HOST_OUT_TESTCASES",
329 "ANDROID_TARGET_OUT_TESTCASES",
330 "ANDROID_TOOLCHAIN",
331 "ANDROID_TOOLCHAIN_2ND_ARCH",
332 "ANDROID_DEV_SCRIPTS",
333 "ANDROID_EMULATOR_PREBUILTS",
334 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700335 )
336
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400337 if ret.UseGoma() || ret.ForceUseGoma() {
338 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
339 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400340 }
341
Dan Willemsen1e704462016-08-21 15:17:17 -0700342 // Tell python not to spam the source tree with .pyc files.
343 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
344
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400345 tmpDir := absPath(ctx, ret.TempDir())
346 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800347
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700348 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
349 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
350 "llvm-binutils-stable/llvm-symbolizer")
351 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
352
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800353 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700354 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800355
Yu Liu6e13b402021-07-27 14:29:06 -0700356 srcDir := absPath(ctx, ".")
357 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700358 ctx.Println("You are building in a directory whose absolute path contains a space character:")
359 ctx.Println()
360 ctx.Printf("%q\n", srcDir)
361 ctx.Println()
362 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700363 }
364
Yu Liu6e13b402021-07-27 14:29:06 -0700365 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
366
Dan Willemsendb8457c2017-05-12 16:38:17 -0700367 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700368 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
369 ctx.Println()
370 ctx.Printf("%q\n", outDir)
371 ctx.Println()
372 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700373 }
374
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000375 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700376 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
377 ctx.Println()
378 ctx.Printf("%q\n", distDir)
379 ctx.Println()
380 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700381 }
382
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700383 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000384 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
385 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100386 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800387 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700388 javaHome := func() string {
389 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
390 return override
391 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000392 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
393 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 +0100394 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000395 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
396 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
397 }
398 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700399 }()
400 absJavaHome := absPath(ctx, javaHome)
401
Dan Willemsened869522018-01-08 14:58:46 -0800402 ret.configureLocale(ctx)
403
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700404 newPath := []string{filepath.Join(absJavaHome, "bin")}
405 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
406 newPath = append(newPath, path)
407 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100408
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700409 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
410 ret.environ.Set("JAVA_HOME", absJavaHome)
411 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000412 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
413 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100414 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700415 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
416
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800417 outDir := ret.OutDir()
418 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800419 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800420 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800421 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800422 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800423 }
Colin Cross28f527c2019-11-26 16:19:04 -0800424
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800425 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
426
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400427 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400428 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400429 ret.environ.Set(k, v)
430 }
431 }
432
Patrice Arruda83842d72020-12-08 19:42:08 +0000433 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800434 if err := os.RemoveAll(bpd); err != nil {
435 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
436 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000437
Patrice Arruda96850362020-08-11 20:41:11 +0000438 c := Config{ret}
439 storeConfigMetrics(ctx, c)
440 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700441}
442
Patrice Arruda13848222019-04-22 17:12:02 -0700443// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
444// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700445func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
446 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700447}
448
Patrice Arruda96850362020-08-11 20:41:11 +0000449// storeConfigMetrics selects a set of configuration information and store in
450// the metrics system for further analysis.
451func storeConfigMetrics(ctx Context, config Config) {
452 if ctx.Metrics == nil {
453 return
454 }
455
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400456 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000457
458 s := &smpb.SystemResourceInfo{
459 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
460 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
461 }
462 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000463}
464
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400465func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700466 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400467 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
468 UseGoma: proto.Bool(config.UseGoma()),
469 UseRbe: proto.Bool(config.UseRBE()),
470 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
471 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400472 }
Yu Liue737a992021-10-04 13:21:41 -0700473 c.Targets = append(c.Targets, config.arguments...)
474
475 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400476}
477
Patrice Arruda13848222019-04-22 17:12:02 -0700478// getConfigArgs processes the command arguments based on the build action and creates a set of new
479// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700480func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700481 // The next block of code verifies that the current directory is the root directory of the source
482 // tree. It then finds the relative path of dir based on the root directory of the source tree
483 // and verify that dir is inside of the source tree.
484 checkTopDir(ctx)
485 topDir, err := os.Getwd()
486 if err != nil {
487 ctx.Fatalf("Error retrieving top directory: %v", err)
488 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700489 dir, err = filepath.EvalSymlinks(dir)
490 if err != nil {
491 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
492 }
Patrice Arruda13848222019-04-22 17:12:02 -0700493 dir, err = filepath.Abs(dir)
494 if err != nil {
495 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
496 }
497 relDir, err := filepath.Rel(topDir, dir)
498 if err != nil {
499 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
500 }
501 // If there are ".." in the path, it's not in the source tree.
502 if strings.Contains(relDir, "..") {
503 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
504 }
505
506 configArgs := args[:]
507
508 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
509 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
510 targetNamePrefix := "MODULES-IN-"
511 if inList("GET-INSTALL-PATH", configArgs) {
512 targetNamePrefix = "GET-INSTALL-PATH-IN-"
513 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
514 }
515
Patrice Arruda13848222019-04-22 17:12:02 -0700516 var targets []string
517
518 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700519 case BUILD_MODULES:
520 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700521 case BUILD_MODULES_IN_A_DIRECTORY:
522 // If dir is the root source tree, all the modules are built of the source tree are built so
523 // no need to find the build file.
524 if topDir == dir {
525 break
526 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700527
Patrice Arruda13848222019-04-22 17:12:02 -0700528 buildFile := findBuildFile(ctx, relDir)
529 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700530 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700531 }
Patrice Arruda13848222019-04-22 17:12:02 -0700532 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
533 case BUILD_MODULES_IN_DIRECTORIES:
534 newConfigArgs, dirs := splitArgs(configArgs)
535 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700536 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700537 }
538
539 // Tidy only override all other specified targets.
540 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
541 if tidyOnly == "true" || tidyOnly == "1" {
542 configArgs = append(configArgs, "tidy_only")
543 } else {
544 configArgs = append(configArgs, targets...)
545 }
546
547 return configArgs
548}
549
550// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
551func convertToTarget(dir string, targetNamePrefix string) string {
552 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
553}
554
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700555// hasBuildFile returns true if dir contains an Android build file.
556func hasBuildFile(ctx Context, dir string) bool {
557 for _, buildFile := range buildFiles {
558 _, err := os.Stat(filepath.Join(dir, buildFile))
559 if err == nil {
560 return true
561 }
562 if !os.IsNotExist(err) {
563 ctx.Fatalf("Error retrieving the build file stats: %v", err)
564 }
565 }
566 return false
567}
568
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700569// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
570// in the current and any sub directory of dir. If a build file is not found, traverse the path
571// up by one directory and repeat again until either a build file is found or reached to the root
572// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
573// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700574func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700575 // If the string is empty or ".", assume it is top directory of the source tree.
576 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700577 return ""
578 }
579
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700580 found := false
581 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
582 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
583 if err != nil {
584 return err
585 }
586 if found {
587 return filepath.SkipDir
588 }
589 if info.IsDir() {
590 return nil
591 }
592 for _, buildFile := range buildFiles {
593 if info.Name() == buildFile {
594 found = true
595 return filepath.SkipDir
596 }
597 }
598 return nil
599 })
600 if err != nil {
601 ctx.Fatalf("Error finding Android build file: %v", err)
602 }
603
604 if found {
605 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700606 }
607 }
608
609 return ""
610}
611
612// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
613func splitArgs(args []string) (newArgs []string, dirs []string) {
614 specialArgs := map[string]bool{
615 "showcommands": true,
616 "snod": true,
617 "dist": true,
618 "checkbuild": true,
619 }
620
621 newArgs = []string{}
622 dirs = []string{}
623
624 for _, arg := range args {
625 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
626 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
627 newArgs = append(newArgs, arg)
628 continue
629 }
630
631 if _, ok := specialArgs[arg]; ok {
632 newArgs = append(newArgs, arg)
633 continue
634 }
635
636 dirs = append(dirs, arg)
637 }
638
639 return newArgs, dirs
640}
641
642// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
643// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
644// source root tree where the build action command was invoked. Each directory is validated if the
645// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700646func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700647 for _, dir := range dirs {
648 // The directory may have specified specific modules to build. ":" is the separator to separate
649 // the directory and the list of modules.
650 s := strings.Split(dir, ":")
651 l := len(s)
652 if l > 2 { // more than one ":" was specified.
653 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
654 }
655
656 dir = filepath.Join(relDir, s[0])
657 if _, err := os.Stat(dir); err != nil {
658 ctx.Fatalf("couldn't find directory %s", dir)
659 }
660
661 // Verify that if there are any targets specified after ":". Each target is separated by ",".
662 var newTargets []string
663 if l == 2 && s[1] != "" {
664 newTargets = strings.Split(s[1], ",")
665 if inList("", newTargets) {
666 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
667 }
668 }
669
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700670 // If there are specified targets to build in dir, an android build file must exist for the one
671 // shot build. For the non-targets case, find the appropriate build file and build all the
672 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700673 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700674 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700675 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
676 }
677 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700678 buildFile := findBuildFile(ctx, dir)
679 if buildFile == "" {
680 ctx.Fatalf("Build file not found for %s directory", dir)
681 }
682 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700683 }
684
Patrice Arruda13848222019-04-22 17:12:02 -0700685 targets = append(targets, newTargets...)
686 }
687
Dan Willemsence41e942019-07-29 23:39:30 -0700688 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700689}
690
Dan Willemsen9b587492017-07-10 22:13:00 -0700691func (c *configImpl) parseArgs(ctx Context, args []string) {
692 for i := 0; i < len(args); i++ {
693 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100694 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700695 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200696 } else if arg == "--empty-ninja-file" {
697 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100698 } else if arg == "--skip-ninja" {
699 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700700 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700701 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
702 // but it does run a Kati ninja file if the .kati_enabled marker file was created
703 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000704 c.skipConfig = true
705 c.skipKati = true
706 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100707 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000708 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100709 } else if arg == "--soong-only" {
710 c.skipKati = true
711 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200712 } else if arg == "--config-only" {
713 c.skipKati = true
714 c.skipKatiNinja = true
715 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700716 } else if arg == "--skip-config" {
717 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700718 } else if arg == "--skip-soong-tests" {
719 c.skipSoongTests = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500720 } else if arg == "--mk-metrics" {
721 c.reportMkMetrics = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400722 } else if arg == "--bazel-mode" {
723 c.bazelProdMode = true
724 } else if arg == "--bazel-mode-dev" {
725 c.bazelDevMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000726 } else if arg == "--bazel-mode-staging" {
727 c.bazelStagingMode = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700728 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700729 parseArgNum := func(def int) int {
730 if len(arg) > 2 {
731 p, err := strconv.ParseUint(arg[2:], 10, 31)
732 if err != nil {
733 ctx.Fatalf("Failed to parse %q: %v", arg, err)
734 }
735 return int(p)
736 } else if i+1 < len(args) {
737 p, err := strconv.ParseUint(args[i+1], 10, 31)
738 if err == nil {
739 i++
740 return int(p)
741 }
742 }
743 return def
744 }
745
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700746 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700747 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700748 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700749 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700750 } else {
751 ctx.Fatalln("Unknown option:", arg)
752 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700753 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700754 if k == "OUT_DIR" {
755 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
756 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700757 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700758 } else if arg == "dist" {
759 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200760 } else if arg == "json-module-graph" {
761 c.jsonModuleGraph = true
762 } else if arg == "bp2build" {
763 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000764 } else if arg == "api_bp2build" {
765 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200766 } else if arg == "queryview" {
767 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200768 } else if arg == "soong_docs" {
769 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700770 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700771 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800772 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700773 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700774 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700775 }
776 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700777}
778
Dan Willemsened869522018-01-08 14:58:46 -0800779func (c *configImpl) configureLocale(ctx Context) {
780 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
781 output, err := cmd.Output()
782
783 var locales []string
784 if err == nil {
785 locales = strings.Split(string(output), "\n")
786 } else {
787 // If we're unable to list the locales, let's assume en_US.UTF-8
788 locales = []string{"en_US.UTF-8"}
789 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
790 }
791
792 // gettext uses LANGUAGE, which is passed directly through
793
794 // For LANG and LC_*, only preserve the evaluated version of
795 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800796 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800797 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800798 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800799 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800800 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800801 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800802 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800803 }
804
805 c.environ.UnsetWithPrefix("LC_")
806
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800807 if userLang != "" {
808 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800809 }
810
811 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
812 // for others)
813 if inList("C.UTF-8", locales) {
814 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500815 } else if inList("C.utf8", locales) {
816 // These normalize to the same thing
817 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800818 } else if inList("en_US.UTF-8", locales) {
819 c.environ.Set("LANG", "en_US.UTF-8")
820 } else if inList("en_US.utf8", locales) {
821 // These normalize to the same thing
822 c.environ.Set("LANG", "en_US.UTF-8")
823 } else {
824 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
825 }
826}
827
Dan Willemsen1e704462016-08-21 15:17:17 -0700828func (c *configImpl) Environment() *Environment {
829 return c.environ
830}
831
832func (c *configImpl) Arguments() []string {
833 return c.arguments
834}
835
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200836func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200837 if len(c.Arguments()) > 0 {
838 // Explicit targets requested that are not special targets like b2pbuild
839 // or the JSON module graph
840 return true
841 }
842
Spandan Das5af0bd32022-09-28 20:43:08 +0000843 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200844 // Command line was empty, the default Ninja target is built
845 return true
846 }
847
Liz Kammer88677422021-12-15 15:03:19 -0500848 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
849 if c.Dist() && !c.Bp2Build() {
850 return true
851 }
852
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200853 // build.ninja doesn't need to be generated
854 return false
855}
856
Dan Willemsen1e704462016-08-21 15:17:17 -0700857func (c *configImpl) OutDir() string {
858 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700859 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700860 }
861 return "out"
862}
863
Dan Willemsen8a073a82017-02-04 17:30:44 -0800864func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400865 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000866}
867
868func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700869 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800870}
871
Dan Willemsen1e704462016-08-21 15:17:17 -0700872func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000873 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700874 return c.arguments
875 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700876 return c.ninjaArgs
877}
878
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500879func (c *configImpl) BazelOutDir() string {
880 return filepath.Join(c.OutDir(), "bazel")
881}
882
Dan Willemsen1e704462016-08-21 15:17:17 -0700883func (c *configImpl) SoongOutDir() string {
884 return filepath.Join(c.OutDir(), "soong")
885}
886
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200887func (c *configImpl) PrebuiltOS() string {
888 switch runtime.GOOS {
889 case "linux":
890 return "linux-x86"
891 case "darwin":
892 return "darwin-x86"
893 default:
894 panic("Unknown GOOS")
895 }
896}
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100897
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200898func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -0700899 if c.SkipKatiNinja() {
900 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
901 } else {
902 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
903 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200904}
905
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200906func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100907 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200908}
909
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200910func (c *configImpl) UsedEnvFile(tag string) string {
911 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
912}
913
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000914func (c *configImpl) Bp2BuildFilesMarkerFile() string {
915 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
916}
917
918func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100919 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200920}
921
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200922func (c *configImpl) SoongDocsHtml() string {
923 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
924}
925
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200926func (c *configImpl) QueryviewMarkerFile() string {
927 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
928}
929
Spandan Das5af0bd32022-09-28 20:43:08 +0000930func (c *configImpl) ApiBp2buildMarkerFile() string {
931 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
932}
933
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200934func (c *configImpl) ModuleGraphFile() string {
935 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
936}
937
kgui67007242022-01-25 13:50:25 +0800938func (c *configImpl) ModuleActionsFile() string {
939 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
940}
941
Jeff Gastonefc1b412017-03-29 17:29:06 -0700942func (c *configImpl) TempDir() string {
943 return shared.TempDirForOutDir(c.SoongOutDir())
944}
945
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700946func (c *configImpl) FileListDir() string {
947 return filepath.Join(c.OutDir(), ".module_paths")
948}
949
Dan Willemsen1e704462016-08-21 15:17:17 -0700950func (c *configImpl) KatiSuffix() string {
951 if c.katiSuffix != "" {
952 return c.katiSuffix
953 }
954 panic("SetKatiSuffix has not been called")
955}
956
Colin Cross37193492017-11-16 17:55:00 -0800957// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
958// user is interested in additional checks at the expense of build time.
959func (c *configImpl) Checkbuild() bool {
960 return c.checkbuild
961}
962
Dan Willemsen8a073a82017-02-04 17:30:44 -0800963func (c *configImpl) Dist() bool {
964 return c.dist
965}
966
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200967func (c *configImpl) JsonModuleGraph() bool {
968 return c.jsonModuleGraph
969}
970
971func (c *configImpl) Bp2Build() bool {
972 return c.bp2build
973}
974
Spandan Das5af0bd32022-09-28 20:43:08 +0000975func (c *configImpl) ApiBp2build() bool {
976 return c.apiBp2build
977}
978
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200979func (c *configImpl) Queryview() bool {
980 return c.queryview
981}
982
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200983func (c *configImpl) SoongDocs() bool {
984 return c.soongDocs
985}
986
Dan Willemsen1e704462016-08-21 15:17:17 -0700987func (c *configImpl) IsVerbose() bool {
988 return c.verbose
989}
990
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000991func (c *configImpl) SkipKati() bool {
992 return c.skipKati
993}
994
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100995func (c *configImpl) SkipKatiNinja() bool {
996 return c.skipKatiNinja
997}
998
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200999func (c *configImpl) SkipSoong() bool {
1000 return c.skipSoong
1001}
1002
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001003func (c *configImpl) SkipNinja() bool {
1004 return c.skipNinja
1005}
1006
Anton Hansson5a7861a2021-06-04 10:09:01 +01001007func (c *configImpl) SetSkipNinja(v bool) {
1008 c.skipNinja = v
1009}
1010
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001011func (c *configImpl) SkipConfig() bool {
1012 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001013}
1014
Dan Willemsen1e704462016-08-21 15:17:17 -07001015func (c *configImpl) TargetProduct() string {
1016 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1017 return v
1018 }
1019 panic("TARGET_PRODUCT is not defined")
1020}
1021
Dan Willemsen02781d52017-05-12 19:28:13 -07001022func (c *configImpl) TargetDevice() string {
1023 return c.targetDevice
1024}
1025
1026func (c *configImpl) SetTargetDevice(device string) {
1027 c.targetDevice = device
1028}
1029
1030func (c *configImpl) TargetBuildVariant() string {
1031 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1032 return v
1033 }
1034 panic("TARGET_BUILD_VARIANT is not defined")
1035}
1036
Dan Willemsen1e704462016-08-21 15:17:17 -07001037func (c *configImpl) KatiArgs() []string {
1038 return c.katiArgs
1039}
1040
1041func (c *configImpl) Parallel() int {
1042 return c.parallel
1043}
1044
Colin Cross8b8bec32019-11-15 13:18:43 -08001045func (c *configImpl) HighmemParallel() int {
1046 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1047 return i
1048 }
1049
1050 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1051 parallel := c.Parallel()
1052 if c.UseRemoteBuild() {
1053 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1054 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1055 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1056 // Return 1/16th of the size of the local pool, rounding up.
1057 return (parallel + 15) / 16
1058 } else if c.totalRAM == 0 {
1059 // Couldn't detect the total RAM, don't restrict highmem processes.
1060 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001061 } else if c.totalRAM <= 16*1024*1024*1024 {
1062 // Less than 16GB of ram, restrict to 1 highmem processes
1063 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001064 } else if c.totalRAM <= 32*1024*1024*1024 {
1065 // Less than 32GB of ram, restrict to 2 highmem processes
1066 return 2
1067 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1068 // If less than 8GB total RAM per process, reduce the number of highmem processes
1069 return p
1070 }
1071 // No restriction on highmem processes
1072 return parallel
1073}
1074
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001075func (c *configImpl) TotalRAM() uint64 {
1076 return c.totalRAM
1077}
1078
Kousik Kumarec478642020-09-21 13:39:24 -04001079// ForceUseGoma determines whether we should override Goma deprecation
1080// and use Goma for the current build or not.
1081func (c *configImpl) ForceUseGoma() bool {
1082 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1083 v = strings.TrimSpace(v)
1084 if v != "" && v != "false" {
1085 return true
1086 }
1087 }
1088 return false
1089}
1090
Dan Willemsen1e704462016-08-21 15:17:17 -07001091func (c *configImpl) UseGoma() bool {
1092 if v, ok := c.environ.Get("USE_GOMA"); ok {
1093 v = strings.TrimSpace(v)
1094 if v != "" && v != "false" {
1095 return true
1096 }
1097 }
1098 return false
1099}
1100
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001101func (c *configImpl) StartGoma() bool {
1102 if !c.UseGoma() {
1103 return false
1104 }
1105
1106 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1107 v = strings.TrimSpace(v)
1108 if v != "" && v != "false" {
1109 return false
1110 }
1111 }
1112 return true
1113}
1114
Ramy Medhatbbf25672019-07-17 12:30:04 +00001115func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001116 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001117 v = strings.TrimSpace(v)
1118 if v != "" && v != "false" {
1119 return true
1120 }
1121 }
1122 return false
1123}
1124
Chris Parsonsef615e52022-08-18 22:04:11 -04001125func (c *configImpl) BazelBuildEnabled() bool {
MarkDacekb78465d2022-10-18 20:10:16 +00001126 return c.bazelProdMode || c.bazelDevMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001127}
1128
Ramy Medhatbbf25672019-07-17 12:30:04 +00001129func (c *configImpl) StartRBE() bool {
1130 if !c.UseRBE() {
1131 return false
1132 }
1133
1134 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1135 v = strings.TrimSpace(v)
1136 if v != "" && v != "false" {
1137 return false
1138 }
1139 }
1140 return true
1141}
1142
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001143func (c *configImpl) rbeProxyLogsDir() string {
1144 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001145 if v, ok := c.environ.Get(f); ok {
1146 return v
1147 }
1148 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001149 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1150 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001151}
1152
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001153func (c *configImpl) shouldCleanupRBELogsDir() bool {
1154 // Perform a log directory cleanup only when the log directory
1155 // is auto created by the build rather than user-specified.
1156 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1157 if _, ok := c.environ.Get(f); ok {
1158 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001159 }
1160 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001161 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001162}
1163
1164func (c *configImpl) rbeExecRoot() string {
1165 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1166 if v, ok := c.environ.Get(f); ok {
1167 return v
1168 }
1169 }
1170 wd, err := os.Getwd()
1171 if err != nil {
1172 return ""
1173 }
1174 return wd
1175}
1176
1177func (c *configImpl) rbeDir() string {
1178 if v, ok := c.environ.Get("RBE_DIR"); ok {
1179 return v
1180 }
1181 return "prebuilts/remoteexecution-client/live/"
1182}
1183
1184func (c *configImpl) rbeReproxy() string {
1185 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1186 if v, ok := c.environ.Get(f); ok {
1187 return v
1188 }
1189 }
1190 return filepath.Join(c.rbeDir(), "reproxy")
1191}
1192
1193func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001194 credFlags := []string{
1195 "use_application_default_credentials",
1196 "use_gce_credentials",
1197 "credential_file",
1198 "use_google_prod_creds",
1199 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001200 for _, cf := range credFlags {
1201 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1202 if v, ok := c.environ.Get(f); ok {
1203 v = strings.TrimSpace(v)
1204 if v != "" && v != "false" && v != "0" {
1205 return "RBE_" + cf, v
1206 }
1207 }
1208 }
1209 }
1210 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001211}
1212
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001213func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1214 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1215 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1216
1217 name := filepath.Join(dir, base)
1218 if len(name) < maxNameLen {
1219 return name, nil
1220 }
1221
1222 name = filepath.Join("/tmp", base)
1223 if len(name) < maxNameLen {
1224 return name, nil
1225 }
1226
1227 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1228}
1229
Kousik Kumar7bc78192022-04-27 14:52:56 -04001230// IsGooglerEnvironment returns true if the current build is running
1231// on a Google developer machine and false otherwise.
1232func (c *configImpl) IsGooglerEnvironment() bool {
1233 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1234 if v, ok := c.environ.Get(cf); ok {
1235 return v == "googler"
1236 }
1237 return false
1238}
1239
1240// GoogleProdCredsExist determine whether credentials exist on the
1241// Googler machine to use remote execution.
1242func (c *configImpl) GoogleProdCredsExist() bool {
1243 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1244 return false
1245 }
1246 return true
1247}
1248
1249// UseRemoteBuild indicates whether to use a remote build acceleration system
1250// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001251func (c *configImpl) UseRemoteBuild() bool {
1252 return c.UseGoma() || c.UseRBE()
1253}
1254
Kousik Kumar7bc78192022-04-27 14:52:56 -04001255// StubbyExists checks whether the stubby binary exists on the machine running
1256// the build.
1257func (c *configImpl) StubbyExists() bool {
1258 if _, err := exec.LookPath("stubby"); err != nil {
1259 return false
1260 }
1261 return true
1262}
1263
Dan Willemsen1e704462016-08-21 15:17:17 -07001264// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001265// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001266// still limited by Parallel()
1267func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001268 if !c.UseRemoteBuild() {
1269 return 0
1270 }
1271 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1272 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001273 }
1274 return 500
1275}
1276
1277func (c *configImpl) SetKatiArgs(args []string) {
1278 c.katiArgs = args
1279}
1280
1281func (c *configImpl) SetNinjaArgs(args []string) {
1282 c.ninjaArgs = args
1283}
1284
1285func (c *configImpl) SetKatiSuffix(suffix string) {
1286 c.katiSuffix = suffix
1287}
1288
Dan Willemsene0879fc2017-08-04 15:06:27 -07001289func (c *configImpl) LastKatiSuffixFile() string {
1290 return filepath.Join(c.OutDir(), "last_kati_suffix")
1291}
1292
1293func (c *configImpl) HasKatiSuffix() bool {
1294 return c.katiSuffix != ""
1295}
1296
Dan Willemsen1e704462016-08-21 15:17:17 -07001297func (c *configImpl) KatiEnvFile() string {
1298 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1299}
1300
Dan Willemsen29971232018-09-26 14:58:30 -07001301func (c *configImpl) KatiBuildNinjaFile() string {
1302 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001303}
1304
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001305func (c *configImpl) KatiPackageNinjaFile() string {
1306 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1307}
1308
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001309func (c *configImpl) SoongVarsFile() string {
1310 return filepath.Join(c.SoongOutDir(), "soong.variables")
1311}
1312
Dan Willemsen1e704462016-08-21 15:17:17 -07001313func (c *configImpl) SoongNinjaFile() string {
1314 return filepath.Join(c.SoongOutDir(), "build.ninja")
1315}
1316
1317func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001318 if c.katiSuffix == "" {
1319 return filepath.Join(c.OutDir(), "combined.ninja")
1320 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001321 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1322}
1323
1324func (c *configImpl) SoongAndroidMk() string {
1325 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1326}
1327
1328func (c *configImpl) SoongMakeVarsMk() string {
1329 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1330}
1331
Dan Willemsenf052f782017-05-18 15:29:04 -07001332func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001333 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001334}
1335
Dan Willemsen02781d52017-05-12 19:28:13 -07001336func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001337 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1338}
1339
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001340func (c *configImpl) KatiPackageMkDir() string {
1341 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1342}
1343
Dan Willemsenf052f782017-05-18 15:29:04 -07001344func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001345 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001346}
1347
1348func (c *configImpl) HostOut() string {
1349 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1350}
1351
1352// This probably needs to be multi-valued, so not exporting it for now
1353func (c *configImpl) hostCrossOut() string {
1354 if runtime.GOOS == "linux" {
1355 return filepath.Join(c.hostOutRoot(), "windows-x86")
1356 } else {
1357 return ""
1358 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001359}
1360
Dan Willemsen1e704462016-08-21 15:17:17 -07001361func (c *configImpl) HostPrebuiltTag() string {
1362 if runtime.GOOS == "linux" {
1363 return "linux-x86"
1364 } else if runtime.GOOS == "darwin" {
1365 return "darwin-x86"
1366 } else {
1367 panic("Unsupported OS")
1368 }
1369}
Dan Willemsenf173d592017-04-27 14:28:00 -07001370
Dan Willemsen8122bd52017-10-12 20:20:41 -07001371func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001372 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1373 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001374 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1375 if _, err := os.Stat(asan); err == nil {
1376 return asan
1377 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001378 }
1379 }
1380 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1381}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001382
1383func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1384 c.brokenDupRules = val
1385}
1386
1387func (c *configImpl) BuildBrokenDupRules() bool {
1388 return c.brokenDupRules
1389}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001390
Dan Willemsen25e6f092019-04-09 10:22:43 -07001391func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1392 c.brokenUsesNetwork = val
1393}
1394
1395func (c *configImpl) BuildBrokenUsesNetwork() bool {
1396 return c.brokenUsesNetwork
1397}
1398
Dan Willemsene3336352020-01-02 19:10:38 -08001399func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1400 c.brokenNinjaEnvVars = val
1401}
1402
1403func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1404 return c.brokenNinjaEnvVars
1405}
1406
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001407func (c *configImpl) SetTargetDeviceDir(dir string) {
1408 c.targetDeviceDir = dir
1409}
1410
1411func (c *configImpl) TargetDeviceDir() string {
1412 return c.targetDeviceDir
1413}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001414
Patrice Arruda219eef32020-06-01 17:29:30 +00001415func (c *configImpl) BuildDateTime() string {
1416 return c.buildDateTime
1417}
1418
1419func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001420 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001421}
Patrice Arruda83842d72020-12-08 19:42:08 +00001422
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001423// LogsDir returns the absolute path to the logs directory where build log and
1424// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001425// directory. If the argument dist is specified, the logs directory
1426// is <dist_dir>/logs.
1427func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001428 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001429 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001430 // 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 -05001431 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001432 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001433 absDir, err := filepath.Abs(dir)
1434 if err != nil {
1435 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1436 os.Exit(1)
1437 }
1438 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001439}
1440
1441// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1442// where the bazel profiles are located.
1443func (c *configImpl) BazelMetricsDir() string {
1444 return filepath.Join(c.LogsDir(), "bazel_metrics")
1445}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001446
Chris Parsons53f68ae2022-03-03 12:01:40 -05001447// MkFileMetrics returns the file path for make-related metrics.
1448func (c *configImpl) MkMetrics() string {
1449 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1450}
1451
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001452func (c *configImpl) SetEmptyNinjaFile(v bool) {
1453 c.emptyNinjaFile = v
1454}
1455
1456func (c *configImpl) EmptyNinjaFile() bool {
1457 return c.emptyNinjaFile
1458}
Yu Liu6e13b402021-07-27 14:29:06 -07001459
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001460func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1461 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1462}
1463
Yu Liu6e13b402021-07-27 14:29:06 -07001464func GetMetricsUploader(topDir string, env *Environment) string {
1465 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1466 metricsUploader := filepath.Join(topDir, p)
1467 if _, err := os.Stat(metricsUploader); err == nil {
1468 return metricsUploader
1469 }
1470 }
1471
1472 return ""
1473}