blob: b3c4405c9a48860a0011eb162089d58507242693 [file] [log] [blame]
Dan Willemsen1e704462016-08-21 15:17:17 -07001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package build
16
17import (
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050018 "context"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050019 "encoding/json"
Ramy Medhat0fc67eb2020-08-12 01:26:23 -040020 "fmt"
Kousik Kumar3ff037e2022-01-25 22:11:01 -050021 "io/ioutil"
Kousik Kumar4c180ad2022-05-27 07:48:37 -040022 "math/rand"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080023 "os"
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050024 "os/exec"
Dan Willemsen1e704462016-08-21 15:17:17 -070025 "path/filepath"
26 "runtime"
27 "strconv"
28 "strings"
Kousik Kumar4c180ad2022-05-27 07:48:37 -040029 "syscall"
Nan Zhang2e6a4ff2018-02-14 13:27:26 -080030 "time"
Jeff Gastonefc1b412017-03-29 17:29:06 -070031
32 "android/soong/shared"
Kousik Kumarec478642020-09-21 13:39:24 -040033
Dan Willemsen4591b642021-05-24 14:24:12 -070034 "google.golang.org/protobuf/proto"
Patrice Arruda96850362020-08-11 20:41:11 +000035
36 smpb "android/soong/ui/metrics/metrics_proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070037)
38
Kousik Kumar3ff037e2022-01-25 22:11:01 -050039const (
Chris Parsons53f68ae2022-03-03 12:01:40 -050040 envConfigDir = "vendor/google/tools/soong_config"
41 jsonSuffix = "json"
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050042
Chris Parsons53f68ae2022-03-03 12:01:40 -050043 configFetcher = "vendor/google/tools/soong/expconfigfetcher"
Kousik Kumar84bd5bf2022-01-26 23:32:22 -050044 envConfigFetchTimeout = 10 * time.Second
Kousik Kumar3ff037e2022-01-25 22:11:01 -050045)
46
Kousik Kumar4c180ad2022-05-27 07:48:37 -040047var (
48 rbeRandPrefix int
49)
50
51func init() {
52 rand.Seed(time.Now().UnixNano())
53 rbeRandPrefix = rand.Intn(1000)
54}
55
Dan Willemsen1e704462016-08-21 15:17:17 -070056type Config struct{ *configImpl }
57
58type configImpl struct {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020059 // Some targets that are implemented in soong_build
60 // (bp2build, json-module-graph) are not here and have their own bits below.
Colin Cross28f527c2019-11-26 16:19:04 -080061 arguments []string
62 goma bool
63 environ *Environment
64 distDir string
65 buildDateTime string
Dan Willemsen1e704462016-08-21 15:17:17 -070066
67 // From the arguments
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020068 parallel int
69 keepGoing int
70 verbose bool
71 checkbuild bool
72 dist bool
73 jsonModuleGraph bool
Spandan Das5af0bd32022-09-28 20:43:08 +000074 apiBp2build bool // Generate BUILD files for Soong modules that contribute APIs
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020075 bp2build bool
Lukacs T. Berki3a821692021-09-06 17:08:02 +020076 queryview bool
Chris Parsons53f68ae2022-03-03 12:01:40 -050077 reportMkMetrics bool // Collect and report mk2bp migration progress metrics.
Lukacs T. Berkic6012f32021-09-06 18:31:46 +020078 soongDocs bool
Lukacs T. Berkia1b93722021-09-02 17:23:06 +020079 skipConfig bool
80 skipKati bool
81 skipKatiNinja bool
82 skipSoong bool
83 skipNinja bool
84 skipSoongTests bool
Spandan Das394aa322022-11-03 17:02:10 +000085 searchApiDir bool // Scan the Android.bp files generated in out/api_surfaces
Dan Willemsen1e704462016-08-21 15:17:17 -070086
87 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070088 katiArgs []string
89 ninjaArgs []string
90 katiSuffix string
91 targetDevice string
92 targetDeviceDir string
Spandan Dasa3639e62021-05-25 19:14:02 +000093 sandboxConfig *SandboxConfig
Dan Willemsen3d60b112018-04-04 22:25:56 -070094
Dan Willemsen2bb82d02019-12-27 09:35:42 -080095 // Autodetected
96 totalRAM uint64
97
Dan Willemsene3336352020-01-02 19:10:38 -080098 brokenDupRules bool
99 brokenUsesNetwork bool
100 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -0700101
102 pathReplaced bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000103
MarkDacekb78465d2022-10-18 20:10:16 +0000104 bazelProdMode bool
105 bazelDevMode bool
106 bazelStagingMode bool
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000107
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700108 // Set by multiproduct_kati
109 emptyNinjaFile bool
Yu Liu6e13b402021-07-27 14:29:06 -0700110
111 metricsUploader string
Dan Willemsen1e704462016-08-21 15:17:17 -0700112}
113
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800114const srcDirFileCheck = "build/soong/root.bp"
115
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700116var buildFiles = []string{"Android.mk", "Android.bp"}
117
Patrice Arruda13848222019-04-22 17:12:02 -0700118type BuildAction uint
119
120const (
121 // Builds all of the modules and their dependencies of a specified directory, relative to the root
122 // directory of the source tree.
123 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
124
125 // Builds all of the modules and their dependencies of a list of specified directories. All specified
126 // directories are relative to the root directory of the source tree.
127 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -0700128
129 // Build a list of specified modules. If none was specified, simply build the whole source tree.
130 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -0700131)
132
133// checkTopDir validates that the current directory is at the root directory of the source tree.
134func checkTopDir(ctx Context) {
135 if _, err := os.Stat(srcDirFileCheck); err != nil {
136 if os.IsNotExist(err) {
137 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
138 }
139 ctx.Fatalln("Error verifying tree state:", err)
140 }
141}
142
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500143// fetchEnvConfig optionally fetches environment config from an
144// experiments system to control Soong features dynamically.
145func fetchEnvConfig(ctx Context, config *configImpl, envConfigName string) error {
David Goldsmith62243a32022-04-08 13:42:04 +0000146 configName := envConfigName + "." + jsonSuffix
Kousik Kumarc75e1292022-07-07 02:20:51 +0000147 expConfigFetcher := &smpb.ExpConfigFetcher{Filename: &configName}
David Goldsmith62243a32022-04-08 13:42:04 +0000148 defer func() {
149 ctx.Metrics.ExpConfigFetcher(expConfigFetcher)
150 }()
Kousik Kumarc75e1292022-07-07 02:20:51 +0000151 if !config.GoogleProdCredsExist() {
152 status := smpb.ExpConfigFetcher_MISSING_GCERT
153 expConfigFetcher.Status = &status
154 return nil
155 }
David Goldsmith62243a32022-04-08 13:42:04 +0000156
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500157 s, err := os.Stat(configFetcher)
158 if err != nil {
159 if os.IsNotExist(err) {
160 return nil
161 }
162 return err
163 }
164 if s.Mode()&0111 == 0 {
David Goldsmith62243a32022-04-08 13:42:04 +0000165 status := smpb.ExpConfigFetcher_ERROR
166 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500167 return fmt.Errorf("configuration fetcher binary %v is not executable: %v", configFetcher, s.Mode())
168 }
169
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500170 tCtx, cancel := context.WithTimeout(ctx, envConfigFetchTimeout)
171 defer cancel()
David Goldsmith62243a32022-04-08 13:42:04 +0000172 fetchStart := time.Now()
173 cmd := exec.CommandContext(tCtx, configFetcher, "-output_config_dir", config.OutDir(),
174 "-output_config_name", configName)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500175 if err := cmd.Start(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000176 status := smpb.ExpConfigFetcher_ERROR
177 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500178 return err
179 }
180
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500181 if err := cmd.Wait(); err != nil {
David Goldsmith62243a32022-04-08 13:42:04 +0000182 status := smpb.ExpConfigFetcher_ERROR
183 expConfigFetcher.Status = &status
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500184 return err
185 }
David Goldsmith62243a32022-04-08 13:42:04 +0000186 fetchEnd := time.Now()
187 expConfigFetcher.Micros = proto.Uint64(uint64(fetchEnd.Sub(fetchStart).Microseconds()))
188 outConfigFilePath := filepath.Join(config.OutDir(), configName)
189 expConfigFetcher.Filename = proto.String(outConfigFilePath)
190 if _, err := os.Stat(outConfigFilePath); err == nil {
191 status := smpb.ExpConfigFetcher_CONFIG
192 expConfigFetcher.Status = &status
193 } else {
194 status := smpb.ExpConfigFetcher_NO_CONFIG
195 expConfigFetcher.Status = &status
196 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500197 return nil
198}
199
200func loadEnvConfig(ctx Context, config *configImpl) error {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500201 bc := os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG")
202 if bc == "" {
203 return nil
204 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500205
206 if err := fetchEnvConfig(ctx, config, bc); err != nil {
Kousik Kumar595fb1c2022-06-24 16:49:52 +0000207 ctx.Verbosef("Failed to fetch config file: %v\n", err)
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500208 }
209
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500210 configDirs := []string{
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500211 config.OutDir(),
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500212 os.Getenv("ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR"),
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500213 envConfigDir,
214 }
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500215 for _, dir := range configDirs {
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500216 cfgFile := filepath.Join(os.Getenv("TOP"), dir, fmt.Sprintf("%s.%s", bc, jsonSuffix))
217 envVarsJSON, err := ioutil.ReadFile(cfgFile)
218 if err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500219 continue
220 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500221 ctx.Verbosef("Loading config file %v\n", cfgFile)
222 var envVars map[string]map[string]string
223 if err := json.Unmarshal(envVarsJSON, &envVars); err != nil {
224 fmt.Fprintf(os.Stderr, "Env vars config file %s did not parse correctly: %s", cfgFile, err.Error())
225 continue
226 }
227 for k, v := range envVars["env"] {
228 if os.Getenv(k) != "" {
229 continue
230 }
231 config.environ.Set(k, v)
232 }
233 ctx.Verbosef("Finished loading config file %v\n", cfgFile)
234 break
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500235 }
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500236
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500237 return nil
238}
239
Chris Parsonsb6e96902022-10-31 20:08:45 -0400240func defaultBazelProdMode(cfg *configImpl) bool {
241 // Envirnoment flag to disable Bazel for users which experience
242 // broken bazel-handled builds, or significant performance regressions.
243 if cfg.IsBazelMixedBuildForceDisabled() {
244 return false
245 }
246 // Darwin-host builds are currently untested with Bazel.
247 if runtime.GOOS == "darwin" {
248 return false
249 }
Chris Parsons035e03a2022-11-01 14:25:45 -0400250 return true
Chris Parsonsb6e96902022-10-31 20:08:45 -0400251}
252
Dan Willemsen1e704462016-08-21 15:17:17 -0700253func NewConfig(ctx Context, args ...string) Config {
254 ret := &configImpl{
Spandan Dasa3639e62021-05-25 19:14:02 +0000255 environ: OsEnvironment(),
256 sandboxConfig: &SandboxConfig{},
Dan Willemsen1e704462016-08-21 15:17:17 -0700257 }
258
Patrice Arruda90109172020-07-28 18:07:27 +0000259 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -0700260 ret.parallel = runtime.NumCPU() + 2
261 ret.keepGoing = 1
262
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800263 ret.totalRAM = detectTotalRAM(ctx)
264
Dan Willemsen9b587492017-07-10 22:13:00 -0700265 ret.parseArgs(ctx, args)
266
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800267 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700268 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
269 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
270 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800271 outDir := "out"
272 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
273 if wd, err := os.Getwd(); err != nil {
274 ctx.Fatalln("Failed to get working directory:", err)
275 } else {
276 outDir = filepath.Join(baseDir, filepath.Base(wd))
277 }
278 }
279 ret.environ.Set("OUT_DIR", outDir)
280 }
281
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500282 // loadEnvConfig needs to know what the OUT_DIR is, so it should
283 // be called after we determine the appropriate out directory.
Kousik Kumar84bd5bf2022-01-26 23:32:22 -0500284 if err := loadEnvConfig(ctx, ret); err != nil {
Kousik Kumar3ff037e2022-01-25 22:11:01 -0500285 ctx.Fatalln("Failed to parse env config files: %v", err)
286 }
287
Dan Willemsen2d31a442018-10-20 21:33:41 -0700288 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
289 ret.distDir = filepath.Clean(distDir)
290 } else {
291 ret.distDir = filepath.Join(ret.OutDir(), "dist")
292 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700293
Spandan Das05063612021-06-25 01:39:04 +0000294 if srcDirIsWritable, ok := ret.environ.Get("BUILD_BROKEN_SRC_DIR_IS_WRITABLE"); ok {
295 ret.sandboxConfig.SetSrcDirIsRO(srcDirIsWritable == "false")
296 }
297
Dan Willemsen1e704462016-08-21 15:17:17 -0700298 ret.environ.Unset(
299 // We're already using it
300 "USE_SOONG_UI",
301
302 // We should never use GOROOT/GOPATH from the shell environment
303 "GOROOT",
304 "GOPATH",
305
306 // These should only come from Soong, not the environment.
307 "CLANG",
308 "CLANG_CXX",
309 "CCC_CC",
310 "CCC_CXX",
311
312 // Used by the goma compiler wrapper, but should only be set by
313 // gomacc
314 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800315
316 // We handle this above
317 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700318
Dan Willemsen2d31a442018-10-20 21:33:41 -0700319 // This is handled above too, and set for individual commands later
320 "DIST_DIR",
321
Dan Willemsen68a09852017-04-18 13:56:57 -0700322 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000323 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700324 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700325 "DISPLAY",
326 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700327 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700328 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700329
330 // Drop make flags
331 "MAKEFLAGS",
332 "MAKELEVEL",
333 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700334
335 // Set in envsetup.sh, reset in makefiles
336 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700337
338 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
339 "ANDROID_BUILD_TOP",
340 "ANDROID_HOST_OUT",
341 "ANDROID_PRODUCT_OUT",
342 "ANDROID_HOST_OUT_TESTCASES",
343 "ANDROID_TARGET_OUT_TESTCASES",
344 "ANDROID_TOOLCHAIN",
345 "ANDROID_TOOLCHAIN_2ND_ARCH",
346 "ANDROID_DEV_SCRIPTS",
347 "ANDROID_EMULATOR_PREBUILTS",
348 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsen1e704462016-08-21 15:17:17 -0700349 )
350
Kousik Kumarb328f6d2020-10-19 01:45:46 -0400351 if ret.UseGoma() || ret.ForceUseGoma() {
352 ctx.Println("Goma for Android has been deprecated and replaced with RBE. See go/rbe_for_android for instructions on how to use RBE.")
353 ctx.Fatalln("USE_GOMA / FORCE_USE_GOMA flag is no longer supported.")
Kousik Kumarec478642020-09-21 13:39:24 -0400354 }
355
Dan Willemsen1e704462016-08-21 15:17:17 -0700356 // Tell python not to spam the source tree with .pyc files.
357 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
358
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400359 tmpDir := absPath(ctx, ret.TempDir())
360 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800361
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700362 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
363 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
364 "llvm-binutils-stable/llvm-symbolizer")
365 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
366
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800367 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700368 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800369
Yu Liu6e13b402021-07-27 14:29:06 -0700370 srcDir := absPath(ctx, ".")
371 if strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700372 ctx.Println("You are building in a directory whose absolute path contains a space character:")
373 ctx.Println()
374 ctx.Printf("%q\n", srcDir)
375 ctx.Println()
376 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700377 }
378
Yu Liu6e13b402021-07-27 14:29:06 -0700379 ret.metricsUploader = GetMetricsUploader(srcDir, ret.environ)
380
Dan Willemsendb8457c2017-05-12 16:38:17 -0700381 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700382 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
383 ctx.Println()
384 ctx.Printf("%q\n", outDir)
385 ctx.Println()
386 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700387 }
388
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000389 if distDir := ret.RealDistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700390 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
391 ctx.Println()
392 ctx.Printf("%q\n", distDir)
393 ctx.Println()
394 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700395 }
396
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700397 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000398 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
399 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100400 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Colin Cross59c1e6a2022-03-04 13:37:19 -0800401 java17Home := filepath.Join("prebuilts/jdk/jdk17", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700402 javaHome := func() string {
403 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
404 return override
405 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000406 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
407 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 +0100408 }
Sorin Basca7e094b32022-10-05 08:20:12 +0000409 if toolchain17, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN"); ok && toolchain17 != "true" {
410 ctx.Fatalln("The environment variable EXPERIMENTAL_USE_OPENJDK17_TOOLCHAIN is no longer supported. An OpenJDK 17 toolchain is now the global default.")
411 }
412 return java17Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700413 }()
414 absJavaHome := absPath(ctx, javaHome)
415
Dan Willemsened869522018-01-08 14:58:46 -0800416 ret.configureLocale(ctx)
417
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700418 newPath := []string{filepath.Join(absJavaHome, "bin")}
419 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
420 newPath = append(newPath, path)
421 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100422
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700423 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
424 ret.environ.Set("JAVA_HOME", absJavaHome)
425 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000426 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
427 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100428 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700429 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
430
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800431 outDir := ret.OutDir()
432 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800433 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800434 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800435 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800436 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800437 }
Colin Cross28f527c2019-11-26 16:19:04 -0800438
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800439 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
440
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400441 if ret.UseRBE() {
Ramy Medhat0fc67eb2020-08-12 01:26:23 -0400442 for k, v := range getRBEVars(ctx, Config{ret}) {
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400443 ret.environ.Set(k, v)
444 }
445 }
446
Patrice Arruda83842d72020-12-08 19:42:08 +0000447 bpd := ret.BazelMetricsDir()
Patrice Arrudaaf880da2020-11-13 08:41:26 -0800448 if err := os.RemoveAll(bpd); err != nil {
449 ctx.Fatalf("Unable to remove bazel profile directory %q: %v", bpd, err)
450 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000451
Patrice Arruda96850362020-08-11 20:41:11 +0000452 c := Config{ret}
453 storeConfigMetrics(ctx, c)
454 return c
Dan Willemsen9b587492017-07-10 22:13:00 -0700455}
456
Patrice Arruda13848222019-04-22 17:12:02 -0700457// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
458// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700459func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
460 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700461}
462
Patrice Arruda96850362020-08-11 20:41:11 +0000463// storeConfigMetrics selects a set of configuration information and store in
464// the metrics system for further analysis.
465func storeConfigMetrics(ctx Context, config Config) {
466 if ctx.Metrics == nil {
467 return
468 }
469
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400470 ctx.Metrics.BuildConfig(buildConfig(config))
Patrice Arruda3edfd482020-10-13 23:58:41 +0000471
472 s := &smpb.SystemResourceInfo{
473 TotalPhysicalMemory: proto.Uint64(config.TotalRAM()),
474 AvailableCpus: proto.Int32(int32(runtime.NumCPU())),
475 }
476 ctx.Metrics.SystemResourceInfo(s)
Patrice Arruda96850362020-08-11 20:41:11 +0000477}
478
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400479func buildConfig(config Config) *smpb.BuildConfig {
Yu Liue737a992021-10-04 13:21:41 -0700480 c := &smpb.BuildConfig{
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -0400481 ForceUseGoma: proto.Bool(config.ForceUseGoma()),
482 UseGoma: proto.Bool(config.UseGoma()),
483 UseRbe: proto.Bool(config.UseRBE()),
484 BazelMixedBuild: proto.Bool(config.BazelBuildEnabled()),
485 ForceDisableBazelMixedBuild: proto.Bool(config.IsBazelMixedBuildForceDisabled()),
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400486 }
Yu Liue737a992021-10-04 13:21:41 -0700487 c.Targets = append(c.Targets, config.arguments...)
488
489 return c
Liz Kammerca9cb2e2021-07-14 15:29:57 -0400490}
491
Patrice Arruda13848222019-04-22 17:12:02 -0700492// getConfigArgs processes the command arguments based on the build action and creates a set of new
493// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700494func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700495 // The next block of code verifies that the current directory is the root directory of the source
496 // tree. It then finds the relative path of dir based on the root directory of the source tree
497 // and verify that dir is inside of the source tree.
498 checkTopDir(ctx)
499 topDir, err := os.Getwd()
500 if err != nil {
501 ctx.Fatalf("Error retrieving top directory: %v", err)
502 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700503 dir, err = filepath.EvalSymlinks(dir)
504 if err != nil {
505 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
506 }
Patrice Arruda13848222019-04-22 17:12:02 -0700507 dir, err = filepath.Abs(dir)
508 if err != nil {
509 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
510 }
511 relDir, err := filepath.Rel(topDir, dir)
512 if err != nil {
513 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
514 }
515 // If there are ".." in the path, it's not in the source tree.
516 if strings.Contains(relDir, "..") {
517 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
518 }
519
520 configArgs := args[:]
521
522 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
523 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
524 targetNamePrefix := "MODULES-IN-"
525 if inList("GET-INSTALL-PATH", configArgs) {
526 targetNamePrefix = "GET-INSTALL-PATH-IN-"
527 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
528 }
529
Patrice Arruda13848222019-04-22 17:12:02 -0700530 var targets []string
531
532 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700533 case BUILD_MODULES:
534 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700535 case BUILD_MODULES_IN_A_DIRECTORY:
536 // If dir is the root source tree, all the modules are built of the source tree are built so
537 // no need to find the build file.
538 if topDir == dir {
539 break
540 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700541
Patrice Arruda13848222019-04-22 17:12:02 -0700542 buildFile := findBuildFile(ctx, relDir)
543 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700544 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700545 }
Patrice Arruda13848222019-04-22 17:12:02 -0700546 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
547 case BUILD_MODULES_IN_DIRECTORIES:
548 newConfigArgs, dirs := splitArgs(configArgs)
549 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700550 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700551 }
552
553 // Tidy only override all other specified targets.
554 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
555 if tidyOnly == "true" || tidyOnly == "1" {
556 configArgs = append(configArgs, "tidy_only")
557 } else {
558 configArgs = append(configArgs, targets...)
559 }
560
561 return configArgs
562}
563
564// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
565func convertToTarget(dir string, targetNamePrefix string) string {
566 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
567}
568
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700569// hasBuildFile returns true if dir contains an Android build file.
570func hasBuildFile(ctx Context, dir string) bool {
571 for _, buildFile := range buildFiles {
572 _, err := os.Stat(filepath.Join(dir, buildFile))
573 if err == nil {
574 return true
575 }
576 if !os.IsNotExist(err) {
577 ctx.Fatalf("Error retrieving the build file stats: %v", err)
578 }
579 }
580 return false
581}
582
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700583// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
584// in the current and any sub directory of dir. If a build file is not found, traverse the path
585// up by one directory and repeat again until either a build file is found or reached to the root
586// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
587// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700588func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700589 // If the string is empty or ".", assume it is top directory of the source tree.
590 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700591 return ""
592 }
593
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700594 found := false
595 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
596 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
597 if err != nil {
598 return err
599 }
600 if found {
601 return filepath.SkipDir
602 }
603 if info.IsDir() {
604 return nil
605 }
606 for _, buildFile := range buildFiles {
607 if info.Name() == buildFile {
608 found = true
609 return filepath.SkipDir
610 }
611 }
612 return nil
613 })
614 if err != nil {
615 ctx.Fatalf("Error finding Android build file: %v", err)
616 }
617
618 if found {
619 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700620 }
621 }
622
623 return ""
624}
625
626// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
627func splitArgs(args []string) (newArgs []string, dirs []string) {
628 specialArgs := map[string]bool{
629 "showcommands": true,
630 "snod": true,
631 "dist": true,
632 "checkbuild": true,
633 }
634
635 newArgs = []string{}
636 dirs = []string{}
637
638 for _, arg := range args {
639 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
640 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
641 newArgs = append(newArgs, arg)
642 continue
643 }
644
645 if _, ok := specialArgs[arg]; ok {
646 newArgs = append(newArgs, arg)
647 continue
648 }
649
650 dirs = append(dirs, arg)
651 }
652
653 return newArgs, dirs
654}
655
656// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
657// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
658// source root tree where the build action command was invoked. Each directory is validated if the
659// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700660func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700661 for _, dir := range dirs {
662 // The directory may have specified specific modules to build. ":" is the separator to separate
663 // the directory and the list of modules.
664 s := strings.Split(dir, ":")
665 l := len(s)
666 if l > 2 { // more than one ":" was specified.
667 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
668 }
669
670 dir = filepath.Join(relDir, s[0])
671 if _, err := os.Stat(dir); err != nil {
672 ctx.Fatalf("couldn't find directory %s", dir)
673 }
674
675 // Verify that if there are any targets specified after ":". Each target is separated by ",".
676 var newTargets []string
677 if l == 2 && s[1] != "" {
678 newTargets = strings.Split(s[1], ",")
679 if inList("", newTargets) {
680 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
681 }
682 }
683
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700684 // If there are specified targets to build in dir, an android build file must exist for the one
685 // shot build. For the non-targets case, find the appropriate build file and build all the
686 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700687 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700688 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700689 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
690 }
691 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700692 buildFile := findBuildFile(ctx, dir)
693 if buildFile == "" {
694 ctx.Fatalf("Build file not found for %s directory", dir)
695 }
696 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700697 }
698
Patrice Arruda13848222019-04-22 17:12:02 -0700699 targets = append(targets, newTargets...)
700 }
701
Dan Willemsence41e942019-07-29 23:39:30 -0700702 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700703}
704
Dan Willemsen9b587492017-07-10 22:13:00 -0700705func (c *configImpl) parseArgs(ctx Context, args []string) {
706 for i := 0; i < len(args); i++ {
707 arg := strings.TrimSpace(args[i])
Anton Hansson5a7861a2021-06-04 10:09:01 +0100708 if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700709 c.verbose = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200710 } else if arg == "--empty-ninja-file" {
711 c.emptyNinjaFile = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100712 } else if arg == "--skip-ninja" {
713 c.skipNinja = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700714 } else if arg == "--skip-make" {
Colin Cross30e444b2021-06-18 11:26:19 -0700715 // TODO(ccross): deprecate this, it has confusing behaviors. It doesn't run kati,
716 // but it does run a Kati ninja file if the .kati_enabled marker file was created
717 // by a previous build.
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000718 c.skipConfig = true
719 c.skipKati = true
720 } else if arg == "--skip-kati" {
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100721 // TODO: remove --skip-kati once module builds have been migrated to --song-only
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000722 c.skipKati = true
Anton Hansson0b55bdb2021-06-04 10:08:08 +0100723 } else if arg == "--soong-only" {
724 c.skipKati = true
725 c.skipKatiNinja = true
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200726 } else if arg == "--config-only" {
727 c.skipKati = true
728 c.skipKatiNinja = true
729 c.skipSoong = true
Colin Cross30e444b2021-06-18 11:26:19 -0700730 } else if arg == "--skip-config" {
731 c.skipConfig = true
Colin Cross00a8a3f2020-10-29 14:08:31 -0700732 } else if arg == "--skip-soong-tests" {
733 c.skipSoongTests = true
Chris Parsons53f68ae2022-03-03 12:01:40 -0500734 } else if arg == "--mk-metrics" {
735 c.reportMkMetrics = true
Chris Parsonsef615e52022-08-18 22:04:11 -0400736 } else if arg == "--bazel-mode" {
737 c.bazelProdMode = true
738 } else if arg == "--bazel-mode-dev" {
739 c.bazelDevMode = true
MarkDacekb78465d2022-10-18 20:10:16 +0000740 } else if arg == "--bazel-mode-staging" {
741 c.bazelStagingMode = true
Spandan Das394aa322022-11-03 17:02:10 +0000742 } else if arg == "--search-api-dir" {
743 c.searchApiDir = true
MarkDacekb96561e2022-12-02 04:34:43 +0000744 } else if strings.HasPrefix(arg, "--build-command=") {
745 buildCmd := strings.TrimPrefix(arg, "--build-command=")
746 // remove quotations
747 buildCmd = strings.TrimPrefix(buildCmd, "\"")
748 buildCmd = strings.TrimSuffix(buildCmd, "\"")
749 ctx.Metrics.SetBuildCommand([]string{buildCmd})
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700750 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700751 parseArgNum := func(def int) int {
752 if len(arg) > 2 {
753 p, err := strconv.ParseUint(arg[2:], 10, 31)
754 if err != nil {
755 ctx.Fatalf("Failed to parse %q: %v", arg, err)
756 }
757 return int(p)
758 } else if i+1 < len(args) {
759 p, err := strconv.ParseUint(args[i+1], 10, 31)
760 if err == nil {
761 i++
762 return int(p)
763 }
764 }
765 return def
766 }
767
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700768 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700769 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700770 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700771 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700772 } else {
773 ctx.Fatalln("Unknown option:", arg)
774 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700775 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700776 if k == "OUT_DIR" {
777 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
778 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700779 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700780 } else if arg == "dist" {
781 c.dist = true
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200782 } else if arg == "json-module-graph" {
783 c.jsonModuleGraph = true
784 } else if arg == "bp2build" {
785 c.bp2build = true
Spandan Das5af0bd32022-09-28 20:43:08 +0000786 } else if arg == "api_bp2build" {
787 c.apiBp2build = true
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200788 } else if arg == "queryview" {
789 c.queryview = true
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200790 } else if arg == "soong_docs" {
791 c.soongDocs = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700792 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700793 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800794 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700795 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700796 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700797 }
798 }
Chris Parsonsb6e96902022-10-31 20:08:45 -0400799 if (!c.bazelProdMode) && (!c.bazelDevMode) && (!c.bazelStagingMode) {
800 c.bazelProdMode = defaultBazelProdMode(c)
801 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700802}
803
Dan Willemsened869522018-01-08 14:58:46 -0800804func (c *configImpl) configureLocale(ctx Context) {
805 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
806 output, err := cmd.Output()
807
808 var locales []string
809 if err == nil {
810 locales = strings.Split(string(output), "\n")
811 } else {
812 // If we're unable to list the locales, let's assume en_US.UTF-8
813 locales = []string{"en_US.UTF-8"}
814 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
815 }
816
817 // gettext uses LANGUAGE, which is passed directly through
818
819 // For LANG and LC_*, only preserve the evaluated version of
820 // LC_MESSAGES
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800821 userLang := ""
Dan Willemsened869522018-01-08 14:58:46 -0800822 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800823 userLang = lc_all
Dan Willemsened869522018-01-08 14:58:46 -0800824 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800825 userLang = lc_messages
Dan Willemsened869522018-01-08 14:58:46 -0800826 } else if lang, ok := c.environ.Get("LANG"); ok {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800827 userLang = lang
Dan Willemsened869522018-01-08 14:58:46 -0800828 }
829
830 c.environ.UnsetWithPrefix("LC_")
831
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800832 if userLang != "" {
833 c.environ.Set("LC_MESSAGES", userLang)
Dan Willemsened869522018-01-08 14:58:46 -0800834 }
835
836 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
837 // for others)
838 if inList("C.UTF-8", locales) {
839 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500840 } else if inList("C.utf8", locales) {
841 // These normalize to the same thing
842 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800843 } else if inList("en_US.UTF-8", locales) {
844 c.environ.Set("LANG", "en_US.UTF-8")
845 } else if inList("en_US.utf8", locales) {
846 // These normalize to the same thing
847 c.environ.Set("LANG", "en_US.UTF-8")
848 } else {
849 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
850 }
851}
852
Dan Willemsen1e704462016-08-21 15:17:17 -0700853func (c *configImpl) Environment() *Environment {
854 return c.environ
855}
856
857func (c *configImpl) Arguments() []string {
858 return c.arguments
859}
860
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200861func (c *configImpl) SoongBuildInvocationNeeded() bool {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200862 if len(c.Arguments()) > 0 {
863 // Explicit targets requested that are not special targets like b2pbuild
864 // or the JSON module graph
865 return true
866 }
867
Spandan Das5af0bd32022-09-28 20:43:08 +0000868 if !c.JsonModuleGraph() && !c.Bp2Build() && !c.Queryview() && !c.SoongDocs() && !c.ApiBp2build() {
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200869 // Command line was empty, the default Ninja target is built
870 return true
871 }
872
Liz Kammer88677422021-12-15 15:03:19 -0500873 // bp2build + dist may be used to dist bp2build logs but does not require SoongBuildInvocation
874 if c.Dist() && !c.Bp2Build() {
875 return true
876 }
877
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200878 // build.ninja doesn't need to be generated
879 return false
880}
881
Dan Willemsen1e704462016-08-21 15:17:17 -0700882func (c *configImpl) OutDir() string {
883 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700884 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700885 }
886 return "out"
887}
888
Dan Willemsen8a073a82017-02-04 17:30:44 -0800889func (c *configImpl) DistDir() string {
Chris Parsons19ab9a42022-08-30 13:15:04 -0400890 return c.distDir
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000891}
892
893func (c *configImpl) RealDistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700894 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800895}
896
Dan Willemsen1e704462016-08-21 15:17:17 -0700897func (c *configImpl) NinjaArgs() []string {
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000898 if c.skipKati {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700899 return c.arguments
900 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700901 return c.ninjaArgs
902}
903
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500904func (c *configImpl) BazelOutDir() string {
905 return filepath.Join(c.OutDir(), "bazel")
906}
907
Liz Kammer2af5ea82022-11-11 14:21:03 -0500908func (c *configImpl) bazelOutputBase() string {
909 return filepath.Join(c.BazelOutDir(), "output")
910}
911
Dan Willemsen1e704462016-08-21 15:17:17 -0700912func (c *configImpl) SoongOutDir() string {
913 return filepath.Join(c.OutDir(), "soong")
914}
915
Spandan Das394aa322022-11-03 17:02:10 +0000916func (c *configImpl) ApiSurfacesOutDir() string {
917 return filepath.Join(c.OutDir(), "api_surfaces")
918}
919
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200920func (c *configImpl) PrebuiltOS() string {
921 switch runtime.GOOS {
922 case "linux":
923 return "linux-x86"
924 case "darwin":
925 return "darwin-x86"
926 default:
927 panic("Unknown GOOS")
928 }
929}
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100930
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200931func (c *configImpl) HostToolDir() string {
Colin Crossacfcc1f2021-10-25 15:40:32 -0700932 if c.SkipKatiNinja() {
933 return filepath.Join(c.SoongOutDir(), "host", c.PrebuiltOS(), "bin")
934 } else {
935 return filepath.Join(c.OutDir(), "host", c.PrebuiltOS(), "bin")
936 }
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200937}
938
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200939func (c *configImpl) NamedGlobFile(name string) string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100940 return shared.JoinPath(c.SoongOutDir(), "globs-"+name+".ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200941}
942
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200943func (c *configImpl) UsedEnvFile(tag string) string {
944 return shared.JoinPath(c.SoongOutDir(), usedEnvFile+"."+tag)
945}
946
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000947func (c *configImpl) Bp2BuildFilesMarkerFile() string {
948 return shared.JoinPath(c.SoongOutDir(), "bp2build_files_marker")
949}
950
951func (c *configImpl) Bp2BuildWorkspaceMarkerFile() string {
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100952 return shared.JoinPath(c.SoongOutDir(), "bp2build_workspace_marker")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200953}
954
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200955func (c *configImpl) SoongDocsHtml() string {
956 return shared.JoinPath(c.SoongOutDir(), "docs/soong_build.html")
957}
958
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200959func (c *configImpl) QueryviewMarkerFile() string {
960 return shared.JoinPath(c.SoongOutDir(), "queryview.marker")
961}
962
Spandan Das5af0bd32022-09-28 20:43:08 +0000963func (c *configImpl) ApiBp2buildMarkerFile() string {
964 return shared.JoinPath(c.SoongOutDir(), "api_bp2build.marker")
965}
966
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200967func (c *configImpl) ModuleGraphFile() string {
968 return shared.JoinPath(c.SoongOutDir(), "module-graph.json")
969}
970
kgui67007242022-01-25 13:50:25 +0800971func (c *configImpl) ModuleActionsFile() string {
972 return shared.JoinPath(c.SoongOutDir(), "module-actions.json")
973}
974
Jeff Gastonefc1b412017-03-29 17:29:06 -0700975func (c *configImpl) TempDir() string {
976 return shared.TempDirForOutDir(c.SoongOutDir())
977}
978
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700979func (c *configImpl) FileListDir() string {
980 return filepath.Join(c.OutDir(), ".module_paths")
981}
982
Dan Willemsen1e704462016-08-21 15:17:17 -0700983func (c *configImpl) KatiSuffix() string {
984 if c.katiSuffix != "" {
985 return c.katiSuffix
986 }
987 panic("SetKatiSuffix has not been called")
988}
989
Colin Cross37193492017-11-16 17:55:00 -0800990// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
991// user is interested in additional checks at the expense of build time.
992func (c *configImpl) Checkbuild() bool {
993 return c.checkbuild
994}
995
Dan Willemsen8a073a82017-02-04 17:30:44 -0800996func (c *configImpl) Dist() bool {
997 return c.dist
998}
999
Lukacs T. Berkia1b93722021-09-02 17:23:06 +02001000func (c *configImpl) JsonModuleGraph() bool {
1001 return c.jsonModuleGraph
1002}
1003
1004func (c *configImpl) Bp2Build() bool {
1005 return c.bp2build
1006}
1007
Spandan Das5af0bd32022-09-28 20:43:08 +00001008func (c *configImpl) ApiBp2build() bool {
1009 return c.apiBp2build
1010}
1011
Lukacs T. Berki3a821692021-09-06 17:08:02 +02001012func (c *configImpl) Queryview() bool {
1013 return c.queryview
1014}
1015
Lukacs T. Berkic6012f32021-09-06 18:31:46 +02001016func (c *configImpl) SoongDocs() bool {
1017 return c.soongDocs
1018}
1019
Dan Willemsen1e704462016-08-21 15:17:17 -07001020func (c *configImpl) IsVerbose() bool {
1021 return c.verbose
1022}
1023
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001024func (c *configImpl) SkipKati() bool {
1025 return c.skipKati
1026}
1027
Anton Hansson0b55bdb2021-06-04 10:08:08 +01001028func (c *configImpl) SkipKatiNinja() bool {
1029 return c.skipKatiNinja
1030}
1031
Lukacs T. Berkicef87b62021-08-10 15:01:13 +02001032func (c *configImpl) SkipSoong() bool {
1033 return c.skipSoong
1034}
1035
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +01001036func (c *configImpl) SkipNinja() bool {
1037 return c.skipNinja
1038}
1039
Anton Hansson5a7861a2021-06-04 10:09:01 +01001040func (c *configImpl) SetSkipNinja(v bool) {
1041 c.skipNinja = v
1042}
1043
Anton Hansson5e5c48b2020-11-27 12:35:20 +00001044func (c *configImpl) SkipConfig() bool {
1045 return c.skipConfig
Dan Willemsene0879fc2017-08-04 15:06:27 -07001046}
1047
Dan Willemsen1e704462016-08-21 15:17:17 -07001048func (c *configImpl) TargetProduct() string {
1049 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
1050 return v
1051 }
1052 panic("TARGET_PRODUCT is not defined")
1053}
1054
Dan Willemsen02781d52017-05-12 19:28:13 -07001055func (c *configImpl) TargetDevice() string {
1056 return c.targetDevice
1057}
1058
1059func (c *configImpl) SetTargetDevice(device string) {
1060 c.targetDevice = device
1061}
1062
1063func (c *configImpl) TargetBuildVariant() string {
1064 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
1065 return v
1066 }
1067 panic("TARGET_BUILD_VARIANT is not defined")
1068}
1069
Dan Willemsen1e704462016-08-21 15:17:17 -07001070func (c *configImpl) KatiArgs() []string {
1071 return c.katiArgs
1072}
1073
1074func (c *configImpl) Parallel() int {
1075 return c.parallel
1076}
1077
Colin Cross8b8bec32019-11-15 13:18:43 -08001078func (c *configImpl) HighmemParallel() int {
1079 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
1080 return i
1081 }
1082
1083 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
1084 parallel := c.Parallel()
1085 if c.UseRemoteBuild() {
1086 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
1087 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
1088 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
1089 // Return 1/16th of the size of the local pool, rounding up.
1090 return (parallel + 15) / 16
1091 } else if c.totalRAM == 0 {
1092 // Couldn't detect the total RAM, don't restrict highmem processes.
1093 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -07001094 } else if c.totalRAM <= 16*1024*1024*1024 {
1095 // Less than 16GB of ram, restrict to 1 highmem processes
1096 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -08001097 } else if c.totalRAM <= 32*1024*1024*1024 {
1098 // Less than 32GB of ram, restrict to 2 highmem processes
1099 return 2
1100 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
1101 // If less than 8GB total RAM per process, reduce the number of highmem processes
1102 return p
1103 }
1104 // No restriction on highmem processes
1105 return parallel
1106}
1107
Dan Willemsen2bb82d02019-12-27 09:35:42 -08001108func (c *configImpl) TotalRAM() uint64 {
1109 return c.totalRAM
1110}
1111
Kousik Kumarec478642020-09-21 13:39:24 -04001112// ForceUseGoma determines whether we should override Goma deprecation
1113// and use Goma for the current build or not.
1114func (c *configImpl) ForceUseGoma() bool {
1115 if v, ok := c.environ.Get("FORCE_USE_GOMA"); ok {
1116 v = strings.TrimSpace(v)
1117 if v != "" && v != "false" {
1118 return true
1119 }
1120 }
1121 return false
1122}
1123
Dan Willemsen1e704462016-08-21 15:17:17 -07001124func (c *configImpl) UseGoma() bool {
1125 if v, ok := c.environ.Get("USE_GOMA"); ok {
1126 v = strings.TrimSpace(v)
1127 if v != "" && v != "false" {
1128 return true
1129 }
1130 }
1131 return false
1132}
1133
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +09001134func (c *configImpl) StartGoma() bool {
1135 if !c.UseGoma() {
1136 return false
1137 }
1138
1139 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
1140 v = strings.TrimSpace(v)
1141 if v != "" && v != "false" {
1142 return false
1143 }
1144 }
1145 return true
1146}
1147
Ramy Medhatbbf25672019-07-17 12:30:04 +00001148func (c *configImpl) UseRBE() bool {
Kousik Kumar3ff037e2022-01-25 22:11:01 -05001149 if v, ok := c.Environment().Get("USE_RBE"); ok {
Ramy Medhatbbf25672019-07-17 12:30:04 +00001150 v = strings.TrimSpace(v)
1151 if v != "" && v != "false" {
1152 return true
1153 }
1154 }
1155 return false
1156}
1157
Chris Parsonsef615e52022-08-18 22:04:11 -04001158func (c *configImpl) BazelBuildEnabled() bool {
MarkDacekb78465d2022-10-18 20:10:16 +00001159 return c.bazelProdMode || c.bazelDevMode || c.bazelStagingMode
Chris Parsonsec1a3dc2021-04-20 15:32:07 -04001160}
1161
Ramy Medhatbbf25672019-07-17 12:30:04 +00001162func (c *configImpl) StartRBE() bool {
1163 if !c.UseRBE() {
1164 return false
1165 }
1166
1167 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
1168 v = strings.TrimSpace(v)
1169 if v != "" && v != "false" {
1170 return false
1171 }
1172 }
1173 return true
1174}
1175
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001176func (c *configImpl) rbeProxyLogsDir() string {
1177 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
Kousik Kumar0d15a722020-09-23 02:54:11 -04001178 if v, ok := c.environ.Get(f); ok {
1179 return v
1180 }
1181 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001182 buildTmpDir := shared.TempDirForOutDir(c.SoongOutDir())
1183 return filepath.Join(buildTmpDir, "rbe")
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001184}
1185
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001186func (c *configImpl) shouldCleanupRBELogsDir() bool {
1187 // Perform a log directory cleanup only when the log directory
1188 // is auto created by the build rather than user-specified.
1189 for _, f := range []string{"RBE_proxy_log_dir", "FLAG_output_dir"} {
1190 if _, ok := c.environ.Get(f); ok {
1191 return false
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001192 }
1193 }
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001194 return true
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001195}
1196
1197func (c *configImpl) rbeExecRoot() string {
1198 for _, f := range []string{"RBE_exec_root", "FLAG_exec_root"} {
1199 if v, ok := c.environ.Get(f); ok {
1200 return v
1201 }
1202 }
1203 wd, err := os.Getwd()
1204 if err != nil {
1205 return ""
1206 }
1207 return wd
1208}
1209
1210func (c *configImpl) rbeDir() string {
1211 if v, ok := c.environ.Get("RBE_DIR"); ok {
1212 return v
1213 }
1214 return "prebuilts/remoteexecution-client/live/"
1215}
1216
1217func (c *configImpl) rbeReproxy() string {
1218 for _, f := range []string{"RBE_re_proxy", "FLAG_re_proxy"} {
1219 if v, ok := c.environ.Get(f); ok {
1220 return v
1221 }
1222 }
1223 return filepath.Join(c.rbeDir(), "reproxy")
1224}
1225
1226func (c *configImpl) rbeAuth() (string, string) {
Kousik Kumar93d192c2022-03-18 01:39:56 -04001227 credFlags := []string{
1228 "use_application_default_credentials",
1229 "use_gce_credentials",
1230 "credential_file",
1231 "use_google_prod_creds",
1232 }
Ramy Medhat0fc67eb2020-08-12 01:26:23 -04001233 for _, cf := range credFlags {
1234 for _, f := range []string{"RBE_" + cf, "FLAG_" + cf} {
1235 if v, ok := c.environ.Get(f); ok {
1236 v = strings.TrimSpace(v)
1237 if v != "" && v != "false" && v != "0" {
1238 return "RBE_" + cf, v
1239 }
1240 }
1241 }
1242 }
1243 return "RBE_use_application_default_credentials", "true"
Patrice Arruda62f1bf22020-07-07 12:48:26 +00001244}
1245
Kousik Kumar4c180ad2022-05-27 07:48:37 -04001246func (c *configImpl) rbeSockAddr(dir string) (string, error) {
1247 maxNameLen := len(syscall.RawSockaddrUnix{}.Path)
1248 base := fmt.Sprintf("reproxy_%v.sock", rbeRandPrefix)
1249
1250 name := filepath.Join(dir, base)
1251 if len(name) < maxNameLen {
1252 return name, nil
1253 }
1254
1255 name = filepath.Join("/tmp", base)
1256 if len(name) < maxNameLen {
1257 return name, nil
1258 }
1259
1260 return "", fmt.Errorf("cannot generate a proxy socket address shorter than the limit of %v", maxNameLen)
1261}
1262
Kousik Kumar7bc78192022-04-27 14:52:56 -04001263// IsGooglerEnvironment returns true if the current build is running
1264// on a Google developer machine and false otherwise.
1265func (c *configImpl) IsGooglerEnvironment() bool {
1266 cf := "ANDROID_BUILD_ENVIRONMENT_CONFIG"
1267 if v, ok := c.environ.Get(cf); ok {
1268 return v == "googler"
1269 }
1270 return false
1271}
1272
1273// GoogleProdCredsExist determine whether credentials exist on the
1274// Googler machine to use remote execution.
1275func (c *configImpl) GoogleProdCredsExist() bool {
1276 if _, err := exec.Command("/usr/bin/prodcertstatus", "--simple_output", "--nocheck_loas").Output(); err != nil {
1277 return false
1278 }
1279 return true
1280}
1281
1282// UseRemoteBuild indicates whether to use a remote build acceleration system
1283// to speed up the build.
Colin Cross9016b912019-11-11 14:57:42 -08001284func (c *configImpl) UseRemoteBuild() bool {
1285 return c.UseGoma() || c.UseRBE()
1286}
1287
Kousik Kumar7bc78192022-04-27 14:52:56 -04001288// StubbyExists checks whether the stubby binary exists on the machine running
1289// the build.
1290func (c *configImpl) StubbyExists() bool {
1291 if _, err := exec.LookPath("stubby"); err != nil {
1292 return false
1293 }
1294 return true
1295}
1296
Dan Willemsen1e704462016-08-21 15:17:17 -07001297// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -07001298// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -07001299// still limited by Parallel()
1300func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -08001301 if !c.UseRemoteBuild() {
1302 return 0
1303 }
1304 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
1305 return i
Dan Willemsen1e704462016-08-21 15:17:17 -07001306 }
1307 return 500
1308}
1309
1310func (c *configImpl) SetKatiArgs(args []string) {
1311 c.katiArgs = args
1312}
1313
1314func (c *configImpl) SetNinjaArgs(args []string) {
1315 c.ninjaArgs = args
1316}
1317
1318func (c *configImpl) SetKatiSuffix(suffix string) {
1319 c.katiSuffix = suffix
1320}
1321
Dan Willemsene0879fc2017-08-04 15:06:27 -07001322func (c *configImpl) LastKatiSuffixFile() string {
1323 return filepath.Join(c.OutDir(), "last_kati_suffix")
1324}
1325
1326func (c *configImpl) HasKatiSuffix() bool {
1327 return c.katiSuffix != ""
1328}
1329
Dan Willemsen1e704462016-08-21 15:17:17 -07001330func (c *configImpl) KatiEnvFile() string {
1331 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
1332}
1333
Dan Willemsen29971232018-09-26 14:58:30 -07001334func (c *configImpl) KatiBuildNinjaFile() string {
1335 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -07001336}
1337
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001338func (c *configImpl) KatiPackageNinjaFile() string {
1339 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
1340}
1341
Jihoon Kang9f4f8a32022-08-16 00:57:30 +00001342func (c *configImpl) SoongVarsFile() string {
1343 return filepath.Join(c.SoongOutDir(), "soong.variables")
1344}
1345
Dan Willemsen1e704462016-08-21 15:17:17 -07001346func (c *configImpl) SoongNinjaFile() string {
1347 return filepath.Join(c.SoongOutDir(), "build.ninja")
1348}
1349
1350func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -07001351 if c.katiSuffix == "" {
1352 return filepath.Join(c.OutDir(), "combined.ninja")
1353 }
Dan Willemsen1e704462016-08-21 15:17:17 -07001354 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
1355}
1356
1357func (c *configImpl) SoongAndroidMk() string {
1358 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
1359}
1360
1361func (c *configImpl) SoongMakeVarsMk() string {
1362 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
1363}
1364
Dan Willemsenf052f782017-05-18 15:29:04 -07001365func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001366 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -07001367}
1368
Dan Willemsen02781d52017-05-12 19:28:13 -07001369func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -07001370 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
1371}
1372
Dan Willemsenfb1271a2018-09-26 15:00:42 -07001373func (c *configImpl) KatiPackageMkDir() string {
1374 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
1375}
1376
Dan Willemsenf052f782017-05-18 15:29:04 -07001377func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -07001378 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -07001379}
1380
1381func (c *configImpl) HostOut() string {
1382 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
1383}
1384
1385// This probably needs to be multi-valued, so not exporting it for now
1386func (c *configImpl) hostCrossOut() string {
1387 if runtime.GOOS == "linux" {
1388 return filepath.Join(c.hostOutRoot(), "windows-x86")
1389 } else {
1390 return ""
1391 }
Dan Willemsen02781d52017-05-12 19:28:13 -07001392}
1393
Dan Willemsen1e704462016-08-21 15:17:17 -07001394func (c *configImpl) HostPrebuiltTag() string {
1395 if runtime.GOOS == "linux" {
1396 return "linux-x86"
1397 } else if runtime.GOOS == "darwin" {
1398 return "darwin-x86"
1399 } else {
1400 panic("Unsupported OS")
1401 }
1402}
Dan Willemsenf173d592017-04-27 14:28:00 -07001403
Dan Willemsen8122bd52017-10-12 20:20:41 -07001404func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -07001405 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
1406 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -07001407 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
1408 if _, err := os.Stat(asan); err == nil {
1409 return asan
1410 }
Dan Willemsenf173d592017-04-27 14:28:00 -07001411 }
1412 }
1413 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
1414}
Dan Willemsen3d60b112018-04-04 22:25:56 -07001415
1416func (c *configImpl) SetBuildBrokenDupRules(val bool) {
1417 c.brokenDupRules = val
1418}
1419
1420func (c *configImpl) BuildBrokenDupRules() bool {
1421 return c.brokenDupRules
1422}
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001423
Dan Willemsen25e6f092019-04-09 10:22:43 -07001424func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
1425 c.brokenUsesNetwork = val
1426}
1427
1428func (c *configImpl) BuildBrokenUsesNetwork() bool {
1429 return c.brokenUsesNetwork
1430}
1431
Dan Willemsene3336352020-01-02 19:10:38 -08001432func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
1433 c.brokenNinjaEnvVars = val
1434}
1435
1436func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
1437 return c.brokenNinjaEnvVars
1438}
1439
Dan Willemsen6ab79db2018-05-02 00:06:28 -07001440func (c *configImpl) SetTargetDeviceDir(dir string) {
1441 c.targetDeviceDir = dir
1442}
1443
1444func (c *configImpl) TargetDeviceDir() string {
1445 return c.targetDeviceDir
1446}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -07001447
Patrice Arruda219eef32020-06-01 17:29:30 +00001448func (c *configImpl) BuildDateTime() string {
1449 return c.buildDateTime
1450}
1451
1452func (c *configImpl) MetricsUploaderApp() string {
Yu Liu6e13b402021-07-27 14:29:06 -07001453 return c.metricsUploader
Patrice Arruda219eef32020-06-01 17:29:30 +00001454}
Patrice Arruda83842d72020-12-08 19:42:08 +00001455
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001456// LogsDir returns the absolute path to the logs directory where build log and
1457// metrics files are located. By default, the logs directory is the out
Patrice Arruda83842d72020-12-08 19:42:08 +00001458// directory. If the argument dist is specified, the logs directory
1459// is <dist_dir>/logs.
1460func (c *configImpl) LogsDir() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001461 dir := c.OutDir()
Patrice Arruda83842d72020-12-08 19:42:08 +00001462 if c.Dist() {
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +00001463 // 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 -05001464 dir = filepath.Join(c.RealDistDir(), "logs")
Patrice Arruda83842d72020-12-08 19:42:08 +00001465 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -05001466 absDir, err := filepath.Abs(dir)
1467 if err != nil {
1468 fmt.Fprintf(os.Stderr, "\nError making log dir '%s' absolute: %s\n", dir, err.Error())
1469 os.Exit(1)
1470 }
1471 return absDir
Patrice Arruda83842d72020-12-08 19:42:08 +00001472}
1473
1474// BazelMetricsDir returns the <logs dir>/bazel_metrics directory
1475// where the bazel profiles are located.
1476func (c *configImpl) BazelMetricsDir() string {
1477 return filepath.Join(c.LogsDir(), "bazel_metrics")
1478}
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001479
Chris Parsons53f68ae2022-03-03 12:01:40 -05001480// MkFileMetrics returns the file path for make-related metrics.
1481func (c *configImpl) MkMetrics() string {
1482 return filepath.Join(c.LogsDir(), "mk_metrics.pb")
1483}
1484
Colin Crossf3bdbcb2021-06-01 11:43:55 -07001485func (c *configImpl) SetEmptyNinjaFile(v bool) {
1486 c.emptyNinjaFile = v
1487}
1488
1489func (c *configImpl) EmptyNinjaFile() bool {
1490 return c.emptyNinjaFile
1491}
Yu Liu6e13b402021-07-27 14:29:06 -07001492
Romain Jobredeaux0a7529b2022-10-26 12:56:41 -04001493func (c *configImpl) IsBazelMixedBuildForceDisabled() bool {
1494 return c.Environment().IsEnvTrue("BUILD_BROKEN_DISABLE_BAZEL")
1495}
1496
Yu Liu6e13b402021-07-27 14:29:06 -07001497func GetMetricsUploader(topDir string, env *Environment) string {
1498 if p, ok := env.Get("METRICS_UPLOADER"); ok {
1499 metricsUploader := filepath.Join(topDir, p)
1500 if _, err := os.Stat(metricsUploader); err == nil {
1501 return metricsUploader
1502 }
1503 }
1504
1505 return ""
1506}