blob: 14a99d08074da2805c778c007f98c86e69941972 [file] [log] [blame]
Dan Willemsen1e704462016-08-21 15:17:17 -07001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package build
16
17import (
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050018 "context"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050019 "encoding/json"
Ramy Medhat0fc67eb2020-08-12 01:26:23 -040020 "fmt"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050021 "io/ioutil"
Kousik Kumar4c180ad2022-05-27 07:48:37 -040022 "math/rand"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080023 "os"
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050024 "os/exec"
Dan Willemsen1e704462016-08-21 15:17:17 -070025 "path/filepath"
26 "runtime"
27 "strconv"
28 "strings"
Kousik Kumar4c180ad2022-05-27 07:48:37 -040029 "syscall"
Nan Zhang2e6a4ff2018-02-14 13:27:26 -080030 "time"
Jeff Gastonefc1b412017-03-29 17:29:06 -070031
32 "android/soong/shared"
Kousik Kumarec478642020-09-21 13:39:24 -040033
Dan Willemsen4591b642021-05-24 14:24:12 -070034 "google.golang.org/protobuf/proto"
Patrice Arruda96850362020-08-11 20:41:11 +000035
36 smpb "android/soong/ui/metrics/metrics_proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070037)
38
Kousik Kumar3ff037e2022-01-25 22:11:01 -050039const (
Chris Parsons53f68ae2022-03-03 12:01:40 -050040 envConfigDir = "vendor/google/tools/soong_config"
41 jsonSuffix = "json"
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050042
Chris Parsons53f68ae2022-03-03 12:01:40 -050043 configFetcher = "vendor/google/tools/soong/expconfigfetcher"
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050044 envConfigFetchTimeout = 10 * time.Second
Kousik Kumar3ff037e2022-01-25 22:11:01 -050045)
46
Kousik Kumar4c180ad2022-05-27 07:48:37 -040047var (
48 rbeRandPrefix int
49)
50
51func init() {
52 rand.Seed(time.Now().UnixNano())
53 rbeRandPrefix = rand.Intn(1000)
54}
55
Dan Willemsen1e704462016-08-21 15:17:17 -070056type Config struct{ *configImpl }
57
58type configImpl struct {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020059 // Some targets that are implemented in soong_build
60 // (bp2build, json-module-graph) are not here and have their own bits below.
Colin Cross28f527c2019-11-26 16:19:04 -080061 arguments []string
62 goma bool
63 environ *Environment
64 distDir string
65 buildDateTime string
Dan Willemsen1e704462016-08-21 15:17:17 -070066
67 // From the arguments
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020068 parallel int
69 keepGoing int
70 verbose bool
71 checkbuild bool
72 dist bool
73 jsonModuleGraph bool
74 bp2build bool
Lukacs T. Berki3a821692021-09-06 17:08:02 +020075 queryview bool
Chris Parsons53f68ae2022-03-03 12:01:40 -050076 reportMkMetrics bool // Collect and report mk2bp migration progress metrics.
Lukacs T. Berkic6012f32021-09-06 18:31:46 +020077 soongDocs bool
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020078 skipConfig bool
79 skipKati bool
80 skipKatiNinja bool
81 skipSoong bool
82 skipNinja bool
83 skipSoongTests bool
Dan Willemsen1e704462016-08-21 15:17:17 -070084
85 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070086 katiArgs []string
87 ninjaArgs []string
88 katiSuffix string
89 targetDevice string
90 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +000091 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -070092
Dan Willemsen2bb82d02019-12-27 09:35:42 -080093 // Autodetected
94 totalRAM uint64
95
Dan Willemsene3336352020-01-02 19:10:38 -080096 brokenDupRules bool
97 brokenUsesNetwork bool
98 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -070099
100 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000101
Chris Parsonsef615e52022-08-18 22:04:11 -0400102 bazelProdMode bool
103 bazelDevMode bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000104
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700105 // Set by multiproduct_kati
106 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700107
108 metricsUploader string
Dan Willemsen1e704462016-08-21 15:17:17 -0700109}
110
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800111const srcDirFileCheck = "build/soong/root.bp"
112
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700113var buildFiles = []string{"Android.mk", "Android.bp"}
114
Patrice Arruda13848222019-04-22 17:12:02 -0700115type BuildAction uint
116
117const (
118 // Builds all of the modules and their dependencies of a specified directory, relative to the root
119 // directory of the source tree.
120 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
121
122 // Builds all of the modules and their dependencies of a list of specified directories. All specified
123 // directories are relative to the root directory of the source tree.
124 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700125
126 // Build a list of specified modules. If none was specified, simply build the whole source tree.
127 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700128)
129
130// checkTopDir validates that the current directory is at the root directory of the source tree.
131func checkTopDir(ctx Context) {
132 if _, err := os.Stat(srcDirFileCheck); err != nil {
133 if os.IsNotExist(err) {
134 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
135 }
136 ctx.Fatalln("Error verifying tree state:", err)
137 }
138}
139
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500140// fetchEnvConfig optionally fetches environment config from an
141// experiments system to control Soong features dynamically.
142func fetchEnvConfig(ctx Context, config *configImpl, envConfigName string) error {
David Goldsmith62243a32022-04-08 13:42:04 +0000143 configName := envConfigName + "." + jsonSuffix
Kousik Kumarc75e1292022-07-07 02:20:51 +0000144 expConfigFetcher := &smpb.ExpConfigFetcher{Filename: &configName}
David Goldsmith62243a32022-04-08 13:42:04 +0000145 defer func() {
146 ctx.Metrics.ExpConfigFetcher(expConfigFetcher)
147 }()
Kousik Kumarc75e1292022-07-07 02:20:51 +0000148 if !config.GoogleProdCredsExist() {
149 status := smpb.ExpConfigFetcher_MISSING_GCERT
150 expConfigFetcher.Status = &status
151 return nil
152 }
David Goldsmith62243a32022-04-08 13:42:04 +0000153
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500154 s, err := os.Stat(configFetcher)
155 if err != nil {
156 if os.IsNotExist(err) {
157 return nil
158 }
159 return err
160 }
161 if s.Mode()&0111 == 0 {
David Goldsmith62243a32022-04-08 13:42:04 +0000162 status := smpb.ExpConfigFetcher_ERROR
163 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500164 return fmt.Errorf("configuration fetcher binary %v is not executable: %v", configFetcher, s.Mode())
165 }
166
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500167 tCtx, cancel := context.WithTimeout(ctx, envConfigFetchTimeout)
168 defer cancel()
David Goldsmith62243a32022-04-08 13:42:04 +0000169 fetchStart := time.Now()
170 cmd := exec.CommandContext(tCtx, configFetcher, "-output_config_dir", config.OutDir(),
171 "-output_config_name", configName)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500172 if err := cmd.Start(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000173 status := smpb.ExpConfigFetcher_ERROR
174 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500175 return err
176 }
177
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500178 if err := cmd.Wait(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000179 status := smpb.ExpConfigFetcher_ERROR
180 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500181 return err
182 }
David Goldsmith62243a32022-04-08 13:42:04 +0000183 fetchEnd := time.Now()
184 expConfigFetcher.Micros = proto.Uint64(uint64(fetchEnd.Sub(fetchStart).Microseconds()))
185 outConfigFilePath := filepath.Join(config.OutDir(), configName)
186 expConfigFetcher.Filename = proto.String(outConfigFilePath)
187 if _, err := os.Stat(outConfigFilePath); err == nil {
188 status := smpb.ExpConfigFetcher_CONFIG
189 expConfigFetcher.Status = &status
190 } else {
191 status := smpb.ExpConfigFetcher_NO_CONFIG
192 expConfigFetcher.Status = &status
193 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500194 return nil
195}
196
197func loadEnvConfig(ctx Context, config *configImpl) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500198 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
199 if bc == "" {
200 return nil
201 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500202
203 if err := fetchEnvConfig(ctx, config, bc); err != nil {
Kousik Kumar595fb1c2022-06-24 16:49:52 +0000204 ctx.Verbosef("Failed to fetch config file: %v\n", err)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500205 }
206
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500207 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500208 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500209 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500210 envConfigDir,
211 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500212 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500213 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
214 envVarsJSON, err := ioutil.ReadFile(cfgFile)
215 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500216 continue
217 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500218 ctx.Verbosef("Loading config file %v\n", cfgFile)
219 var envVars map[string]map[string]string
220 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
221 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
222 continue
223 }
224 for k, v := range envVars["env"] {
225 if os.Getenv(k) != "" {
226 continue
227 }
228 config.environ.Set(k, v)
229 }
230 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
231 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500232 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500233
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500234 return nil
235}
236
Dan Willemsen1e704462016-08-21 15:17:17 -0700237func NewConfig(ctx Context, args ...string) Config {
238 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000239 environ: OsEnvironment(),
240 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700241 }
242
Patrice Arruda90109172020-07-28 18:07:27 +0000243 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700244 ret.parallel = runtime.NumCPU() + 2
245 ret.keepGoing = 1
246
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800247 ret.totalRAM = detectTotalRAM(ctx)
248
Dan Willemsen9b587492017-07-10 22:13:00 -0700249 ret.parseArgs(ctx, args)
250
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800251 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700252 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
253 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
254 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800255 outDir := "out"
256 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
257 if wd, err := os.Getwd(); err != nil {
258 ctx.Fatalln("Failed to get working directory:", err)
259 } else {
260 outDir = filepath.Join(baseDir, filepath.Base(wd))
261 }
262 }
263 ret.environ.Set("OUT_DIR", outDir)
264 }
265
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500266 // loadEnvConfig needs to know what the OUT_DIR is, so it should
267 // be called after we determine the appropriate out directory.
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500268 if err := loadEnvConfig(ctx, ret); err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500269 ctx.Fatalln("Failed to parse env config files: %v", err)
270 }
271
Dan Willemsen2d31a442018-10-20 21:33:41 -0700272 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
273 ret.distDir = filepath.Clean(distDir)
274 } else {
275 ret.distDir = filepath.Join(ret.OutDir(), "dist")
276 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700277
Spandan Das05063612021-06-25 01:39:04 +0000278 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
279 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
280 }
281
Dan Willemsen1e704462016-08-21 15:17:17 -0700282 ret.environ.Unset(
283 // We're already using it
284 "USE_SOONG_UI",
285
286 // We should never use GOROOT/GOPATH from the shell environment
287 "GOROOT",
288 "GOPATH",
289
290 // These should only come from Soong, not the environment.
291 "CLANG",
292 "CLANG_CXX",
293 "CCC_CC",
294 "CCC_CXX",
295
296 // Used by the goma compiler wrapper, but should only be set by
297 // gomacc
298 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800299
300 // We handle this above
301 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700302
Dan Willemsen2d31a442018-10-20 21:33:41 -0700303 // This is handled above too, and set for individual commands later
304 "DIST_DIR",
305
Dan Willemsen68a09852017-04-18 13:56:57 -0700306 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000307 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700308 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700309 "DISPLAY",
310 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700311 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700312 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700313
314 // Drop make flags
315 "MAKEFLAGS",
316 "MAKELEVEL",
317 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700318
319 // Set in envsetup.sh, reset in makefiles
320 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700321
322 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
323 "ANDROID_BUILD_TOP",
324 "ANDROID_HOST_OUT",
325 "ANDROID_PRODUCT_OUT",
326 "ANDROID_HOST_OUT_TESTCASES",
327 "ANDROID_TARGET_OUT_TESTCASES",
328 "ANDROID_TOOLCHAIN",
329 "ANDROID_TOOLCHAIN_2ND_ARCH",
330 "ANDROID_DEV_SCRIPTS",
331 "ANDROID_EMULATOR_PREBUILTS",
332 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700333 )
334
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400335 if ret.UseGoma() || ret.ForceUseGoma() {
336 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
337 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400338 }
339
Dan Willemsen1e704462016-08-21 15:17:17 -0700340 // Tell python not to spam the source tree with .pyc files.
341 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
342
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400343 tmpDir := absPath(ctx, ret.TempDir())
344 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800345
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700346 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
347 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
348 "llvm-binutils-stable/llvm-symbolizer")
349 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
350
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800351 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700352 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800353
Yu Liu6e13b402021-07-27 14:29:06 -0700354 srcDir := absPath(ctx, ".")
355 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700356 ctx.Println("You are building in a directory whose absolute path contains a space character:")
357 ctx.Println()
358 ctx.Printf("%q\n", srcDir)
359 ctx.Println()
360 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700361 }
362
Yu Liu6e13b402021-07-27 14:29:06 -0700363 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
364
Dan Willemsendb8457c2017-05-12 16:38:17 -0700365 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700366 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
367 ctx.Println()
368 ctx.Printf("%q\n", outDir)
369 ctx.Println()
370 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700371 }
372
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000373 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700374 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
375 ctx.Println()
376 ctx.Printf("%q\n", distDir)
377 ctx.Println()
378 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700379 }
380
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700381 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000382 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
383 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100384 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800385 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700386 javaHome := func() string {
387 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
388 return override
389 }
Colin Cross59c1e6a2022-03-04 13:37:19 -0800390 if ret.environ.IsEnvTrue("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN") {
391 return java17Home
392 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000393 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
394 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 +0100395 }
Pete Gillinabbcdda2019-10-28 16:15:33 +0000396 return java11Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700397 }()
398 absJavaHome := absPath(ctx, javaHome)
399
Dan Willemsened869522018-01-08 14:58:46 -0800400 ret.configureLocale(ctx)
401
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700402 newPath := []string{filepath.Join(absJavaHome, "bin")}
403 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
404 newPath = append(newPath, path)
405 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100406
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700407 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
408 ret.environ.Set("JAVA_HOME", absJavaHome)
409 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000410 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
411 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100412 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700413 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
414
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800415 outDir := ret.OutDir()
416 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800417 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800418 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800419 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800420 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800421 }
Colin Cross28f527c2019-11-26 16:19:04 -0800422
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800423 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
424
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400425 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400426 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400427 ret.environ.Set(k, v)
428 }
429 }
430
Patrice Arruda83842d72020-12-08 19:42:08 +0000431 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800432 if err := os.RemoveAll(bpd); err != nil {
433 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
434 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000435
Patrice Arruda96850362020-08-11 20:41:11 +0000436 c := Config{ret}
437 storeConfigMetrics(ctx, c)
438 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700439}
440
Patrice Arruda13848222019-04-22 17:12:02 -0700441// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
442// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700443func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
444 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700445}
446
Patrice Arruda96850362020-08-11 20:41:11 +0000447// storeConfigMetrics selects a set of configuration information and store in
448// the metrics system for further analysis.
449func storeConfigMetrics(ctx Context, config Config) {
450 if ctx.Metrics == nil {
451 return
452 }
453
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400454 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000455
456 s := &smpb.SystemResourceInfo{
457 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
458 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
459 }
460 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000461}
462
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400463func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700464 c := &smpb.BuildConfig{
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400465 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
466 UseGoma: proto.Bool(config.UseGoma()),
467 UseRbe: proto.Bool(config.UseRBE()),
Chris Parsonsef615e52022-08-18 22:04:11 -0400468 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400469 }
Yu Liue737a992021-10-04 13:21:41 -0700470 c.Targets = append(c.Targets, config.arguments...)
471
472 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400473}
474
Patrice Arruda13848222019-04-22 17:12:02 -0700475// getConfigArgs processes the command arguments based on the build action and creates a set of new
476// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700477func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700478 // The next block of code verifies that the current directory is the root directory of the source
479 // tree. It then finds the relative path of dir based on the root directory of the source tree
480 // and verify that dir is inside of the source tree.
481 checkTopDir(ctx)
482 topDir, err := os.Getwd()
483 if err != nil {
484 ctx.Fatalf("Error retrieving top directory: %v", err)
485 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700486 dir, err = filepath.EvalSymlinks(dir)
487 if err != nil {
488 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
489 }
Patrice Arruda13848222019-04-22 17:12:02 -0700490 dir, err = filepath.Abs(dir)
491 if err != nil {
492 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
493 }
494 relDir, err := filepath.Rel(topDir, dir)
495 if err != nil {
496 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
497 }
498 // If there are ".." in the path, it's not in the source tree.
499 if strings.Contains(relDir, "..") {
500 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
501 }
502
503 configArgs := args[:]
504
505 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
506 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
507 targetNamePrefix := "MODULES-IN-"
508 if inList("GET-INSTALL-PATH", configArgs) {
509 targetNamePrefix = "GET-INSTALL-PATH-IN-"
510 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
511 }
512
Patrice Arruda13848222019-04-22 17:12:02 -0700513 var targets []string
514
515 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700516 case BUILD_MODULES:
517 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700518 case BUILD_MODULES_IN_A_DIRECTORY:
519 // If dir is the root source tree, all the modules are built of the source tree are built so
520 // no need to find the build file.
521 if topDir == dir {
522 break
523 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700524
Patrice Arruda13848222019-04-22 17:12:02 -0700525 buildFile := findBuildFile(ctx, relDir)
526 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700527 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700528 }
Patrice Arruda13848222019-04-22 17:12:02 -0700529 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
530 case BUILD_MODULES_IN_DIRECTORIES:
531 newConfigArgs, dirs := splitArgs(configArgs)
532 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700533 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700534 }
535
536 // Tidy only override all other specified targets.
537 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
538 if tidyOnly == "true" || tidyOnly == "1" {
539 configArgs = append(configArgs, "tidy_only")
540 } else {
541 configArgs = append(configArgs, targets...)
542 }
543
544 return configArgs
545}
546
547// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
548func convertToTarget(dir string, targetNamePrefix string) string {
549 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
550}
551
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700552// hasBuildFile returns true if dir contains an Android build file.
553func hasBuildFile(ctx Context, dir string) bool {
554 for _, buildFile := range buildFiles {
555 _, err := os.Stat(filepath.Join(dir, buildFile))
556 if err == nil {
557 return true
558 }
559 if !os.IsNotExist(err) {
560 ctx.Fatalf("Error retrieving the build file stats: %v", err)
561 }
562 }
563 return false
564}
565
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700566// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
567// in the current and any sub directory of dir. If a build file is not found, traverse the path
568// up by one directory and repeat again until either a build file is found or reached to the root
569// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
570// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700571func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700572 // If the string is empty or ".", assume it is top directory of the source tree.
573 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700574 return ""
575 }
576
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700577 found := false
578 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
579 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
580 if err != nil {
581 return err
582 }
583 if found {
584 return filepath.SkipDir
585 }
586 if info.IsDir() {
587 return nil
588 }
589 for _, buildFile := range buildFiles {
590 if info.Name() == buildFile {
591 found = true
592 return filepath.SkipDir
593 }
594 }
595 return nil
596 })
597 if err != nil {
598 ctx.Fatalf("Error finding Android build file: %v", err)
599 }
600
601 if found {
602 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700603 }
604 }
605
606 return ""
607}
608
609// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
610func splitArgs(args []string) (newArgs []string, dirs []string) {
611 specialArgs := map[string]bool{
612 "showcommands": true,
613 "snod": true,
614 "dist": true,
615 "checkbuild": true,
616 }
617
618 newArgs = []string{}
619 dirs = []string{}
620
621 for _, arg := range args {
622 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
623 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
624 newArgs = append(newArgs, arg)
625 continue
626 }
627
628 if _, ok := specialArgs[arg]; ok {
629 newArgs = append(newArgs, arg)
630 continue
631 }
632
633 dirs = append(dirs, arg)
634 }
635
636 return newArgs, dirs
637}
638
639// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
640// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
641// source root tree where the build action command was invoked. Each directory is validated if the
642// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700643func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700644 for _, dir := range dirs {
645 // The directory may have specified specific modules to build. ":" is the separator to separate
646 // the directory and the list of modules.
647 s := strings.Split(dir, ":")
648 l := len(s)
649 if l > 2 { // more than one ":" was specified.
650 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
651 }
652
653 dir = filepath.Join(relDir, s[0])
654 if _, err := os.Stat(dir); err != nil {
655 ctx.Fatalf("couldn't find directory %s", dir)
656 }
657
658 // Verify that if there are any targets specified after ":". Each target is separated by ",".
659 var newTargets []string
660 if l == 2 && s[1] != "" {
661 newTargets = strings.Split(s[1], ",")
662 if inList("", newTargets) {
663 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
664 }
665 }
666
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700667 // If there are specified targets to build in dir, an android build file must exist for the one
668 // shot build. For the non-targets case, find the appropriate build file and build all the
669 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700670 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700671 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700672 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
673 }
674 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700675 buildFile := findBuildFile(ctx, dir)
676 if buildFile == "" {
677 ctx.Fatalf("Build file not found for %s directory", dir)
678 }
679 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700680 }
681
Patrice Arruda13848222019-04-22 17:12:02 -0700682 targets = append(targets, newTargets...)
683 }
684
Dan Willemsence41e942019-07-29 23:39:30 -0700685 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700686}
687
Dan Willemsen9b587492017-07-10 22:13:00 -0700688func (c *configImpl) parseArgs(ctx Context, args []string) {
689 for i := 0; i < len(args); i++ {
690 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100691 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700692 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200693 } else if arg == "--empty-ninja-file" {
694 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100695 } else if arg == "--skip-ninja" {
696 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700697 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700698 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
699 // but it does run a Kati ninja file if the .kati_enabled marker file was created
700 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000701 c.skipConfig = true
702 c.skipKati = true
703 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100704 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000705 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100706 } else if arg == "--soong-only" {
707 c.skipKati = true
708 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200709 } else if arg == "--config-only" {
710 c.skipKati = true
711 c.skipKatiNinja = true
712 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700713 } else if arg == "--skip-config" {
714 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700715 } else if arg == "--skip-soong-tests" {
716 c.skipSoongTests = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500717 } else if arg == "--mk-metrics" {
718 c.reportMkMetrics = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400719 } else if arg == "--bazel-mode" {
720 c.bazelProdMode = true
721 } else if arg == "--bazel-mode-dev" {
722 c.bazelDevMode = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700723 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700724 parseArgNum := func(def int) int {
725 if len(arg) > 2 {
726 p, err := strconv.ParseUint(arg[2:], 10, 31)
727 if err != nil {
728 ctx.Fatalf("Failed to parse %q: %v", arg, err)
729 }
730 return int(p)
731 } else if i+1 < len(args) {
732 p, err := strconv.ParseUint(args[i+1], 10, 31)
733 if err == nil {
734 i++
735 return int(p)
736 }
737 }
738 return def
739 }
740
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700741 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700742 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700743 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700744 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700745 } else {
746 ctx.Fatalln("Unknown option:", arg)
747 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700748 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700749 if k == "OUT_DIR" {
750 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
751 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700752 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700753 } else if arg == "dist" {
754 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200755 } else if arg == "json-module-graph" {
756 c.jsonModuleGraph = true
757 } else if arg == "bp2build" {
758 c.bp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200759 } else if arg == "queryview" {
760 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200761 } else if arg == "soong_docs" {
762 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700763 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700764 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800765 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700766 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700767 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700768 }
769 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700770}
771
Dan Willemsened869522018-01-08 14:58:46 -0800772func (c *configImpl) configureLocale(ctx Context) {
773 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
774 output, err := cmd.Output()
775
776 var locales []string
777 if err == nil {
778 locales = strings.Split(string(output), "\n")
779 } else {
780 // If we're unable to list the locales, let's assume en_US.UTF-8
781 locales = []string{"en_US.UTF-8"}
782 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
783 }
784
785 // gettext uses LANGUAGE, which is passed directly through
786
787 // For LANG and LC_*, only preserve the evaluated version of
788 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800789 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800790 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800791 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800792 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800793 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800794 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800795 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800796 }
797
798 c.environ.UnsetWithPrefix("LC_")
799
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800800 if userLang != "" {
801 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800802 }
803
804 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
805 // for others)
806 if inList("C.UTF-8", locales) {
807 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500808 } else if inList("C.utf8", locales) {
809 // These normalize to the same thing
810 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800811 } else if inList("en_US.UTF-8", locales) {
812 c.environ.Set("LANG", "en_US.UTF-8")
813 } else if inList("en_US.utf8", locales) {
814 // These normalize to the same thing
815 c.environ.Set("LANG", "en_US.UTF-8")
816 } else {
817 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
818 }
819}
820
Dan Willemsen1e704462016-08-21 15:17:17 -0700821func (c *configImpl) Environment() *Environment {
822 return c.environ
823}
824
825func (c *configImpl) Arguments() []string {
826 return c.arguments
827}
828
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200829func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200830 if len(c.Arguments()) > 0 {
831 // Explicit targets requested that are not special targets like b2pbuild
832 // or the JSON module graph
833 return true
834 }
835
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200836 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200837 // Command line was empty, the default Ninja target is built
838 return true
839 }
840
Liz Kammer88677422021-12-15 15:03:19 -0500841 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
842 if c.Dist() && !c.Bp2Build() {
843 return true
844 }
845
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200846 // build.ninja doesn't need to be generated
847 return false
848}
849
Dan Willemsen1e704462016-08-21 15:17:17 -0700850func (c *configImpl) OutDir() string {
851 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700852 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700853 }
854 return "out"
855}
856
Dan Willemsen8a073a82017-02-04 17:30:44 -0800857func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400858 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000859}
860
861func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700862 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800863}
864
Dan Willemsen1e704462016-08-21 15:17:17 -0700865func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000866 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700867 return c.arguments
868 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700869 return c.ninjaArgs
870}
871
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500872func (c *configImpl) BazelOutDir() string {
873 return filepath.Join(c.OutDir(), "bazel")
874}
875
Dan Willemsen1e704462016-08-21 15:17:17 -0700876func (c *configImpl) SoongOutDir() string {
877 return filepath.Join(c.OutDir(), "soong")
878}
879
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200880func (c *configImpl) PrebuiltOS() string {
881 switch runtime.GOOS {
882 case "linux":
883 return "linux-x86"
884 case "darwin":
885 return "darwin-x86"
886 default:
887 panic("Unknown GOOS")
888 }
889}
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100890
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200891func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -0700892 if c.SkipKatiNinja() {
893 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
894 } else {
895 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
896 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200897}
898
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200899func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100900 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200901}
902
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200903func (c *configImpl) UsedEnvFile(tag string) string {
904 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
905}
906
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200907func (c *configImpl) Bp2BuildMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100908 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200909}
910
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200911func (c *configImpl) SoongDocsHtml() string {
912 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
913}
914
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200915func (c *configImpl) QueryviewMarkerFile() string {
916 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
917}
918
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200919func (c *configImpl) ModuleGraphFile() string {
920 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
921}
922
kgui67007242022-01-25 13:50:25 +0800923func (c *configImpl) ModuleActionsFile() string {
924 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
925}
926
Jeff Gastonefc1b412017-03-29 17:29:06 -0700927func (c *configImpl) TempDir() string {
928 return shared.TempDirForOutDir(c.SoongOutDir())
929}
930
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700931func (c *configImpl) FileListDir() string {
932 return filepath.Join(c.OutDir(), ".module_paths")
933}
934
Dan Willemsen1e704462016-08-21 15:17:17 -0700935func (c *configImpl) KatiSuffix() string {
936 if c.katiSuffix != "" {
937 return c.katiSuffix
938 }
939 panic("SetKatiSuffix has not been called")
940}
941
Colin Cross37193492017-11-16 17:55:00 -0800942// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
943// user is interested in additional checks at the expense of build time.
944func (c *configImpl) Checkbuild() bool {
945 return c.checkbuild
946}
947
Dan Willemsen8a073a82017-02-04 17:30:44 -0800948func (c *configImpl) Dist() bool {
949 return c.dist
950}
951
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200952func (c *configImpl) JsonModuleGraph() bool {
953 return c.jsonModuleGraph
954}
955
956func (c *configImpl) Bp2Build() bool {
957 return c.bp2build
958}
959
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200960func (c *configImpl) Queryview() bool {
961 return c.queryview
962}
963
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200964func (c *configImpl) SoongDocs() bool {
965 return c.soongDocs
966}
967
Dan Willemsen1e704462016-08-21 15:17:17 -0700968func (c *configImpl) IsVerbose() bool {
969 return c.verbose
970}
971
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000972func (c *configImpl) SkipKati() bool {
973 return c.skipKati
974}
975
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100976func (c *configImpl) SkipKatiNinja() bool {
977 return c.skipKatiNinja
978}
979
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200980func (c *configImpl) SkipSoong() bool {
981 return c.skipSoong
982}
983
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100984func (c *configImpl) SkipNinja() bool {
985 return c.skipNinja
986}
987
Anton Hansson5a7861a2021-06-04 10:09:01 +0100988func (c *configImpl) SetSkipNinja(v bool) {
989 c.skipNinja = v
990}
991
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000992func (c *configImpl) SkipConfig() bool {
993 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -0700994}
995
Dan Willemsen1e704462016-08-21 15:17:17 -0700996func (c *configImpl) TargetProduct() string {
997 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
998 return v
999 }
1000 panic("TARGET_PRODUCT is not defined")
1001}
1002
Dan Willemsen02781d52017-05-12 19:28:13 -07001003func (c *configImpl) TargetDevice() string {
1004 return c.targetDevice
1005}
1006
1007func (c *configImpl) SetTargetDevice(device string) {
1008 c.targetDevice = device
1009}
1010
1011func (c *configImpl) TargetBuildVariant() string {
1012 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1013 return v
1014 }
1015 panic("TARGET_BUILD_VARIANT is not defined")
1016}
1017
Dan Willemsen1e704462016-08-21 15:17:17 -07001018func (c *configImpl) KatiArgs() []string {
1019 return c.katiArgs
1020}
1021
1022func (c *configImpl) Parallel() int {
1023 return c.parallel
1024}
1025
Colin Cross8b8bec32019-11-15 13:18:43 -08001026func (c *configImpl) HighmemParallel() int {
1027 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1028 return i
1029 }
1030
1031 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1032 parallel := c.Parallel()
1033 if c.UseRemoteBuild() {
1034 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1035 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1036 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1037 // Return 1/16th of the size of the local pool, rounding up.
1038 return (parallel + 15) / 16
1039 } else if c.totalRAM == 0 {
1040 // Couldn't detect the total RAM, don't restrict highmem processes.
1041 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001042 } else if c.totalRAM <= 16*1024*1024*1024 {
1043 // Less than 16GB of ram, restrict to 1 highmem processes
1044 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001045 } else if c.totalRAM <= 32*1024*1024*1024 {
1046 // Less than 32GB of ram, restrict to 2 highmem processes
1047 return 2
1048 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1049 // If less than 8GB total RAM per process, reduce the number of highmem processes
1050 return p
1051 }
1052 // No restriction on highmem processes
1053 return parallel
1054}
1055
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001056func (c *configImpl) TotalRAM() uint64 {
1057 return c.totalRAM
1058}
1059
Kousik Kumarec478642020-09-21 13:39:24 -04001060// ForceUseGoma determines whether we should override Goma deprecation
1061// and use Goma for the current build or not.
1062func (c *configImpl) ForceUseGoma() bool {
1063 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1064 v = strings.TrimSpace(v)
1065 if v != "" && v != "false" {
1066 return true
1067 }
1068 }
1069 return false
1070}
1071
Dan Willemsen1e704462016-08-21 15:17:17 -07001072func (c *configImpl) UseGoma() bool {
1073 if v, ok := c.environ.Get("USE_GOMA"); ok {
1074 v = strings.TrimSpace(v)
1075 if v != "" && v != "false" {
1076 return true
1077 }
1078 }
1079 return false
1080}
1081
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001082func (c *configImpl) StartGoma() bool {
1083 if !c.UseGoma() {
1084 return false
1085 }
1086
1087 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1088 v = strings.TrimSpace(v)
1089 if v != "" && v != "false" {
1090 return false
1091 }
1092 }
1093 return true
1094}
1095
Ramy Medhatbbf25672019-07-17 12:30:04 +00001096func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001097 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001098 v = strings.TrimSpace(v)
1099 if v != "" && v != "false" {
1100 return true
1101 }
1102 }
1103 return false
1104}
1105
Chris Parsonsef615e52022-08-18 22:04:11 -04001106func (c *configImpl) BazelBuildEnabled() bool {
1107 return c.bazelProdMode || c.bazelDevMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001108}
1109
Ramy Medhatbbf25672019-07-17 12:30:04 +00001110func (c *configImpl) StartRBE() bool {
1111 if !c.UseRBE() {
1112 return false
1113 }
1114
1115 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1116 v = strings.TrimSpace(v)
1117 if v != "" && v != "false" {
1118 return false
1119 }
1120 }
1121 return true
1122}
1123
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001124func (c *configImpl) rbeProxyLogsDir() string {
1125 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001126 if v, ok := c.environ.Get(f); ok {
1127 return v
1128 }
1129 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001130 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1131 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001132}
1133
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001134func (c *configImpl) shouldCleanupRBELogsDir() bool {
1135 // Perform a log directory cleanup only when the log directory
1136 // is auto created by the build rather than user-specified.
1137 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1138 if _, ok := c.environ.Get(f); ok {
1139 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001140 }
1141 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001142 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001143}
1144
1145func (c *configImpl) rbeExecRoot() string {
1146 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1147 if v, ok := c.environ.Get(f); ok {
1148 return v
1149 }
1150 }
1151 wd, err := os.Getwd()
1152 if err != nil {
1153 return ""
1154 }
1155 return wd
1156}
1157
1158func (c *configImpl) rbeDir() string {
1159 if v, ok := c.environ.Get("RBE_DIR"); ok {
1160 return v
1161 }
1162 return "prebuilts/remoteexecution-client/live/"
1163}
1164
1165func (c *configImpl) rbeReproxy() string {
1166 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1167 if v, ok := c.environ.Get(f); ok {
1168 return v
1169 }
1170 }
1171 return filepath.Join(c.rbeDir(), "reproxy")
1172}
1173
1174func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001175 credFlags := []string{
1176 "use_application_default_credentials",
1177 "use_gce_credentials",
1178 "credential_file",
1179 "use_google_prod_creds",
1180 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001181 for _, cf := range credFlags {
1182 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1183 if v, ok := c.environ.Get(f); ok {
1184 v = strings.TrimSpace(v)
1185 if v != "" && v != "false" && v != "0" {
1186 return "RBE_" + cf, v
1187 }
1188 }
1189 }
1190 }
1191 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001192}
1193
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001194func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1195 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1196 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1197
1198 name := filepath.Join(dir, base)
1199 if len(name) < maxNameLen {
1200 return name, nil
1201 }
1202
1203 name = filepath.Join("/tmp", base)
1204 if len(name) < maxNameLen {
1205 return name, nil
1206 }
1207
1208 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1209}
1210
Kousik Kumar7bc78192022-04-27 14:52:56 -04001211// IsGooglerEnvironment returns true if the current build is running
1212// on a Google developer machine and false otherwise.
1213func (c *configImpl) IsGooglerEnvironment() bool {
1214 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1215 if v, ok := c.environ.Get(cf); ok {
1216 return v == "googler"
1217 }
1218 return false
1219}
1220
1221// GoogleProdCredsExist determine whether credentials exist on the
1222// Googler machine to use remote execution.
1223func (c *configImpl) GoogleProdCredsExist() bool {
1224 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1225 return false
1226 }
1227 return true
1228}
1229
1230// UseRemoteBuild indicates whether to use a remote build acceleration system
1231// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001232func (c *configImpl) UseRemoteBuild() bool {
1233 return c.UseGoma() || c.UseRBE()
1234}
1235
Kousik Kumar7bc78192022-04-27 14:52:56 -04001236// StubbyExists checks whether the stubby binary exists on the machine running
1237// the build.
1238func (c *configImpl) StubbyExists() bool {
1239 if _, err := exec.LookPath("stubby"); err != nil {
1240 return false
1241 }
1242 return true
1243}
1244
Dan Willemsen1e704462016-08-21 15:17:17 -07001245// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001246// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001247// still limited by Parallel()
1248func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001249 if !c.UseRemoteBuild() {
1250 return 0
1251 }
1252 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1253 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001254 }
1255 return 500
1256}
1257
1258func (c *configImpl) SetKatiArgs(args []string) {
1259 c.katiArgs = args
1260}
1261
1262func (c *configImpl) SetNinjaArgs(args []string) {
1263 c.ninjaArgs = args
1264}
1265
1266func (c *configImpl) SetKatiSuffix(suffix string) {
1267 c.katiSuffix = suffix
1268}
1269
Dan Willemsene0879fc2017-08-04 15:06:27 -07001270func (c *configImpl) LastKatiSuffixFile() string {
1271 return filepath.Join(c.OutDir(), "last_kati_suffix")
1272}
1273
1274func (c *configImpl) HasKatiSuffix() bool {
1275 return c.katiSuffix != ""
1276}
1277
Dan Willemsen1e704462016-08-21 15:17:17 -07001278func (c *configImpl) KatiEnvFile() string {
1279 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1280}
1281
Dan Willemsen29971232018-09-26 14:58:30 -07001282func (c *configImpl) KatiBuildNinjaFile() string {
1283 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001284}
1285
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001286func (c *configImpl) KatiPackageNinjaFile() string {
1287 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1288}
1289
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001290func (c *configImpl) SoongVarsFile() string {
1291 return filepath.Join(c.SoongOutDir(), "soong.variables")
1292}
1293
Dan Willemsen1e704462016-08-21 15:17:17 -07001294func (c *configImpl) SoongNinjaFile() string {
1295 return filepath.Join(c.SoongOutDir(), "build.ninja")
1296}
1297
1298func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001299 if c.katiSuffix == "" {
1300 return filepath.Join(c.OutDir(), "combined.ninja")
1301 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001302 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1303}
1304
1305func (c *configImpl) SoongAndroidMk() string {
1306 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1307}
1308
1309func (c *configImpl) SoongMakeVarsMk() string {
1310 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1311}
1312
Dan Willemsenf052f782017-05-18 15:29:04 -07001313func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001314 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001315}
1316
Dan Willemsen02781d52017-05-12 19:28:13 -07001317func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001318 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1319}
1320
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001321func (c *configImpl) KatiPackageMkDir() string {
1322 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1323}
1324
Dan Willemsenf052f782017-05-18 15:29:04 -07001325func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001326 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001327}
1328
1329func (c *configImpl) HostOut() string {
1330 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1331}
1332
1333// This probably needs to be multi-valued, so not exporting it for now
1334func (c *configImpl) hostCrossOut() string {
1335 if runtime.GOOS == "linux" {
1336 return filepath.Join(c.hostOutRoot(), "windows-x86")
1337 } else {
1338 return ""
1339 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001340}
1341
Dan Willemsen1e704462016-08-21 15:17:17 -07001342func (c *configImpl) HostPrebuiltTag() string {
1343 if runtime.GOOS == "linux" {
1344 return "linux-x86"
1345 } else if runtime.GOOS == "darwin" {
1346 return "darwin-x86"
1347 } else {
1348 panic("Unsupported OS")
1349 }
1350}
Dan Willemsenf173d592017-04-27 14:28:00 -07001351
Dan Willemsen8122bd52017-10-12 20:20:41 -07001352func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001353 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1354 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001355 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1356 if _, err := os.Stat(asan); err == nil {
1357 return asan
1358 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001359 }
1360 }
1361 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1362}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001363
1364func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1365 c.brokenDupRules = val
1366}
1367
1368func (c *configImpl) BuildBrokenDupRules() bool {
1369 return c.brokenDupRules
1370}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001371
Dan Willemsen25e6f092019-04-09 10:22:43 -07001372func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1373 c.brokenUsesNetwork = val
1374}
1375
1376func (c *configImpl) BuildBrokenUsesNetwork() bool {
1377 return c.brokenUsesNetwork
1378}
1379
Dan Willemsene3336352020-01-02 19:10:38 -08001380func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1381 c.brokenNinjaEnvVars = val
1382}
1383
1384func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1385 return c.brokenNinjaEnvVars
1386}
1387
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001388func (c *configImpl) SetTargetDeviceDir(dir string) {
1389 c.targetDeviceDir = dir
1390}
1391
1392func (c *configImpl) TargetDeviceDir() string {
1393 return c.targetDeviceDir
1394}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001395
Patrice Arruda219eef32020-06-01 17:29:30 +00001396func (c *configImpl) BuildDateTime() string {
1397 return c.buildDateTime
1398}
1399
1400func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001401 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001402}
Patrice Arruda83842d72020-12-08 19:42:08 +00001403
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001404// LogsDir returns the absolute path to the logs directory where build log and
1405// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001406// directory. If the argument dist is specified, the logs directory
1407// is <dist_dir>/logs.
1408func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001409 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001410 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001411 // 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 -05001412 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001413 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001414 absDir, err := filepath.Abs(dir)
1415 if err != nil {
1416 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1417 os.Exit(1)
1418 }
1419 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001420}
1421
1422// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1423// where the bazel profiles are located.
1424func (c *configImpl) BazelMetricsDir() string {
1425 return filepath.Join(c.LogsDir(), "bazel_metrics")
1426}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001427
Chris Parsons53f68ae2022-03-03 12:01:40 -05001428// MkFileMetrics returns the file path for make-related metrics.
1429func (c *configImpl) MkMetrics() string {
1430 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1431}
1432
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001433func (c *configImpl) SetEmptyNinjaFile(v bool) {
1434 c.emptyNinjaFile = v
1435}
1436
1437func (c *configImpl) EmptyNinjaFile() bool {
1438 return c.emptyNinjaFile
1439}
Yu Liu6e13b402021-07-27 14:29:06 -07001440
1441func GetMetricsUploader(topDir string, env *Environment) string {
1442 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1443 metricsUploader := filepath.Join(topDir, p)
1444 if _, err := os.Stat(metricsUploader); err == nil {
1445 return metricsUploader
1446 }
1447 }
1448
1449 return ""
1450}