blob: c1c83ff2aedd1c2fc08caf681f10708eaede4ab6 [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{
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400467 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
468 UseGoma: proto.Bool(config.UseGoma()),
469 UseRbe: proto.Bool(config.UseRBE()),
Chris Parsonsef615e52022-08-18 22:04:11 -0400470 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400471 }
Yu Liue737a992021-10-04 13:21:41 -0700472 c.Targets = append(c.Targets, config.arguments...)
473
474 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400475}
476
Patrice Arruda13848222019-04-22 17:12:02 -0700477// getConfigArgs processes the command arguments based on the build action and creates a set of new
478// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700479func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700480 // The next block of code verifies that the current directory is the root directory of the source
481 // tree. It then finds the relative path of dir based on the root directory of the source tree
482 // and verify that dir is inside of the source tree.
483 checkTopDir(ctx)
484 topDir, err := os.Getwd()
485 if err != nil {
486 ctx.Fatalf("Error retrieving top directory: %v", err)
487 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700488 dir, err = filepath.EvalSymlinks(dir)
489 if err != nil {
490 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
491 }
Patrice Arruda13848222019-04-22 17:12:02 -0700492 dir, err = filepath.Abs(dir)
493 if err != nil {
494 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
495 }
496 relDir, err := filepath.Rel(topDir, dir)
497 if err != nil {
498 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
499 }
500 // If there are ".." in the path, it's not in the source tree.
501 if strings.Contains(relDir, "..") {
502 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
503 }
504
505 configArgs := args[:]
506
507 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
508 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
509 targetNamePrefix := "MODULES-IN-"
510 if inList("GET-INSTALL-PATH", configArgs) {
511 targetNamePrefix = "GET-INSTALL-PATH-IN-"
512 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
513 }
514
Patrice Arruda13848222019-04-22 17:12:02 -0700515 var targets []string
516
517 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700518 case BUILD_MODULES:
519 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700520 case BUILD_MODULES_IN_A_DIRECTORY:
521 // If dir is the root source tree, all the modules are built of the source tree are built so
522 // no need to find the build file.
523 if topDir == dir {
524 break
525 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700526
Patrice Arruda13848222019-04-22 17:12:02 -0700527 buildFile := findBuildFile(ctx, relDir)
528 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700529 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700530 }
Patrice Arruda13848222019-04-22 17:12:02 -0700531 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
532 case BUILD_MODULES_IN_DIRECTORIES:
533 newConfigArgs, dirs := splitArgs(configArgs)
534 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700535 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700536 }
537
538 // Tidy only override all other specified targets.
539 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
540 if tidyOnly == "true" || tidyOnly == "1" {
541 configArgs = append(configArgs, "tidy_only")
542 } else {
543 configArgs = append(configArgs, targets...)
544 }
545
546 return configArgs
547}
548
549// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
550func convertToTarget(dir string, targetNamePrefix string) string {
551 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
552}
553
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700554// hasBuildFile returns true if dir contains an Android build file.
555func hasBuildFile(ctx Context, dir string) bool {
556 for _, buildFile := range buildFiles {
557 _, err := os.Stat(filepath.Join(dir, buildFile))
558 if err == nil {
559 return true
560 }
561 if !os.IsNotExist(err) {
562 ctx.Fatalf("Error retrieving the build file stats: %v", err)
563 }
564 }
565 return false
566}
567
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700568// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
569// in the current and any sub directory of dir. If a build file is not found, traverse the path
570// up by one directory and repeat again until either a build file is found or reached to the root
571// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
572// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700573func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700574 // If the string is empty or ".", assume it is top directory of the source tree.
575 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700576 return ""
577 }
578
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700579 found := false
580 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
581 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
582 if err != nil {
583 return err
584 }
585 if found {
586 return filepath.SkipDir
587 }
588 if info.IsDir() {
589 return nil
590 }
591 for _, buildFile := range buildFiles {
592 if info.Name() == buildFile {
593 found = true
594 return filepath.SkipDir
595 }
596 }
597 return nil
598 })
599 if err != nil {
600 ctx.Fatalf("Error finding Android build file: %v", err)
601 }
602
603 if found {
604 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700605 }
606 }
607
608 return ""
609}
610
611// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
612func splitArgs(args []string) (newArgs []string, dirs []string) {
613 specialArgs := map[string]bool{
614 "showcommands": true,
615 "snod": true,
616 "dist": true,
617 "checkbuild": true,
618 }
619
620 newArgs = []string{}
621 dirs = []string{}
622
623 for _, arg := range args {
624 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
625 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
626 newArgs = append(newArgs, arg)
627 continue
628 }
629
630 if _, ok := specialArgs[arg]; ok {
631 newArgs = append(newArgs, arg)
632 continue
633 }
634
635 dirs = append(dirs, arg)
636 }
637
638 return newArgs, dirs
639}
640
641// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
642// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
643// source root tree where the build action command was invoked. Each directory is validated if the
644// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700645func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700646 for _, dir := range dirs {
647 // The directory may have specified specific modules to build. ":" is the separator to separate
648 // the directory and the list of modules.
649 s := strings.Split(dir, ":")
650 l := len(s)
651 if l > 2 { // more than one ":" was specified.
652 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
653 }
654
655 dir = filepath.Join(relDir, s[0])
656 if _, err := os.Stat(dir); err != nil {
657 ctx.Fatalf("couldn't find directory %s", dir)
658 }
659
660 // Verify that if there are any targets specified after ":". Each target is separated by ",".
661 var newTargets []string
662 if l == 2 && s[1] != "" {
663 newTargets = strings.Split(s[1], ",")
664 if inList("", newTargets) {
665 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
666 }
667 }
668
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700669 // If there are specified targets to build in dir, an android build file must exist for the one
670 // shot build. For the non-targets case, find the appropriate build file and build all the
671 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700672 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700673 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700674 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
675 }
676 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700677 buildFile := findBuildFile(ctx, dir)
678 if buildFile == "" {
679 ctx.Fatalf("Build file not found for %s directory", dir)
680 }
681 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700682 }
683
Patrice Arruda13848222019-04-22 17:12:02 -0700684 targets = append(targets, newTargets...)
685 }
686
Dan Willemsence41e942019-07-29 23:39:30 -0700687 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700688}
689
Dan Willemsen9b587492017-07-10 22:13:00 -0700690func (c *configImpl) parseArgs(ctx Context, args []string) {
691 for i := 0; i < len(args); i++ {
692 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100693 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700694 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200695 } else if arg == "--empty-ninja-file" {
696 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100697 } else if arg == "--skip-ninja" {
698 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700699 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700700 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
701 // but it does run a Kati ninja file if the .kati_enabled marker file was created
702 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000703 c.skipConfig = true
704 c.skipKati = true
705 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100706 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000707 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100708 } else if arg == "--soong-only" {
709 c.skipKati = true
710 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200711 } else if arg == "--config-only" {
712 c.skipKati = true
713 c.skipKatiNinja = true
714 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700715 } else if arg == "--skip-config" {
716 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700717 } else if arg == "--skip-soong-tests" {
718 c.skipSoongTests = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500719 } else if arg == "--mk-metrics" {
720 c.reportMkMetrics = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400721 } else if arg == "--bazel-mode" {
722 c.bazelProdMode = true
723 } else if arg == "--bazel-mode-dev" {
724 c.bazelDevMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000725 } else if arg == "--bazel-mode-staging" {
726 c.bazelStagingMode = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700727 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700728 parseArgNum := func(def int) int {
729 if len(arg) > 2 {
730 p, err := strconv.ParseUint(arg[2:], 10, 31)
731 if err != nil {
732 ctx.Fatalf("Failed to parse %q: %v", arg, err)
733 }
734 return int(p)
735 } else if i+1 < len(args) {
736 p, err := strconv.ParseUint(args[i+1], 10, 31)
737 if err == nil {
738 i++
739 return int(p)
740 }
741 }
742 return def
743 }
744
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700745 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700746 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700747 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700748 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700749 } else {
750 ctx.Fatalln("Unknown option:", arg)
751 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700752 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700753 if k == "OUT_DIR" {
754 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
755 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700756 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700757 } else if arg == "dist" {
758 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200759 } else if arg == "json-module-graph" {
760 c.jsonModuleGraph = true
761 } else if arg == "bp2build" {
762 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000763 } else if arg == "api_bp2build" {
764 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200765 } else if arg == "queryview" {
766 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200767 } else if arg == "soong_docs" {
768 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700769 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700770 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800771 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700772 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700773 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700774 }
775 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700776}
777
Dan Willemsened869522018-01-08 14:58:46 -0800778func (c *configImpl) configureLocale(ctx Context) {
779 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
780 output, err := cmd.Output()
781
782 var locales []string
783 if err == nil {
784 locales = strings.Split(string(output), "\n")
785 } else {
786 // If we're unable to list the locales, let's assume en_US.UTF-8
787 locales = []string{"en_US.UTF-8"}
788 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
789 }
790
791 // gettext uses LANGUAGE, which is passed directly through
792
793 // For LANG and LC_*, only preserve the evaluated version of
794 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800795 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800796 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800797 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800798 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800799 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800800 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800801 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800802 }
803
804 c.environ.UnsetWithPrefix("LC_")
805
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800806 if userLang != "" {
807 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800808 }
809
810 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
811 // for others)
812 if inList("C.UTF-8", locales) {
813 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500814 } else if inList("C.utf8", locales) {
815 // These normalize to the same thing
816 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800817 } else if inList("en_US.UTF-8", locales) {
818 c.environ.Set("LANG", "en_US.UTF-8")
819 } else if inList("en_US.utf8", locales) {
820 // These normalize to the same thing
821 c.environ.Set("LANG", "en_US.UTF-8")
822 } else {
823 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
824 }
825}
826
Dan Willemsen1e704462016-08-21 15:17:17 -0700827func (c *configImpl) Environment() *Environment {
828 return c.environ
829}
830
831func (c *configImpl) Arguments() []string {
832 return c.arguments
833}
834
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200835func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200836 if len(c.Arguments()) > 0 {
837 // Explicit targets requested that are not special targets like b2pbuild
838 // or the JSON module graph
839 return true
840 }
841
Spandan Das5af0bd32022-09-28 20:43:08 +0000842 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200843 // Command line was empty, the default Ninja target is built
844 return true
845 }
846
Liz Kammer88677422021-12-15 15:03:19 -0500847 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
848 if c.Dist() && !c.Bp2Build() {
849 return true
850 }
851
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200852 // build.ninja doesn't need to be generated
853 return false
854}
855
Dan Willemsen1e704462016-08-21 15:17:17 -0700856func (c *configImpl) OutDir() string {
857 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700858 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700859 }
860 return "out"
861}
862
Dan Willemsen8a073a82017-02-04 17:30:44 -0800863func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400864 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000865}
866
867func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700868 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800869}
870
Dan Willemsen1e704462016-08-21 15:17:17 -0700871func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000872 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700873 return c.arguments
874 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700875 return c.ninjaArgs
876}
877
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500878func (c *configImpl) BazelOutDir() string {
879 return filepath.Join(c.OutDir(), "bazel")
880}
881
Dan Willemsen1e704462016-08-21 15:17:17 -0700882func (c *configImpl) SoongOutDir() string {
883 return filepath.Join(c.OutDir(), "soong")
884}
885
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200886func (c *configImpl) PrebuiltOS() string {
887 switch runtime.GOOS {
888 case "linux":
889 return "linux-x86"
890 case "darwin":
891 return "darwin-x86"
892 default:
893 panic("Unknown GOOS")
894 }
895}
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100896
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200897func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -0700898 if c.SkipKatiNinja() {
899 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
900 } else {
901 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
902 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200903}
904
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200905func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100906 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200907}
908
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200909func (c *configImpl) UsedEnvFile(tag string) string {
910 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
911}
912
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000913func (c *configImpl) Bp2BuildFilesMarkerFile() string {
914 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
915}
916
917func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100918 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200919}
920
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200921func (c *configImpl) SoongDocsHtml() string {
922 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
923}
924
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200925func (c *configImpl) QueryviewMarkerFile() string {
926 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
927}
928
Spandan Das5af0bd32022-09-28 20:43:08 +0000929func (c *configImpl) ApiBp2buildMarkerFile() string {
930 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
931}
932
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200933func (c *configImpl) ModuleGraphFile() string {
934 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
935}
936
kgui67007242022-01-25 13:50:25 +0800937func (c *configImpl) ModuleActionsFile() string {
938 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
939}
940
Jeff Gastonefc1b412017-03-29 17:29:06 -0700941func (c *configImpl) TempDir() string {
942 return shared.TempDirForOutDir(c.SoongOutDir())
943}
944
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700945func (c *configImpl) FileListDir() string {
946 return filepath.Join(c.OutDir(), ".module_paths")
947}
948
Dan Willemsen1e704462016-08-21 15:17:17 -0700949func (c *configImpl) KatiSuffix() string {
950 if c.katiSuffix != "" {
951 return c.katiSuffix
952 }
953 panic("SetKatiSuffix has not been called")
954}
955
Colin Cross37193492017-11-16 17:55:00 -0800956// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
957// user is interested in additional checks at the expense of build time.
958func (c *configImpl) Checkbuild() bool {
959 return c.checkbuild
960}
961
Dan Willemsen8a073a82017-02-04 17:30:44 -0800962func (c *configImpl) Dist() bool {
963 return c.dist
964}
965
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200966func (c *configImpl) JsonModuleGraph() bool {
967 return c.jsonModuleGraph
968}
969
970func (c *configImpl) Bp2Build() bool {
971 return c.bp2build
972}
973
Spandan Das5af0bd32022-09-28 20:43:08 +0000974func (c *configImpl) ApiBp2build() bool {
975 return c.apiBp2build
976}
977
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200978func (c *configImpl) Queryview() bool {
979 return c.queryview
980}
981
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200982func (c *configImpl) SoongDocs() bool {
983 return c.soongDocs
984}
985
Dan Willemsen1e704462016-08-21 15:17:17 -0700986func (c *configImpl) IsVerbose() bool {
987 return c.verbose
988}
989
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000990func (c *configImpl) SkipKati() bool {
991 return c.skipKati
992}
993
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100994func (c *configImpl) SkipKatiNinja() bool {
995 return c.skipKatiNinja
996}
997
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200998func (c *configImpl) SkipSoong() bool {
999 return c.skipSoong
1000}
1001
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001002func (c *configImpl) SkipNinja() bool {
1003 return c.skipNinja
1004}
1005
Anton Hansson5a7861a2021-06-04 10:09:01 +01001006func (c *configImpl) SetSkipNinja(v bool) {
1007 c.skipNinja = v
1008}
1009
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001010func (c *configImpl) SkipConfig() bool {
1011 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001012}
1013
Dan Willemsen1e704462016-08-21 15:17:17 -07001014func (c *configImpl) TargetProduct() string {
1015 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1016 return v
1017 }
1018 panic("TARGET_PRODUCT is not defined")
1019}
1020
Dan Willemsen02781d52017-05-12 19:28:13 -07001021func (c *configImpl) TargetDevice() string {
1022 return c.targetDevice
1023}
1024
1025func (c *configImpl) SetTargetDevice(device string) {
1026 c.targetDevice = device
1027}
1028
1029func (c *configImpl) TargetBuildVariant() string {
1030 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1031 return v
1032 }
1033 panic("TARGET_BUILD_VARIANT is not defined")
1034}
1035
Dan Willemsen1e704462016-08-21 15:17:17 -07001036func (c *configImpl) KatiArgs() []string {
1037 return c.katiArgs
1038}
1039
1040func (c *configImpl) Parallel() int {
1041 return c.parallel
1042}
1043
Colin Cross8b8bec32019-11-15 13:18:43 -08001044func (c *configImpl) HighmemParallel() int {
1045 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1046 return i
1047 }
1048
1049 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1050 parallel := c.Parallel()
1051 if c.UseRemoteBuild() {
1052 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1053 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1054 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1055 // Return 1/16th of the size of the local pool, rounding up.
1056 return (parallel + 15) / 16
1057 } else if c.totalRAM == 0 {
1058 // Couldn't detect the total RAM, don't restrict highmem processes.
1059 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001060 } else if c.totalRAM <= 16*1024*1024*1024 {
1061 // Less than 16GB of ram, restrict to 1 highmem processes
1062 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001063 } else if c.totalRAM <= 32*1024*1024*1024 {
1064 // Less than 32GB of ram, restrict to 2 highmem processes
1065 return 2
1066 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1067 // If less than 8GB total RAM per process, reduce the number of highmem processes
1068 return p
1069 }
1070 // No restriction on highmem processes
1071 return parallel
1072}
1073
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001074func (c *configImpl) TotalRAM() uint64 {
1075 return c.totalRAM
1076}
1077
Kousik Kumarec478642020-09-21 13:39:24 -04001078// ForceUseGoma determines whether we should override Goma deprecation
1079// and use Goma for the current build or not.
1080func (c *configImpl) ForceUseGoma() bool {
1081 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1082 v = strings.TrimSpace(v)
1083 if v != "" && v != "false" {
1084 return true
1085 }
1086 }
1087 return false
1088}
1089
Dan Willemsen1e704462016-08-21 15:17:17 -07001090func (c *configImpl) UseGoma() bool {
1091 if v, ok := c.environ.Get("USE_GOMA"); ok {
1092 v = strings.TrimSpace(v)
1093 if v != "" && v != "false" {
1094 return true
1095 }
1096 }
1097 return false
1098}
1099
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001100func (c *configImpl) StartGoma() bool {
1101 if !c.UseGoma() {
1102 return false
1103 }
1104
1105 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1106 v = strings.TrimSpace(v)
1107 if v != "" && v != "false" {
1108 return false
1109 }
1110 }
1111 return true
1112}
1113
Ramy Medhatbbf25672019-07-17 12:30:04 +00001114func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001115 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001116 v = strings.TrimSpace(v)
1117 if v != "" && v != "false" {
1118 return true
1119 }
1120 }
1121 return false
1122}
1123
Chris Parsonsef615e52022-08-18 22:04:11 -04001124func (c *configImpl) BazelBuildEnabled() bool {
MarkDacekb78465d2022-10-18 20:10:16 +00001125 return c.bazelProdMode || c.bazelDevMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001126}
1127
Ramy Medhatbbf25672019-07-17 12:30:04 +00001128func (c *configImpl) StartRBE() bool {
1129 if !c.UseRBE() {
1130 return false
1131 }
1132
1133 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1134 v = strings.TrimSpace(v)
1135 if v != "" && v != "false" {
1136 return false
1137 }
1138 }
1139 return true
1140}
1141
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001142func (c *configImpl) rbeProxyLogsDir() string {
1143 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001144 if v, ok := c.environ.Get(f); ok {
1145 return v
1146 }
1147 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001148 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1149 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001150}
1151
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001152func (c *configImpl) shouldCleanupRBELogsDir() bool {
1153 // Perform a log directory cleanup only when the log directory
1154 // is auto created by the build rather than user-specified.
1155 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1156 if _, ok := c.environ.Get(f); ok {
1157 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001158 }
1159 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001160 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001161}
1162
1163func (c *configImpl) rbeExecRoot() string {
1164 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1165 if v, ok := c.environ.Get(f); ok {
1166 return v
1167 }
1168 }
1169 wd, err := os.Getwd()
1170 if err != nil {
1171 return ""
1172 }
1173 return wd
1174}
1175
1176func (c *configImpl) rbeDir() string {
1177 if v, ok := c.environ.Get("RBE_DIR"); ok {
1178 return v
1179 }
1180 return "prebuilts/remoteexecution-client/live/"
1181}
1182
1183func (c *configImpl) rbeReproxy() string {
1184 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1185 if v, ok := c.environ.Get(f); ok {
1186 return v
1187 }
1188 }
1189 return filepath.Join(c.rbeDir(), "reproxy")
1190}
1191
1192func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001193 credFlags := []string{
1194 "use_application_default_credentials",
1195 "use_gce_credentials",
1196 "credential_file",
1197 "use_google_prod_creds",
1198 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001199 for _, cf := range credFlags {
1200 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1201 if v, ok := c.environ.Get(f); ok {
1202 v = strings.TrimSpace(v)
1203 if v != "" && v != "false" && v != "0" {
1204 return "RBE_" + cf, v
1205 }
1206 }
1207 }
1208 }
1209 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001210}
1211
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001212func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1213 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1214 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1215
1216 name := filepath.Join(dir, base)
1217 if len(name) < maxNameLen {
1218 return name, nil
1219 }
1220
1221 name = filepath.Join("/tmp", base)
1222 if len(name) < maxNameLen {
1223 return name, nil
1224 }
1225
1226 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1227}
1228
Kousik Kumar7bc78192022-04-27 14:52:56 -04001229// IsGooglerEnvironment returns true if the current build is running
1230// on a Google developer machine and false otherwise.
1231func (c *configImpl) IsGooglerEnvironment() bool {
1232 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1233 if v, ok := c.environ.Get(cf); ok {
1234 return v == "googler"
1235 }
1236 return false
1237}
1238
1239// GoogleProdCredsExist determine whether credentials exist on the
1240// Googler machine to use remote execution.
1241func (c *configImpl) GoogleProdCredsExist() bool {
1242 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1243 return false
1244 }
1245 return true
1246}
1247
1248// UseRemoteBuild indicates whether to use a remote build acceleration system
1249// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001250func (c *configImpl) UseRemoteBuild() bool {
1251 return c.UseGoma() || c.UseRBE()
1252}
1253
Kousik Kumar7bc78192022-04-27 14:52:56 -04001254// StubbyExists checks whether the stubby binary exists on the machine running
1255// the build.
1256func (c *configImpl) StubbyExists() bool {
1257 if _, err := exec.LookPath("stubby"); err != nil {
1258 return false
1259 }
1260 return true
1261}
1262
Dan Willemsen1e704462016-08-21 15:17:17 -07001263// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001264// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001265// still limited by Parallel()
1266func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001267 if !c.UseRemoteBuild() {
1268 return 0
1269 }
1270 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1271 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001272 }
1273 return 500
1274}
1275
1276func (c *configImpl) SetKatiArgs(args []string) {
1277 c.katiArgs = args
1278}
1279
1280func (c *configImpl) SetNinjaArgs(args []string) {
1281 c.ninjaArgs = args
1282}
1283
1284func (c *configImpl) SetKatiSuffix(suffix string) {
1285 c.katiSuffix = suffix
1286}
1287
Dan Willemsene0879fc2017-08-04 15:06:27 -07001288func (c *configImpl) LastKatiSuffixFile() string {
1289 return filepath.Join(c.OutDir(), "last_kati_suffix")
1290}
1291
1292func (c *configImpl) HasKatiSuffix() bool {
1293 return c.katiSuffix != ""
1294}
1295
Dan Willemsen1e704462016-08-21 15:17:17 -07001296func (c *configImpl) KatiEnvFile() string {
1297 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1298}
1299
Dan Willemsen29971232018-09-26 14:58:30 -07001300func (c *configImpl) KatiBuildNinjaFile() string {
1301 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001302}
1303
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001304func (c *configImpl) KatiPackageNinjaFile() string {
1305 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1306}
1307
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001308func (c *configImpl) SoongVarsFile() string {
1309 return filepath.Join(c.SoongOutDir(), "soong.variables")
1310}
1311
Dan Willemsen1e704462016-08-21 15:17:17 -07001312func (c *configImpl) SoongNinjaFile() string {
1313 return filepath.Join(c.SoongOutDir(), "build.ninja")
1314}
1315
1316func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001317 if c.katiSuffix == "" {
1318 return filepath.Join(c.OutDir(), "combined.ninja")
1319 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001320 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1321}
1322
1323func (c *configImpl) SoongAndroidMk() string {
1324 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1325}
1326
1327func (c *configImpl) SoongMakeVarsMk() string {
1328 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1329}
1330
Dan Willemsenf052f782017-05-18 15:29:04 -07001331func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001332 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001333}
1334
Dan Willemsen02781d52017-05-12 19:28:13 -07001335func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001336 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1337}
1338
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001339func (c *configImpl) KatiPackageMkDir() string {
1340 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1341}
1342
Dan Willemsenf052f782017-05-18 15:29:04 -07001343func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001344 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001345}
1346
1347func (c *configImpl) HostOut() string {
1348 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1349}
1350
1351// This probably needs to be multi-valued, so not exporting it for now
1352func (c *configImpl) hostCrossOut() string {
1353 if runtime.GOOS == "linux" {
1354 return filepath.Join(c.hostOutRoot(), "windows-x86")
1355 } else {
1356 return ""
1357 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001358}
1359
Dan Willemsen1e704462016-08-21 15:17:17 -07001360func (c *configImpl) HostPrebuiltTag() string {
1361 if runtime.GOOS == "linux" {
1362 return "linux-x86"
1363 } else if runtime.GOOS == "darwin" {
1364 return "darwin-x86"
1365 } else {
1366 panic("Unsupported OS")
1367 }
1368}
Dan Willemsenf173d592017-04-27 14:28:00 -07001369
Dan Willemsen8122bd52017-10-12 20:20:41 -07001370func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001371 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1372 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001373 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1374 if _, err := os.Stat(asan); err == nil {
1375 return asan
1376 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001377 }
1378 }
1379 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1380}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001381
1382func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1383 c.brokenDupRules = val
1384}
1385
1386func (c *configImpl) BuildBrokenDupRules() bool {
1387 return c.brokenDupRules
1388}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001389
Dan Willemsen25e6f092019-04-09 10:22:43 -07001390func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1391 c.brokenUsesNetwork = val
1392}
1393
1394func (c *configImpl) BuildBrokenUsesNetwork() bool {
1395 return c.brokenUsesNetwork
1396}
1397
Dan Willemsene3336352020-01-02 19:10:38 -08001398func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1399 c.brokenNinjaEnvVars = val
1400}
1401
1402func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1403 return c.brokenNinjaEnvVars
1404}
1405
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001406func (c *configImpl) SetTargetDeviceDir(dir string) {
1407 c.targetDeviceDir = dir
1408}
1409
1410func (c *configImpl) TargetDeviceDir() string {
1411 return c.targetDeviceDir
1412}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001413
Patrice Arruda219eef32020-06-01 17:29:30 +00001414func (c *configImpl) BuildDateTime() string {
1415 return c.buildDateTime
1416}
1417
1418func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001419 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001420}
Patrice Arruda83842d72020-12-08 19:42:08 +00001421
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001422// LogsDir returns the absolute path to the logs directory where build log and
1423// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001424// directory. If the argument dist is specified, the logs directory
1425// is <dist_dir>/logs.
1426func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001427 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001428 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001429 // 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 -05001430 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001431 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001432 absDir, err := filepath.Abs(dir)
1433 if err != nil {
1434 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1435 os.Exit(1)
1436 }
1437 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001438}
1439
1440// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1441// where the bazel profiles are located.
1442func (c *configImpl) BazelMetricsDir() string {
1443 return filepath.Join(c.LogsDir(), "bazel_metrics")
1444}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001445
Chris Parsons53f68ae2022-03-03 12:01:40 -05001446// MkFileMetrics returns the file path for make-related metrics.
1447func (c *configImpl) MkMetrics() string {
1448 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1449}
1450
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001451func (c *configImpl) SetEmptyNinjaFile(v bool) {
1452 c.emptyNinjaFile = v
1453}
1454
1455func (c *configImpl) EmptyNinjaFile() bool {
1456 return c.emptyNinjaFile
1457}
Yu Liu6e13b402021-07-27 14:29:06 -07001458
1459func GetMetricsUploader(topDir string, env *Environment) string {
1460 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1461 metricsUploader := filepath.Join(topDir, p)
1462 if _, err := os.Stat(metricsUploader); err == nil {
1463 return metricsUploader
1464 }
1465 }
1466
1467 return ""
1468}