blob: 590aeb9be241f6a31ac4f3a3ec5514312b67e94d [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 // TODO(b/243077098): Remove useBazel.
103 useBazel bool
104 bazelProdMode bool
105 bazelDevMode bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000106
107 // During Bazel execution, Bazel cannot write outside OUT_DIR.
108 // So if DIST_DIR is set to an external dir (outside of OUT_DIR), we need to rig it temporarily and then migrate files at the end of the build.
109 riggedDistDirForBazel string
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700110
111 // Set by multiproduct_kati
112 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700113
114 metricsUploader string
Dan Willemsen1e704462016-08-21 15:17:17 -0700115}
116
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800117const srcDirFileCheck = "build/soong/root.bp"
118
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700119var buildFiles = []string{"Android.mk", "Android.bp"}
120
Patrice Arruda13848222019-04-22 17:12:02 -0700121type BuildAction uint
122
123const (
124 // Builds all of the modules and their dependencies of a specified directory, relative to the root
125 // directory of the source tree.
126 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
127
128 // Builds all of the modules and their dependencies of a list of specified directories. All specified
129 // directories are relative to the root directory of the source tree.
130 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700131
132 // Build a list of specified modules. If none was specified, simply build the whole source tree.
133 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700134)
135
136// checkTopDir validates that the current directory is at the root directory of the source tree.
137func checkTopDir(ctx Context) {
138 if _, err := os.Stat(srcDirFileCheck); err != nil {
139 if os.IsNotExist(err) {
140 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
141 }
142 ctx.Fatalln("Error verifying tree state:", err)
143 }
144}
145
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500146// fetchEnvConfig optionally fetches environment config from an
147// experiments system to control Soong features dynamically.
148func fetchEnvConfig(ctx Context, config *configImpl, envConfigName string) error {
David Goldsmith62243a32022-04-08 13:42:04 +0000149 configName := envConfigName + "." + jsonSuffix
Kousik Kumarc75e1292022-07-07 02:20:51 +0000150 expConfigFetcher := &smpb.ExpConfigFetcher{Filename: &configName}
David Goldsmith62243a32022-04-08 13:42:04 +0000151 defer func() {
152 ctx.Metrics.ExpConfigFetcher(expConfigFetcher)
153 }()
Kousik Kumarc75e1292022-07-07 02:20:51 +0000154 if !config.GoogleProdCredsExist() {
155 status := smpb.ExpConfigFetcher_MISSING_GCERT
156 expConfigFetcher.Status = &status
157 return nil
158 }
David Goldsmith62243a32022-04-08 13:42:04 +0000159
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500160 s, err := os.Stat(configFetcher)
161 if err != nil {
162 if os.IsNotExist(err) {
163 return nil
164 }
165 return err
166 }
167 if s.Mode()&0111 == 0 {
David Goldsmith62243a32022-04-08 13:42:04 +0000168 status := smpb.ExpConfigFetcher_ERROR
169 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500170 return fmt.Errorf("configuration fetcher binary %v is not executable: %v", configFetcher, s.Mode())
171 }
172
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500173 tCtx, cancel := context.WithTimeout(ctx, envConfigFetchTimeout)
174 defer cancel()
David Goldsmith62243a32022-04-08 13:42:04 +0000175 fetchStart := time.Now()
176 cmd := exec.CommandContext(tCtx, configFetcher, "-output_config_dir", config.OutDir(),
177 "-output_config_name", configName)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500178 if err := cmd.Start(); 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 }
183
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500184 if err := cmd.Wait(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000185 status := smpb.ExpConfigFetcher_ERROR
186 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500187 return err
188 }
David Goldsmith62243a32022-04-08 13:42:04 +0000189 fetchEnd := time.Now()
190 expConfigFetcher.Micros = proto.Uint64(uint64(fetchEnd.Sub(fetchStart).Microseconds()))
191 outConfigFilePath := filepath.Join(config.OutDir(), configName)
192 expConfigFetcher.Filename = proto.String(outConfigFilePath)
193 if _, err := os.Stat(outConfigFilePath); err == nil {
194 status := smpb.ExpConfigFetcher_CONFIG
195 expConfigFetcher.Status = &status
196 } else {
197 status := smpb.ExpConfigFetcher_NO_CONFIG
198 expConfigFetcher.Status = &status
199 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500200 return nil
201}
202
203func loadEnvConfig(ctx Context, config *configImpl) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500204 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
205 if bc == "" {
206 return nil
207 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500208
209 if err := fetchEnvConfig(ctx, config, bc); err != nil {
Kousik Kumar595fb1c2022-06-24 16:49:52 +0000210 ctx.Verbosef("Failed to fetch config file: %v\n", err)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500211 }
212
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500213 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500214 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500215 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500216 envConfigDir,
217 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500218 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500219 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
220 envVarsJSON, err := ioutil.ReadFile(cfgFile)
221 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500222 continue
223 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500224 ctx.Verbosef("Loading config file %v\n", cfgFile)
225 var envVars map[string]map[string]string
226 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
227 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
228 continue
229 }
230 for k, v := range envVars["env"] {
231 if os.Getenv(k) != "" {
232 continue
233 }
234 config.environ.Set(k, v)
235 }
236 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
237 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500238 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500239
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500240 return nil
241}
242
Dan Willemsen1e704462016-08-21 15:17:17 -0700243func NewConfig(ctx Context, args ...string) Config {
244 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000245 environ: OsEnvironment(),
246 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700247 }
248
Patrice Arruda90109172020-07-28 18:07:27 +0000249 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700250 ret.parallel = runtime.NumCPU() + 2
251 ret.keepGoing = 1
252
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800253 ret.totalRAM = detectTotalRAM(ctx)
254
Dan Willemsen9b587492017-07-10 22:13:00 -0700255 ret.parseArgs(ctx, args)
256
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800257 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700258 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
259 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
260 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800261 outDir := "out"
262 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
263 if wd, err := os.Getwd(); err != nil {
264 ctx.Fatalln("Failed to get working directory:", err)
265 } else {
266 outDir = filepath.Join(baseDir, filepath.Base(wd))
267 }
268 }
269 ret.environ.Set("OUT_DIR", outDir)
270 }
271
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500272 // loadEnvConfig needs to know what the OUT_DIR is, so it should
273 // be called after we determine the appropriate out directory.
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500274 if err := loadEnvConfig(ctx, ret); err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500275 ctx.Fatalln("Failed to parse env config files: %v", err)
276 }
277
Dan Willemsen2d31a442018-10-20 21:33:41 -0700278 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
279 ret.distDir = filepath.Clean(distDir)
280 } else {
281 ret.distDir = filepath.Join(ret.OutDir(), "dist")
282 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700283
Spandan Das05063612021-06-25 01:39:04 +0000284 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
285 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
286 }
287
Dan Willemsen1e704462016-08-21 15:17:17 -0700288 ret.environ.Unset(
289 // We're already using it
290 "USE_SOONG_UI",
291
292 // We should never use GOROOT/GOPATH from the shell environment
293 "GOROOT",
294 "GOPATH",
295
296 // These should only come from Soong, not the environment.
297 "CLANG",
298 "CLANG_CXX",
299 "CCC_CC",
300 "CCC_CXX",
301
302 // Used by the goma compiler wrapper, but should only be set by
303 // gomacc
304 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800305
306 // We handle this above
307 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700308
Dan Willemsen2d31a442018-10-20 21:33:41 -0700309 // This is handled above too, and set for individual commands later
310 "DIST_DIR",
311
Dan Willemsen68a09852017-04-18 13:56:57 -0700312 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000313 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700314 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700315 "DISPLAY",
316 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700317 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700318 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700319
320 // Drop make flags
321 "MAKEFLAGS",
322 "MAKELEVEL",
323 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700324
325 // Set in envsetup.sh, reset in makefiles
326 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700327
328 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
329 "ANDROID_BUILD_TOP",
330 "ANDROID_HOST_OUT",
331 "ANDROID_PRODUCT_OUT",
332 "ANDROID_HOST_OUT_TESTCASES",
333 "ANDROID_TARGET_OUT_TESTCASES",
334 "ANDROID_TOOLCHAIN",
335 "ANDROID_TOOLCHAIN_2ND_ARCH",
336 "ANDROID_DEV_SCRIPTS",
337 "ANDROID_EMULATOR_PREBUILTS",
338 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700339 )
340
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400341 if ret.UseGoma() || ret.ForceUseGoma() {
342 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
343 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400344 }
345
Dan Willemsen1e704462016-08-21 15:17:17 -0700346 // Tell python not to spam the source tree with .pyc files.
347 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
348
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400349 tmpDir := absPath(ctx, ret.TempDir())
350 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800351
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700352 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
353 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
354 "llvm-binutils-stable/llvm-symbolizer")
355 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
356
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800357 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700358 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800359
Yu Liu6e13b402021-07-27 14:29:06 -0700360 srcDir := absPath(ctx, ".")
361 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700362 ctx.Println("You are building in a directory whose absolute path contains a space character:")
363 ctx.Println()
364 ctx.Printf("%q\n", srcDir)
365 ctx.Println()
366 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700367 }
368
Yu Liu6e13b402021-07-27 14:29:06 -0700369 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
370
Dan Willemsendb8457c2017-05-12 16:38:17 -0700371 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700372 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
373 ctx.Println()
374 ctx.Printf("%q\n", outDir)
375 ctx.Println()
376 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700377 }
378
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000379 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700380 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
381 ctx.Println()
382 ctx.Printf("%q\n", distDir)
383 ctx.Println()
384 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700385 }
386
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700387 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000388 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
389 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100390 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800391 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700392 javaHome := func() string {
393 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
394 return override
395 }
Colin Cross59c1e6a2022-03-04 13:37:19 -0800396 if ret.environ.IsEnvTrue("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN") {
397 return java17Home
398 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000399 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
400 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 +0100401 }
Pete Gillinabbcdda2019-10-28 16:15:33 +0000402 return java11Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700403 }()
404 absJavaHome := absPath(ctx, javaHome)
405
Dan Willemsened869522018-01-08 14:58:46 -0800406 ret.configureLocale(ctx)
407
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700408 newPath := []string{filepath.Join(absJavaHome, "bin")}
409 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
410 newPath = append(newPath, path)
411 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100412
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700413 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
414 ret.environ.Set("JAVA_HOME", absJavaHome)
415 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000416 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
417 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100418 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700419 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
420
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800421 outDir := ret.OutDir()
422 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800423 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800424 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800425 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800426 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800427 }
Colin Cross28f527c2019-11-26 16:19:04 -0800428
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800429 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
430
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400431 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400432 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400433 ret.environ.Set(k, v)
434 }
435 }
436
Patrice Arruda83842d72020-12-08 19:42:08 +0000437 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800438 if err := os.RemoveAll(bpd); err != nil {
439 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
440 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000441
442 ret.useBazel = ret.environ.IsEnvTrue("USE_BAZEL")
443
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800444 if ret.UseBazel() {
445 if err := os.MkdirAll(bpd, 0777); err != nil {
446 ctx.Fatalf("Failed to create bazel profile directory %q: %v", bpd, err)
447 }
448 }
449
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000450 if ret.UseBazel() {
451 ret.riggedDistDirForBazel = filepath.Join(ret.OutDir(), "dist")
452 } else {
453 // Not rigged
454 ret.riggedDistDirForBazel = ret.distDir
455 }
456
Patrice Arruda96850362020-08-11 20:41:11 +0000457 c := Config{ret}
458 storeConfigMetrics(ctx, c)
459 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700460}
461
Patrice Arruda13848222019-04-22 17:12:02 -0700462// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
463// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700464func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
465 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700466}
467
Patrice Arruda96850362020-08-11 20:41:11 +0000468// storeConfigMetrics selects a set of configuration information and store in
469// the metrics system for further analysis.
470func storeConfigMetrics(ctx Context, config Config) {
471 if ctx.Metrics == nil {
472 return
473 }
474
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400475 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000476
477 s := &smpb.SystemResourceInfo{
478 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
479 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
480 }
481 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000482}
483
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400484func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700485 c := &smpb.BuildConfig{
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400486 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
487 UseGoma: proto.Bool(config.UseGoma()),
488 UseRbe: proto.Bool(config.UseRBE()),
489 BazelAsNinja: proto.Bool(config.UseBazel()),
Chris Parsonsef615e52022-08-18 22:04:11 -0400490 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400491 }
Yu Liue737a992021-10-04 13:21:41 -0700492 c.Targets = append(c.Targets, config.arguments...)
493
494 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400495}
496
Patrice Arruda13848222019-04-22 17:12:02 -0700497// getConfigArgs processes the command arguments based on the build action and creates a set of new
498// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700499func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700500 // The next block of code verifies that the current directory is the root directory of the source
501 // tree. It then finds the relative path of dir based on the root directory of the source tree
502 // and verify that dir is inside of the source tree.
503 checkTopDir(ctx)
504 topDir, err := os.Getwd()
505 if err != nil {
506 ctx.Fatalf("Error retrieving top directory: %v", err)
507 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700508 dir, err = filepath.EvalSymlinks(dir)
509 if err != nil {
510 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
511 }
Patrice Arruda13848222019-04-22 17:12:02 -0700512 dir, err = filepath.Abs(dir)
513 if err != nil {
514 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
515 }
516 relDir, err := filepath.Rel(topDir, dir)
517 if err != nil {
518 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
519 }
520 // If there are ".." in the path, it's not in the source tree.
521 if strings.Contains(relDir, "..") {
522 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
523 }
524
525 configArgs := args[:]
526
527 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
528 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
529 targetNamePrefix := "MODULES-IN-"
530 if inList("GET-INSTALL-PATH", configArgs) {
531 targetNamePrefix = "GET-INSTALL-PATH-IN-"
532 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
533 }
534
Patrice Arruda13848222019-04-22 17:12:02 -0700535 var targets []string
536
537 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700538 case BUILD_MODULES:
539 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700540 case BUILD_MODULES_IN_A_DIRECTORY:
541 // If dir is the root source tree, all the modules are built of the source tree are built so
542 // no need to find the build file.
543 if topDir == dir {
544 break
545 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700546
Patrice Arruda13848222019-04-22 17:12:02 -0700547 buildFile := findBuildFile(ctx, relDir)
548 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700549 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700550 }
Patrice Arruda13848222019-04-22 17:12:02 -0700551 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
552 case BUILD_MODULES_IN_DIRECTORIES:
553 newConfigArgs, dirs := splitArgs(configArgs)
554 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700555 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700556 }
557
558 // Tidy only override all other specified targets.
559 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
560 if tidyOnly == "true" || tidyOnly == "1" {
561 configArgs = append(configArgs, "tidy_only")
562 } else {
563 configArgs = append(configArgs, targets...)
564 }
565
566 return configArgs
567}
568
569// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
570func convertToTarget(dir string, targetNamePrefix string) string {
571 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
572}
573
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700574// hasBuildFile returns true if dir contains an Android build file.
575func hasBuildFile(ctx Context, dir string) bool {
576 for _, buildFile := range buildFiles {
577 _, err := os.Stat(filepath.Join(dir, buildFile))
578 if err == nil {
579 return true
580 }
581 if !os.IsNotExist(err) {
582 ctx.Fatalf("Error retrieving the build file stats: %v", err)
583 }
584 }
585 return false
586}
587
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700588// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
589// in the current and any sub directory of dir. If a build file is not found, traverse the path
590// up by one directory and repeat again until either a build file is found or reached to the root
591// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
592// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700593func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700594 // If the string is empty or ".", assume it is top directory of the source tree.
595 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700596 return ""
597 }
598
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700599 found := false
600 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
601 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
602 if err != nil {
603 return err
604 }
605 if found {
606 return filepath.SkipDir
607 }
608 if info.IsDir() {
609 return nil
610 }
611 for _, buildFile := range buildFiles {
612 if info.Name() == buildFile {
613 found = true
614 return filepath.SkipDir
615 }
616 }
617 return nil
618 })
619 if err != nil {
620 ctx.Fatalf("Error finding Android build file: %v", err)
621 }
622
623 if found {
624 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700625 }
626 }
627
628 return ""
629}
630
631// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
632func splitArgs(args []string) (newArgs []string, dirs []string) {
633 specialArgs := map[string]bool{
634 "showcommands": true,
635 "snod": true,
636 "dist": true,
637 "checkbuild": true,
638 }
639
640 newArgs = []string{}
641 dirs = []string{}
642
643 for _, arg := range args {
644 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
645 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
646 newArgs = append(newArgs, arg)
647 continue
648 }
649
650 if _, ok := specialArgs[arg]; ok {
651 newArgs = append(newArgs, arg)
652 continue
653 }
654
655 dirs = append(dirs, arg)
656 }
657
658 return newArgs, dirs
659}
660
661// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
662// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
663// source root tree where the build action command was invoked. Each directory is validated if the
664// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700665func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700666 for _, dir := range dirs {
667 // The directory may have specified specific modules to build. ":" is the separator to separate
668 // the directory and the list of modules.
669 s := strings.Split(dir, ":")
670 l := len(s)
671 if l > 2 { // more than one ":" was specified.
672 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
673 }
674
675 dir = filepath.Join(relDir, s[0])
676 if _, err := os.Stat(dir); err != nil {
677 ctx.Fatalf("couldn't find directory %s", dir)
678 }
679
680 // Verify that if there are any targets specified after ":". Each target is separated by ",".
681 var newTargets []string
682 if l == 2 && s[1] != "" {
683 newTargets = strings.Split(s[1], ",")
684 if inList("", newTargets) {
685 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
686 }
687 }
688
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700689 // If there are specified targets to build in dir, an android build file must exist for the one
690 // shot build. For the non-targets case, find the appropriate build file and build all the
691 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700692 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700693 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700694 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
695 }
696 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700697 buildFile := findBuildFile(ctx, dir)
698 if buildFile == "" {
699 ctx.Fatalf("Build file not found for %s directory", dir)
700 }
701 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700702 }
703
Patrice Arruda13848222019-04-22 17:12:02 -0700704 targets = append(targets, newTargets...)
705 }
706
Dan Willemsence41e942019-07-29 23:39:30 -0700707 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700708}
709
Dan Willemsen9b587492017-07-10 22:13:00 -0700710func (c *configImpl) parseArgs(ctx Context, args []string) {
711 for i := 0; i < len(args); i++ {
712 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100713 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700714 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200715 } else if arg == "--empty-ninja-file" {
716 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100717 } else if arg == "--skip-ninja" {
718 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700719 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700720 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
721 // but it does run a Kati ninja file if the .kati_enabled marker file was created
722 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000723 c.skipConfig = true
724 c.skipKati = true
725 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100726 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000727 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100728 } else if arg == "--soong-only" {
729 c.skipKati = true
730 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200731 } else if arg == "--config-only" {
732 c.skipKati = true
733 c.skipKatiNinja = true
734 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700735 } else if arg == "--skip-config" {
736 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700737 } else if arg == "--skip-soong-tests" {
738 c.skipSoongTests = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500739 } else if arg == "--mk-metrics" {
740 c.reportMkMetrics = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400741 } else if arg == "--bazel-mode" {
742 c.bazelProdMode = true
743 } else if arg == "--bazel-mode-dev" {
744 c.bazelDevMode = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700745 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700746 parseArgNum := func(def int) int {
747 if len(arg) > 2 {
748 p, err := strconv.ParseUint(arg[2:], 10, 31)
749 if err != nil {
750 ctx.Fatalf("Failed to parse %q: %v", arg, err)
751 }
752 return int(p)
753 } else if i+1 < len(args) {
754 p, err := strconv.ParseUint(args[i+1], 10, 31)
755 if err == nil {
756 i++
757 return int(p)
758 }
759 }
760 return def
761 }
762
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700763 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700764 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700765 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700766 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700767 } else {
768 ctx.Fatalln("Unknown option:", arg)
769 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700770 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700771 if k == "OUT_DIR" {
772 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
773 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700774 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700775 } else if arg == "dist" {
776 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200777 } else if arg == "json-module-graph" {
778 c.jsonModuleGraph = true
779 } else if arg == "bp2build" {
780 c.bp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200781 } else if arg == "queryview" {
782 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200783 } else if arg == "soong_docs" {
784 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700785 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700786 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800787 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700788 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700789 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700790 }
791 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700792}
793
Dan Willemsened869522018-01-08 14:58:46 -0800794func (c *configImpl) configureLocale(ctx Context) {
795 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
796 output, err := cmd.Output()
797
798 var locales []string
799 if err == nil {
800 locales = strings.Split(string(output), "\n")
801 } else {
802 // If we're unable to list the locales, let's assume en_US.UTF-8
803 locales = []string{"en_US.UTF-8"}
804 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
805 }
806
807 // gettext uses LANGUAGE, which is passed directly through
808
809 // For LANG and LC_*, only preserve the evaluated version of
810 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800811 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800812 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800813 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800814 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800815 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800816 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800817 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800818 }
819
820 c.environ.UnsetWithPrefix("LC_")
821
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800822 if userLang != "" {
823 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800824 }
825
826 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
827 // for others)
828 if inList("C.UTF-8", locales) {
829 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500830 } else if inList("C.utf8", locales) {
831 // These normalize to the same thing
832 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800833 } else if inList("en_US.UTF-8", locales) {
834 c.environ.Set("LANG", "en_US.UTF-8")
835 } else if inList("en_US.utf8", locales) {
836 // These normalize to the same thing
837 c.environ.Set("LANG", "en_US.UTF-8")
838 } else {
839 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
840 }
841}
842
Dan Willemsen1e704462016-08-21 15:17:17 -0700843func (c *configImpl) Environment() *Environment {
844 return c.environ
845}
846
847func (c *configImpl) Arguments() []string {
848 return c.arguments
849}
850
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200851func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200852 if len(c.Arguments()) > 0 {
853 // Explicit targets requested that are not special targets like b2pbuild
854 // or the JSON module graph
855 return true
856 }
857
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200858 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200859 // Command line was empty, the default Ninja target is built
860 return true
861 }
862
Liz Kammer88677422021-12-15 15:03:19 -0500863 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
864 if c.Dist() && !c.Bp2Build() {
865 return true
866 }
867
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200868 // build.ninja doesn't need to be generated
869 return false
870}
871
Dan Willemsen1e704462016-08-21 15:17:17 -0700872func (c *configImpl) OutDir() string {
873 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700874 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700875 }
876 return "out"
877}
878
Dan Willemsen8a073a82017-02-04 17:30:44 -0800879func (c *configImpl) DistDir() string {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000880 if c.UseBazel() {
881 return c.riggedDistDirForBazel
882 } else {
883 return c.distDir
884 }
885}
886
887func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700888 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800889}
890
Dan Willemsen1e704462016-08-21 15:17:17 -0700891func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000892 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700893 return c.arguments
894 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700895 return c.ninjaArgs
896}
897
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500898func (c *configImpl) BazelOutDir() string {
899 return filepath.Join(c.OutDir(), "bazel")
900}
901
Dan Willemsen1e704462016-08-21 15:17:17 -0700902func (c *configImpl) SoongOutDir() string {
903 return filepath.Join(c.OutDir(), "soong")
904}
905
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200906func (c *configImpl) PrebuiltOS() string {
907 switch runtime.GOOS {
908 case "linux":
909 return "linux-x86"
910 case "darwin":
911 return "darwin-x86"
912 default:
913 panic("Unknown GOOS")
914 }
915}
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100916
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200917func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -0700918 if c.SkipKatiNinja() {
919 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
920 } else {
921 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
922 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200923}
924
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200925func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100926 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200927}
928
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200929func (c *configImpl) UsedEnvFile(tag string) string {
930 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
931}
932
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200933func (c *configImpl) Bp2BuildMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100934 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200935}
936
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200937func (c *configImpl) SoongDocsHtml() string {
938 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
939}
940
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200941func (c *configImpl) QueryviewMarkerFile() string {
942 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
943}
944
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200945func (c *configImpl) ModuleGraphFile() string {
946 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
947}
948
kgui67007242022-01-25 13:50:25 +0800949func (c *configImpl) ModuleActionsFile() string {
950 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
951}
952
Jeff Gastonefc1b412017-03-29 17:29:06 -0700953func (c *configImpl) TempDir() string {
954 return shared.TempDirForOutDir(c.SoongOutDir())
955}
956
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700957func (c *configImpl) FileListDir() string {
958 return filepath.Join(c.OutDir(), ".module_paths")
959}
960
Dan Willemsen1e704462016-08-21 15:17:17 -0700961func (c *configImpl) KatiSuffix() string {
962 if c.katiSuffix != "" {
963 return c.katiSuffix
964 }
965 panic("SetKatiSuffix has not been called")
966}
967
Colin Cross37193492017-11-16 17:55:00 -0800968// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
969// user is interested in additional checks at the expense of build time.
970func (c *configImpl) Checkbuild() bool {
971 return c.checkbuild
972}
973
Dan Willemsen8a073a82017-02-04 17:30:44 -0800974func (c *configImpl) Dist() bool {
975 return c.dist
976}
977
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200978func (c *configImpl) JsonModuleGraph() bool {
979 return c.jsonModuleGraph
980}
981
982func (c *configImpl) Bp2Build() bool {
983 return c.bp2build
984}
985
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200986func (c *configImpl) Queryview() bool {
987 return c.queryview
988}
989
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200990func (c *configImpl) SoongDocs() bool {
991 return c.soongDocs
992}
993
Dan Willemsen1e704462016-08-21 15:17:17 -0700994func (c *configImpl) IsVerbose() bool {
995 return c.verbose
996}
997
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000998func (c *configImpl) SkipKati() bool {
999 return c.skipKati
1000}
1001
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001002func (c *configImpl) SkipKatiNinja() bool {
1003 return c.skipKatiNinja
1004}
1005
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001006func (c *configImpl) SkipSoong() bool {
1007 return c.skipSoong
1008}
1009
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001010func (c *configImpl) SkipNinja() bool {
1011 return c.skipNinja
1012}
1013
Anton Hansson5a7861a2021-06-04 10:09:01 +01001014func (c *configImpl) SetSkipNinja(v bool) {
1015 c.skipNinja = v
1016}
1017
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001018func (c *configImpl) SkipConfig() bool {
1019 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001020}
1021
Dan Willemsen1e704462016-08-21 15:17:17 -07001022func (c *configImpl) TargetProduct() string {
1023 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1024 return v
1025 }
1026 panic("TARGET_PRODUCT is not defined")
1027}
1028
Dan Willemsen02781d52017-05-12 19:28:13 -07001029func (c *configImpl) TargetDevice() string {
1030 return c.targetDevice
1031}
1032
1033func (c *configImpl) SetTargetDevice(device string) {
1034 c.targetDevice = device
1035}
1036
1037func (c *configImpl) TargetBuildVariant() string {
1038 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1039 return v
1040 }
1041 panic("TARGET_BUILD_VARIANT is not defined")
1042}
1043
Dan Willemsen1e704462016-08-21 15:17:17 -07001044func (c *configImpl) KatiArgs() []string {
1045 return c.katiArgs
1046}
1047
1048func (c *configImpl) Parallel() int {
1049 return c.parallel
1050}
1051
Colin Cross8b8bec32019-11-15 13:18:43 -08001052func (c *configImpl) HighmemParallel() int {
1053 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1054 return i
1055 }
1056
1057 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1058 parallel := c.Parallel()
1059 if c.UseRemoteBuild() {
1060 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1061 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1062 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1063 // Return 1/16th of the size of the local pool, rounding up.
1064 return (parallel + 15) / 16
1065 } else if c.totalRAM == 0 {
1066 // Couldn't detect the total RAM, don't restrict highmem processes.
1067 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001068 } else if c.totalRAM <= 16*1024*1024*1024 {
1069 // Less than 16GB of ram, restrict to 1 highmem processes
1070 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001071 } else if c.totalRAM <= 32*1024*1024*1024 {
1072 // Less than 32GB of ram, restrict to 2 highmem processes
1073 return 2
1074 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1075 // If less than 8GB total RAM per process, reduce the number of highmem processes
1076 return p
1077 }
1078 // No restriction on highmem processes
1079 return parallel
1080}
1081
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001082func (c *configImpl) TotalRAM() uint64 {
1083 return c.totalRAM
1084}
1085
Kousik Kumarec478642020-09-21 13:39:24 -04001086// ForceUseGoma determines whether we should override Goma deprecation
1087// and use Goma for the current build or not.
1088func (c *configImpl) ForceUseGoma() bool {
1089 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1090 v = strings.TrimSpace(v)
1091 if v != "" && v != "false" {
1092 return true
1093 }
1094 }
1095 return false
1096}
1097
Dan Willemsen1e704462016-08-21 15:17:17 -07001098func (c *configImpl) UseGoma() bool {
1099 if v, ok := c.environ.Get("USE_GOMA"); ok {
1100 v = strings.TrimSpace(v)
1101 if v != "" && v != "false" {
1102 return true
1103 }
1104 }
1105 return false
1106}
1107
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001108func (c *configImpl) StartGoma() bool {
1109 if !c.UseGoma() {
1110 return false
1111 }
1112
1113 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1114 v = strings.TrimSpace(v)
1115 if v != "" && v != "false" {
1116 return false
1117 }
1118 }
1119 return true
1120}
1121
Ramy Medhatbbf25672019-07-17 12:30:04 +00001122func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001123 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001124 v = strings.TrimSpace(v)
1125 if v != "" && v != "false" {
1126 return true
1127 }
1128 }
1129 return false
1130}
1131
Chris Parsonsef615e52022-08-18 22:04:11 -04001132// TODO(b/243077098): Remove UseBazel.
Patrice Arruda0c1c4562020-11-11 13:01:25 -08001133func (c *configImpl) UseBazel() bool {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001134 return c.useBazel
Patrice Arruda0c1c4562020-11-11 13:01:25 -08001135}
1136
Chris Parsonsef615e52022-08-18 22:04:11 -04001137func (c *configImpl) BazelBuildEnabled() bool {
1138 return c.bazelProdMode || c.bazelDevMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001139}
1140
Ramy Medhatbbf25672019-07-17 12:30:04 +00001141func (c *configImpl) StartRBE() bool {
1142 if !c.UseRBE() {
1143 return false
1144 }
1145
1146 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1147 v = strings.TrimSpace(v)
1148 if v != "" && v != "false" {
1149 return false
1150 }
1151 }
1152 return true
1153}
1154
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001155func (c *configImpl) rbeProxyLogsDir() string {
1156 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001157 if v, ok := c.environ.Get(f); ok {
1158 return v
1159 }
1160 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001161 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1162 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001163}
1164
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001165func (c *configImpl) shouldCleanupRBELogsDir() bool {
1166 // Perform a log directory cleanup only when the log directory
1167 // is auto created by the build rather than user-specified.
1168 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1169 if _, ok := c.environ.Get(f); ok {
1170 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001171 }
1172 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001173 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001174}
1175
1176func (c *configImpl) rbeExecRoot() string {
1177 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1178 if v, ok := c.environ.Get(f); ok {
1179 return v
1180 }
1181 }
1182 wd, err := os.Getwd()
1183 if err != nil {
1184 return ""
1185 }
1186 return wd
1187}
1188
1189func (c *configImpl) rbeDir() string {
1190 if v, ok := c.environ.Get("RBE_DIR"); ok {
1191 return v
1192 }
1193 return "prebuilts/remoteexecution-client/live/"
1194}
1195
1196func (c *configImpl) rbeReproxy() string {
1197 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1198 if v, ok := c.environ.Get(f); ok {
1199 return v
1200 }
1201 }
1202 return filepath.Join(c.rbeDir(), "reproxy")
1203}
1204
1205func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001206 credFlags := []string{
1207 "use_application_default_credentials",
1208 "use_gce_credentials",
1209 "credential_file",
1210 "use_google_prod_creds",
1211 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001212 for _, cf := range credFlags {
1213 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1214 if v, ok := c.environ.Get(f); ok {
1215 v = strings.TrimSpace(v)
1216 if v != "" && v != "false" && v != "0" {
1217 return "RBE_" + cf, v
1218 }
1219 }
1220 }
1221 }
1222 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001223}
1224
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001225func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1226 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1227 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1228
1229 name := filepath.Join(dir, base)
1230 if len(name) < maxNameLen {
1231 return name, nil
1232 }
1233
1234 name = filepath.Join("/tmp", base)
1235 if len(name) < maxNameLen {
1236 return name, nil
1237 }
1238
1239 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1240}
1241
Kousik Kumar7bc78192022-04-27 14:52:56 -04001242// IsGooglerEnvironment returns true if the current build is running
1243// on a Google developer machine and false otherwise.
1244func (c *configImpl) IsGooglerEnvironment() bool {
1245 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1246 if v, ok := c.environ.Get(cf); ok {
1247 return v == "googler"
1248 }
1249 return false
1250}
1251
1252// GoogleProdCredsExist determine whether credentials exist on the
1253// Googler machine to use remote execution.
1254func (c *configImpl) GoogleProdCredsExist() bool {
1255 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1256 return false
1257 }
1258 return true
1259}
1260
1261// UseRemoteBuild indicates whether to use a remote build acceleration system
1262// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001263func (c *configImpl) UseRemoteBuild() bool {
1264 return c.UseGoma() || c.UseRBE()
1265}
1266
Kousik Kumar7bc78192022-04-27 14:52:56 -04001267// StubbyExists checks whether the stubby binary exists on the machine running
1268// the build.
1269func (c *configImpl) StubbyExists() bool {
1270 if _, err := exec.LookPath("stubby"); err != nil {
1271 return false
1272 }
1273 return true
1274}
1275
Dan Willemsen1e704462016-08-21 15:17:17 -07001276// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001277// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001278// still limited by Parallel()
1279func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001280 if !c.UseRemoteBuild() {
1281 return 0
1282 }
1283 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1284 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001285 }
1286 return 500
1287}
1288
1289func (c *configImpl) SetKatiArgs(args []string) {
1290 c.katiArgs = args
1291}
1292
1293func (c *configImpl) SetNinjaArgs(args []string) {
1294 c.ninjaArgs = args
1295}
1296
1297func (c *configImpl) SetKatiSuffix(suffix string) {
1298 c.katiSuffix = suffix
1299}
1300
Dan Willemsene0879fc2017-08-04 15:06:27 -07001301func (c *configImpl) LastKatiSuffixFile() string {
1302 return filepath.Join(c.OutDir(), "last_kati_suffix")
1303}
1304
1305func (c *configImpl) HasKatiSuffix() bool {
1306 return c.katiSuffix != ""
1307}
1308
Dan Willemsen1e704462016-08-21 15:17:17 -07001309func (c *configImpl) KatiEnvFile() string {
1310 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1311}
1312
Dan Willemsen29971232018-09-26 14:58:30 -07001313func (c *configImpl) KatiBuildNinjaFile() string {
1314 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001315}
1316
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001317func (c *configImpl) KatiPackageNinjaFile() string {
1318 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1319}
1320
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001321func (c *configImpl) SoongVarsFile() string {
1322 return filepath.Join(c.SoongOutDir(), "soong.variables")
1323}
1324
Dan Willemsen1e704462016-08-21 15:17:17 -07001325func (c *configImpl) SoongNinjaFile() string {
1326 return filepath.Join(c.SoongOutDir(), "build.ninja")
1327}
1328
1329func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001330 if c.katiSuffix == "" {
1331 return filepath.Join(c.OutDir(), "combined.ninja")
1332 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001333 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1334}
1335
1336func (c *configImpl) SoongAndroidMk() string {
1337 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1338}
1339
1340func (c *configImpl) SoongMakeVarsMk() string {
1341 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1342}
1343
Dan Willemsenf052f782017-05-18 15:29:04 -07001344func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001345 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001346}
1347
Dan Willemsen02781d52017-05-12 19:28:13 -07001348func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001349 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1350}
1351
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001352func (c *configImpl) KatiPackageMkDir() string {
1353 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1354}
1355
Dan Willemsenf052f782017-05-18 15:29:04 -07001356func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001357 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001358}
1359
1360func (c *configImpl) HostOut() string {
1361 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1362}
1363
1364// This probably needs to be multi-valued, so not exporting it for now
1365func (c *configImpl) hostCrossOut() string {
1366 if runtime.GOOS == "linux" {
1367 return filepath.Join(c.hostOutRoot(), "windows-x86")
1368 } else {
1369 return ""
1370 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001371}
1372
Dan Willemsen1e704462016-08-21 15:17:17 -07001373func (c *configImpl) HostPrebuiltTag() string {
1374 if runtime.GOOS == "linux" {
1375 return "linux-x86"
1376 } else if runtime.GOOS == "darwin" {
1377 return "darwin-x86"
1378 } else {
1379 panic("Unsupported OS")
1380 }
1381}
Dan Willemsenf173d592017-04-27 14:28:00 -07001382
Dan Willemsen8122bd52017-10-12 20:20:41 -07001383func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001384 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1385 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001386 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1387 if _, err := os.Stat(asan); err == nil {
1388 return asan
1389 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001390 }
1391 }
1392 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1393}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001394
1395func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1396 c.brokenDupRules = val
1397}
1398
1399func (c *configImpl) BuildBrokenDupRules() bool {
1400 return c.brokenDupRules
1401}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001402
Dan Willemsen25e6f092019-04-09 10:22:43 -07001403func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1404 c.brokenUsesNetwork = val
1405}
1406
1407func (c *configImpl) BuildBrokenUsesNetwork() bool {
1408 return c.brokenUsesNetwork
1409}
1410
Dan Willemsene3336352020-01-02 19:10:38 -08001411func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1412 c.brokenNinjaEnvVars = val
1413}
1414
1415func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1416 return c.brokenNinjaEnvVars
1417}
1418
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001419func (c *configImpl) SetTargetDeviceDir(dir string) {
1420 c.targetDeviceDir = dir
1421}
1422
1423func (c *configImpl) TargetDeviceDir() string {
1424 return c.targetDeviceDir
1425}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001426
Patrice Arruda219eef32020-06-01 17:29:30 +00001427func (c *configImpl) BuildDateTime() string {
1428 return c.buildDateTime
1429}
1430
1431func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001432 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001433}
Patrice Arruda83842d72020-12-08 19:42:08 +00001434
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001435// LogsDir returns the absolute path to the logs directory where build log and
1436// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001437// directory. If the argument dist is specified, the logs directory
1438// is <dist_dir>/logs.
1439func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001440 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001441 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001442 // 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 -05001443 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001444 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001445 absDir, err := filepath.Abs(dir)
1446 if err != nil {
1447 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1448 os.Exit(1)
1449 }
1450 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001451}
1452
1453// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1454// where the bazel profiles are located.
1455func (c *configImpl) BazelMetricsDir() string {
1456 return filepath.Join(c.LogsDir(), "bazel_metrics")
1457}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001458
Chris Parsons53f68ae2022-03-03 12:01:40 -05001459// MkFileMetrics returns the file path for make-related metrics.
1460func (c *configImpl) MkMetrics() string {
1461 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1462}
1463
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001464func (c *configImpl) SetEmptyNinjaFile(v bool) {
1465 c.emptyNinjaFile = v
1466}
1467
1468func (c *configImpl) EmptyNinjaFile() bool {
1469 return c.emptyNinjaFile
1470}
Yu Liu6e13b402021-07-27 14:29:06 -07001471
1472func GetMetricsUploader(topDir string, env *Environment) string {
1473 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1474 metricsUploader := filepath.Join(topDir, p)
1475 if _, err := os.Stat(metricsUploader); err == nil {
1476 return metricsUploader
1477 }
1478 }
1479
1480 return ""
1481}