blob: b263a98a5d254eaec7e6ed8c0ea94df574ba3e6d [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 (
Dan Willemsenc2af0be2017-01-20 14:10:01 -080018 "os"
Dan Willemsen1e704462016-08-21 15:17:17 -070019 "path/filepath"
20 "runtime"
21 "strconv"
22 "strings"
Nan Zhang2e6a4ff2018-02-14 13:27:26 -080023 "time"
Jeff Gastonefc1b412017-03-29 17:29:06 -070024
25 "android/soong/shared"
Dan Willemsen1e704462016-08-21 15:17:17 -070026)
27
28type Config struct{ *configImpl }
29
30type configImpl struct {
31 // From the environment
Colin Cross28f527c2019-11-26 16:19:04 -080032 arguments []string
33 goma bool
34 environ *Environment
35 distDir string
36 buildDateTime string
Dan Willemsen1e704462016-08-21 15:17:17 -070037
38 // From the arguments
Colin Cross37193492017-11-16 17:55:00 -080039 parallel int
40 keepGoing int
41 verbose bool
42 checkbuild bool
43 dist bool
44 skipMake bool
Dan Willemsen1e704462016-08-21 15:17:17 -070045
46 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070047 katiArgs []string
48 ninjaArgs []string
49 katiSuffix string
50 targetDevice string
51 targetDeviceDir string
Dan Willemsen3d60b112018-04-04 22:25:56 -070052
Dan Willemsen2bb82d02019-12-27 09:35:42 -080053 // Autodetected
54 totalRAM uint64
55
Dan Willemsene3336352020-01-02 19:10:38 -080056 brokenDupRules bool
57 brokenUsesNetwork bool
58 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -070059
60 pathReplaced bool
Dan Willemsen1e704462016-08-21 15:17:17 -070061}
62
Dan Willemsenc2af0be2017-01-20 14:10:01 -080063const srcDirFileCheck = "build/soong/root.bp"
64
Patrice Arruda9450d0b2019-07-08 11:06:46 -070065var buildFiles = []string{"Android.mk", "Android.bp"}
66
Patrice Arruda13848222019-04-22 17:12:02 -070067type BuildAction uint
68
69const (
70 // Builds all of the modules and their dependencies of a specified directory, relative to the root
71 // directory of the source tree.
72 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
73
74 // Builds all of the modules and their dependencies of a list of specified directories. All specified
75 // directories are relative to the root directory of the source tree.
76 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -070077
78 // Build a list of specified modules. If none was specified, simply build the whole source tree.
79 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -070080)
81
82// checkTopDir validates that the current directory is at the root directory of the source tree.
83func checkTopDir(ctx Context) {
84 if _, err := os.Stat(srcDirFileCheck); err != nil {
85 if os.IsNotExist(err) {
86 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
87 }
88 ctx.Fatalln("Error verifying tree state:", err)
89 }
90}
91
Dan Willemsen1e704462016-08-21 15:17:17 -070092func NewConfig(ctx Context, args ...string) Config {
93 ret := &configImpl{
94 environ: OsEnvironment(),
95 }
96
Patrice Arruda90109172020-07-28 18:07:27 +000097 // Default matching ninja
Dan Willemsen9b587492017-07-10 22:13:00 -070098 ret.parallel = runtime.NumCPU() + 2
99 ret.keepGoing = 1
100
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800101 ret.totalRAM = detectTotalRAM(ctx)
102
Dan Willemsen9b587492017-07-10 22:13:00 -0700103 ret.parseArgs(ctx, args)
104
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800105 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700106 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
107 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
108 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800109 outDir := "out"
110 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
111 if wd, err := os.Getwd(); err != nil {
112 ctx.Fatalln("Failed to get working directory:", err)
113 } else {
114 outDir = filepath.Join(baseDir, filepath.Base(wd))
115 }
116 }
117 ret.environ.Set("OUT_DIR", outDir)
118 }
119
Dan Willemsen2d31a442018-10-20 21:33:41 -0700120 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
121 ret.distDir = filepath.Clean(distDir)
122 } else {
123 ret.distDir = filepath.Join(ret.OutDir(), "dist")
124 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700125
Dan Willemsen1e704462016-08-21 15:17:17 -0700126 ret.environ.Unset(
127 // We're already using it
128 "USE_SOONG_UI",
129
130 // We should never use GOROOT/GOPATH from the shell environment
131 "GOROOT",
132 "GOPATH",
133
134 // These should only come from Soong, not the environment.
135 "CLANG",
136 "CLANG_CXX",
137 "CCC_CC",
138 "CCC_CXX",
139
140 // Used by the goma compiler wrapper, but should only be set by
141 // gomacc
142 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800143
144 // We handle this above
145 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700146
Dan Willemsen2d31a442018-10-20 21:33:41 -0700147 // This is handled above too, and set for individual commands later
148 "DIST_DIR",
149
Dan Willemsen68a09852017-04-18 13:56:57 -0700150 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000151 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700152 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700153 "DISPLAY",
154 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700155 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700156 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700157
158 // Drop make flags
159 "MAKEFLAGS",
160 "MAKELEVEL",
161 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700162
163 // Set in envsetup.sh, reset in makefiles
164 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700165
166 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
167 "ANDROID_BUILD_TOP",
168 "ANDROID_HOST_OUT",
169 "ANDROID_PRODUCT_OUT",
170 "ANDROID_HOST_OUT_TESTCASES",
171 "ANDROID_TARGET_OUT_TESTCASES",
172 "ANDROID_TOOLCHAIN",
173 "ANDROID_TOOLCHAIN_2ND_ARCH",
174 "ANDROID_DEV_SCRIPTS",
175 "ANDROID_EMULATOR_PREBUILTS",
176 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsenf99915f2018-10-25 22:04:42 -0700177
178 // Only set in multiproduct_kati after config generation
179 "EMPTY_NINJA_FILE",
Dan Willemsen1e704462016-08-21 15:17:17 -0700180 )
181
182 // Tell python not to spam the source tree with .pyc files.
183 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
184
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400185 tmpDir := absPath(ctx, ret.TempDir())
186 ret.environ.Set("TMPDIR", tmpDir)
Dan Willemsen32a669b2018-03-08 19:42:00 -0800187
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700188 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
189 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
190 "llvm-binutils-stable/llvm-symbolizer")
191 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
192
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800193 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700194 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800195
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700196 if srcDir := absPath(ctx, "."); strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700197 ctx.Println("You are building in a directory whose absolute path contains a space character:")
198 ctx.Println()
199 ctx.Printf("%q\n", srcDir)
200 ctx.Println()
201 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700202 }
203
204 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700205 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
206 ctx.Println()
207 ctx.Printf("%q\n", outDir)
208 ctx.Println()
209 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700210 }
211
212 if distDir := ret.DistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700213 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
214 ctx.Println()
215 ctx.Printf("%q\n", distDir)
216 ctx.Println()
217 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700218 }
219
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700220 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000221 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
222 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100223 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700224 javaHome := func() string {
225 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
226 return override
227 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000228 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
229 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 +0100230 }
Pete Gillinabbcdda2019-10-28 16:15:33 +0000231 return java11Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700232 }()
233 absJavaHome := absPath(ctx, javaHome)
234
Dan Willemsened869522018-01-08 14:58:46 -0800235 ret.configureLocale(ctx)
236
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700237 newPath := []string{filepath.Join(absJavaHome, "bin")}
238 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
239 newPath = append(newPath, path)
240 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100241
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700242 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
243 ret.environ.Set("JAVA_HOME", absJavaHome)
244 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000245 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
246 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100247 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700248 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
249
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800250 outDir := ret.OutDir()
251 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800252 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800253 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800254 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800255 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800256 }
Colin Cross28f527c2019-11-26 16:19:04 -0800257
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800258 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
259
Ramy Medhatca1e44c2020-07-16 12:18:37 -0400260 if ret.UseRBE() {
261 for k, v := range getRBEVars(ctx, tmpDir) {
262 ret.environ.Set(k, v)
263 }
264 }
265
Dan Willemsen9b587492017-07-10 22:13:00 -0700266 return Config{ret}
267}
268
Patrice Arruda13848222019-04-22 17:12:02 -0700269// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
270// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700271func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
272 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700273}
274
275// getConfigArgs processes the command arguments based on the build action and creates a set of new
276// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700277func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700278 // The next block of code verifies that the current directory is the root directory of the source
279 // tree. It then finds the relative path of dir based on the root directory of the source tree
280 // and verify that dir is inside of the source tree.
281 checkTopDir(ctx)
282 topDir, err := os.Getwd()
283 if err != nil {
284 ctx.Fatalf("Error retrieving top directory: %v", err)
285 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700286 dir, err = filepath.EvalSymlinks(dir)
287 if err != nil {
288 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
289 }
Patrice Arruda13848222019-04-22 17:12:02 -0700290 dir, err = filepath.Abs(dir)
291 if err != nil {
292 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
293 }
294 relDir, err := filepath.Rel(topDir, dir)
295 if err != nil {
296 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
297 }
298 // If there are ".." in the path, it's not in the source tree.
299 if strings.Contains(relDir, "..") {
300 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
301 }
302
303 configArgs := args[:]
304
305 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
306 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
307 targetNamePrefix := "MODULES-IN-"
308 if inList("GET-INSTALL-PATH", configArgs) {
309 targetNamePrefix = "GET-INSTALL-PATH-IN-"
310 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
311 }
312
Patrice Arruda13848222019-04-22 17:12:02 -0700313 var targets []string
314
315 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700316 case BUILD_MODULES:
317 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700318 case BUILD_MODULES_IN_A_DIRECTORY:
319 // If dir is the root source tree, all the modules are built of the source tree are built so
320 // no need to find the build file.
321 if topDir == dir {
322 break
323 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700324
Patrice Arruda13848222019-04-22 17:12:02 -0700325 buildFile := findBuildFile(ctx, relDir)
326 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700327 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700328 }
Patrice Arruda13848222019-04-22 17:12:02 -0700329 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
330 case BUILD_MODULES_IN_DIRECTORIES:
331 newConfigArgs, dirs := splitArgs(configArgs)
332 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700333 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700334 }
335
336 // Tidy only override all other specified targets.
337 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
338 if tidyOnly == "true" || tidyOnly == "1" {
339 configArgs = append(configArgs, "tidy_only")
340 } else {
341 configArgs = append(configArgs, targets...)
342 }
343
344 return configArgs
345}
346
347// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
348func convertToTarget(dir string, targetNamePrefix string) string {
349 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
350}
351
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700352// hasBuildFile returns true if dir contains an Android build file.
353func hasBuildFile(ctx Context, dir string) bool {
354 for _, buildFile := range buildFiles {
355 _, err := os.Stat(filepath.Join(dir, buildFile))
356 if err == nil {
357 return true
358 }
359 if !os.IsNotExist(err) {
360 ctx.Fatalf("Error retrieving the build file stats: %v", err)
361 }
362 }
363 return false
364}
365
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700366// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
367// in the current and any sub directory of dir. If a build file is not found, traverse the path
368// up by one directory and repeat again until either a build file is found or reached to the root
369// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
370// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700371func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700372 // If the string is empty or ".", assume it is top directory of the source tree.
373 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700374 return ""
375 }
376
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700377 found := false
378 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
379 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
380 if err != nil {
381 return err
382 }
383 if found {
384 return filepath.SkipDir
385 }
386 if info.IsDir() {
387 return nil
388 }
389 for _, buildFile := range buildFiles {
390 if info.Name() == buildFile {
391 found = true
392 return filepath.SkipDir
393 }
394 }
395 return nil
396 })
397 if err != nil {
398 ctx.Fatalf("Error finding Android build file: %v", err)
399 }
400
401 if found {
402 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700403 }
404 }
405
406 return ""
407}
408
409// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
410func splitArgs(args []string) (newArgs []string, dirs []string) {
411 specialArgs := map[string]bool{
412 "showcommands": true,
413 "snod": true,
414 "dist": true,
415 "checkbuild": true,
416 }
417
418 newArgs = []string{}
419 dirs = []string{}
420
421 for _, arg := range args {
422 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
423 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
424 newArgs = append(newArgs, arg)
425 continue
426 }
427
428 if _, ok := specialArgs[arg]; ok {
429 newArgs = append(newArgs, arg)
430 continue
431 }
432
433 dirs = append(dirs, arg)
434 }
435
436 return newArgs, dirs
437}
438
439// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
440// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
441// source root tree where the build action command was invoked. Each directory is validated if the
442// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700443func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700444 for _, dir := range dirs {
445 // The directory may have specified specific modules to build. ":" is the separator to separate
446 // the directory and the list of modules.
447 s := strings.Split(dir, ":")
448 l := len(s)
449 if l > 2 { // more than one ":" was specified.
450 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
451 }
452
453 dir = filepath.Join(relDir, s[0])
454 if _, err := os.Stat(dir); err != nil {
455 ctx.Fatalf("couldn't find directory %s", dir)
456 }
457
458 // Verify that if there are any targets specified after ":". Each target is separated by ",".
459 var newTargets []string
460 if l == 2 && s[1] != "" {
461 newTargets = strings.Split(s[1], ",")
462 if inList("", newTargets) {
463 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
464 }
465 }
466
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700467 // If there are specified targets to build in dir, an android build file must exist for the one
468 // shot build. For the non-targets case, find the appropriate build file and build all the
469 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700470 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700471 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700472 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
473 }
474 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700475 buildFile := findBuildFile(ctx, dir)
476 if buildFile == "" {
477 ctx.Fatalf("Build file not found for %s directory", dir)
478 }
479 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700480 }
481
Patrice Arruda13848222019-04-22 17:12:02 -0700482 targets = append(targets, newTargets...)
483 }
484
Dan Willemsence41e942019-07-29 23:39:30 -0700485 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700486}
487
Dan Willemsen9b587492017-07-10 22:13:00 -0700488func (c *configImpl) parseArgs(ctx Context, args []string) {
489 for i := 0; i < len(args); i++ {
490 arg := strings.TrimSpace(args[i])
Dan Willemsen1e704462016-08-21 15:17:17 -0700491 if arg == "--make-mode" {
Dan Willemsen1e704462016-08-21 15:17:17 -0700492 } else if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700493 c.verbose = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700494 } else if arg == "--skip-make" {
495 c.skipMake = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700496 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700497 parseArgNum := func(def int) int {
498 if len(arg) > 2 {
499 p, err := strconv.ParseUint(arg[2:], 10, 31)
500 if err != nil {
501 ctx.Fatalf("Failed to parse %q: %v", arg, err)
502 }
503 return int(p)
504 } else if i+1 < len(args) {
505 p, err := strconv.ParseUint(args[i+1], 10, 31)
506 if err == nil {
507 i++
508 return int(p)
509 }
510 }
511 return def
512 }
513
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700514 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700515 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700516 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700517 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700518 } else {
519 ctx.Fatalln("Unknown option:", arg)
520 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700521 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700522 if k == "OUT_DIR" {
523 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
524 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700525 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700526 } else if arg == "dist" {
527 c.dist = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700528 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700529 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800530 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700531 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700532 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700533 }
534 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700535}
536
Dan Willemsened869522018-01-08 14:58:46 -0800537func (c *configImpl) configureLocale(ctx Context) {
538 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
539 output, err := cmd.Output()
540
541 var locales []string
542 if err == nil {
543 locales = strings.Split(string(output), "\n")
544 } else {
545 // If we're unable to list the locales, let's assume en_US.UTF-8
546 locales = []string{"en_US.UTF-8"}
547 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
548 }
549
550 // gettext uses LANGUAGE, which is passed directly through
551
552 // For LANG and LC_*, only preserve the evaluated version of
553 // LC_MESSAGES
554 user_lang := ""
555 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
556 user_lang = lc_all
557 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
558 user_lang = lc_messages
559 } else if lang, ok := c.environ.Get("LANG"); ok {
560 user_lang = lang
561 }
562
563 c.environ.UnsetWithPrefix("LC_")
564
565 if user_lang != "" {
566 c.environ.Set("LC_MESSAGES", user_lang)
567 }
568
569 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
570 // for others)
571 if inList("C.UTF-8", locales) {
572 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500573 } else if inList("C.utf8", locales) {
574 // These normalize to the same thing
575 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800576 } else if inList("en_US.UTF-8", locales) {
577 c.environ.Set("LANG", "en_US.UTF-8")
578 } else if inList("en_US.utf8", locales) {
579 // These normalize to the same thing
580 c.environ.Set("LANG", "en_US.UTF-8")
581 } else {
582 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
583 }
584}
585
Dan Willemsen1e704462016-08-21 15:17:17 -0700586// Lunch configures the environment for a specific product similarly to the
587// `lunch` bash function.
588func (c *configImpl) Lunch(ctx Context, product, variant string) {
589 if variant != "eng" && variant != "userdebug" && variant != "user" {
590 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
591 }
592
593 c.environ.Set("TARGET_PRODUCT", product)
594 c.environ.Set("TARGET_BUILD_VARIANT", variant)
595 c.environ.Set("TARGET_BUILD_TYPE", "release")
596 c.environ.Unset("TARGET_BUILD_APPS")
Martin Stjernholm08802332020-06-04 17:00:01 +0100597 c.environ.Unset("TARGET_BUILD_UNBUNDLED")
Dan Willemsen1e704462016-08-21 15:17:17 -0700598}
599
600// Tapas configures the environment to build one or more unbundled apps,
601// similarly to the `tapas` bash function.
602func (c *configImpl) Tapas(ctx Context, apps []string, arch, variant string) {
603 if len(apps) == 0 {
604 apps = []string{"all"}
605 }
606 if variant == "" {
607 variant = "eng"
608 }
609
610 if variant != "eng" && variant != "userdebug" && variant != "user" {
611 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
612 }
613
614 var product string
615 switch arch {
Dan Willemsen1e704462016-08-21 15:17:17 -0700616 case "arm", "":
617 product = "aosp_arm"
618 case "arm64":
619 product = "aosm_arm64"
Dan Willemsen1e704462016-08-21 15:17:17 -0700620 case "x86":
621 product = "aosp_x86"
622 case "x86_64":
623 product = "aosp_x86_64"
624 default:
625 ctx.Fatalf("Invalid architecture: %q", arch)
626 }
627
628 c.environ.Set("TARGET_PRODUCT", product)
629 c.environ.Set("TARGET_BUILD_VARIANT", variant)
630 c.environ.Set("TARGET_BUILD_TYPE", "release")
631 c.environ.Set("TARGET_BUILD_APPS", strings.Join(apps, " "))
632}
633
634func (c *configImpl) Environment() *Environment {
635 return c.environ
636}
637
638func (c *configImpl) Arguments() []string {
639 return c.arguments
640}
641
642func (c *configImpl) OutDir() string {
643 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700644 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700645 }
646 return "out"
647}
648
Dan Willemsen8a073a82017-02-04 17:30:44 -0800649func (c *configImpl) DistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700650 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800651}
652
Dan Willemsen1e704462016-08-21 15:17:17 -0700653func (c *configImpl) NinjaArgs() []string {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700654 if c.skipMake {
655 return c.arguments
656 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700657 return c.ninjaArgs
658}
659
660func (c *configImpl) SoongOutDir() string {
661 return filepath.Join(c.OutDir(), "soong")
662}
663
Jeff Gastonefc1b412017-03-29 17:29:06 -0700664func (c *configImpl) TempDir() string {
665 return shared.TempDirForOutDir(c.SoongOutDir())
666}
667
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700668func (c *configImpl) FileListDir() string {
669 return filepath.Join(c.OutDir(), ".module_paths")
670}
671
Dan Willemsen1e704462016-08-21 15:17:17 -0700672func (c *configImpl) KatiSuffix() string {
673 if c.katiSuffix != "" {
674 return c.katiSuffix
675 }
676 panic("SetKatiSuffix has not been called")
677}
678
Colin Cross37193492017-11-16 17:55:00 -0800679// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
680// user is interested in additional checks at the expense of build time.
681func (c *configImpl) Checkbuild() bool {
682 return c.checkbuild
683}
684
Dan Willemsen8a073a82017-02-04 17:30:44 -0800685func (c *configImpl) Dist() bool {
686 return c.dist
687}
688
Dan Willemsen1e704462016-08-21 15:17:17 -0700689func (c *configImpl) IsVerbose() bool {
690 return c.verbose
691}
692
Dan Willemsene0879fc2017-08-04 15:06:27 -0700693func (c *configImpl) SkipMake() bool {
694 return c.skipMake
695}
696
Dan Willemsen1e704462016-08-21 15:17:17 -0700697func (c *configImpl) TargetProduct() string {
698 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
699 return v
700 }
701 panic("TARGET_PRODUCT is not defined")
702}
703
Dan Willemsen02781d52017-05-12 19:28:13 -0700704func (c *configImpl) TargetDevice() string {
705 return c.targetDevice
706}
707
708func (c *configImpl) SetTargetDevice(device string) {
709 c.targetDevice = device
710}
711
712func (c *configImpl) TargetBuildVariant() string {
713 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
714 return v
715 }
716 panic("TARGET_BUILD_VARIANT is not defined")
717}
718
Dan Willemsen1e704462016-08-21 15:17:17 -0700719func (c *configImpl) KatiArgs() []string {
720 return c.katiArgs
721}
722
723func (c *configImpl) Parallel() int {
724 return c.parallel
725}
726
Colin Cross8b8bec32019-11-15 13:18:43 -0800727func (c *configImpl) HighmemParallel() int {
728 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
729 return i
730 }
731
732 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
733 parallel := c.Parallel()
734 if c.UseRemoteBuild() {
735 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
736 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
737 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
738 // Return 1/16th of the size of the local pool, rounding up.
739 return (parallel + 15) / 16
740 } else if c.totalRAM == 0 {
741 // Couldn't detect the total RAM, don't restrict highmem processes.
742 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -0700743 } else if c.totalRAM <= 16*1024*1024*1024 {
744 // Less than 16GB of ram, restrict to 1 highmem processes
745 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -0800746 } else if c.totalRAM <= 32*1024*1024*1024 {
747 // Less than 32GB of ram, restrict to 2 highmem processes
748 return 2
749 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
750 // If less than 8GB total RAM per process, reduce the number of highmem processes
751 return p
752 }
753 // No restriction on highmem processes
754 return parallel
755}
756
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800757func (c *configImpl) TotalRAM() uint64 {
758 return c.totalRAM
759}
760
Dan Willemsen1e704462016-08-21 15:17:17 -0700761func (c *configImpl) UseGoma() bool {
762 if v, ok := c.environ.Get("USE_GOMA"); ok {
763 v = strings.TrimSpace(v)
764 if v != "" && v != "false" {
765 return true
766 }
767 }
768 return false
769}
770
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +0900771func (c *configImpl) StartGoma() bool {
772 if !c.UseGoma() {
773 return false
774 }
775
776 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
777 v = strings.TrimSpace(v)
778 if v != "" && v != "false" {
779 return false
780 }
781 }
782 return true
783}
784
Ramy Medhatbbf25672019-07-17 12:30:04 +0000785func (c *configImpl) UseRBE() bool {
786 if v, ok := c.environ.Get("USE_RBE"); ok {
787 v = strings.TrimSpace(v)
788 if v != "" && v != "false" {
789 return true
790 }
791 }
792 return false
793}
794
795func (c *configImpl) StartRBE() bool {
796 if !c.UseRBE() {
797 return false
798 }
799
800 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
801 v = strings.TrimSpace(v)
802 if v != "" && v != "false" {
803 return false
804 }
805 }
806 return true
807}
808
Patrice Arruda62f1bf22020-07-07 12:48:26 +0000809func (c *configImpl) RBEStatsOutputDir() string {
810 for _, f := range []string{"RBE_output_dir", "FLAG_output_dir"} {
811 if v, ok := c.environ.Get(f); ok {
812 return v
813 }
814 }
815 return ""
816}
817
Colin Cross9016b912019-11-11 14:57:42 -0800818func (c *configImpl) UseRemoteBuild() bool {
819 return c.UseGoma() || c.UseRBE()
820}
821
Dan Willemsen1e704462016-08-21 15:17:17 -0700822// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -0700823// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -0700824// still limited by Parallel()
825func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -0800826 if !c.UseRemoteBuild() {
827 return 0
828 }
829 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
830 return i
Dan Willemsen1e704462016-08-21 15:17:17 -0700831 }
832 return 500
833}
834
835func (c *configImpl) SetKatiArgs(args []string) {
836 c.katiArgs = args
837}
838
839func (c *configImpl) SetNinjaArgs(args []string) {
840 c.ninjaArgs = args
841}
842
843func (c *configImpl) SetKatiSuffix(suffix string) {
844 c.katiSuffix = suffix
845}
846
Dan Willemsene0879fc2017-08-04 15:06:27 -0700847func (c *configImpl) LastKatiSuffixFile() string {
848 return filepath.Join(c.OutDir(), "last_kati_suffix")
849}
850
851func (c *configImpl) HasKatiSuffix() bool {
852 return c.katiSuffix != ""
853}
854
Dan Willemsen1e704462016-08-21 15:17:17 -0700855func (c *configImpl) KatiEnvFile() string {
856 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
857}
858
Dan Willemsen29971232018-09-26 14:58:30 -0700859func (c *configImpl) KatiBuildNinjaFile() string {
860 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -0700861}
862
Dan Willemsenfb1271a2018-09-26 15:00:42 -0700863func (c *configImpl) KatiPackageNinjaFile() string {
864 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
865}
866
Dan Willemsen1e704462016-08-21 15:17:17 -0700867func (c *configImpl) SoongNinjaFile() string {
868 return filepath.Join(c.SoongOutDir(), "build.ninja")
869}
870
871func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700872 if c.katiSuffix == "" {
873 return filepath.Join(c.OutDir(), "combined.ninja")
874 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700875 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
876}
877
878func (c *configImpl) SoongAndroidMk() string {
879 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
880}
881
882func (c *configImpl) SoongMakeVarsMk() string {
883 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
884}
885
Dan Willemsenf052f782017-05-18 15:29:04 -0700886func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -0700887 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -0700888}
889
Dan Willemsen02781d52017-05-12 19:28:13 -0700890func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -0700891 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
892}
893
Dan Willemsenfb1271a2018-09-26 15:00:42 -0700894func (c *configImpl) KatiPackageMkDir() string {
895 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
896}
897
Dan Willemsenf052f782017-05-18 15:29:04 -0700898func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -0700899 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -0700900}
901
902func (c *configImpl) HostOut() string {
903 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
904}
905
906// This probably needs to be multi-valued, so not exporting it for now
907func (c *configImpl) hostCrossOut() string {
908 if runtime.GOOS == "linux" {
909 return filepath.Join(c.hostOutRoot(), "windows-x86")
910 } else {
911 return ""
912 }
Dan Willemsen02781d52017-05-12 19:28:13 -0700913}
914
Dan Willemsen1e704462016-08-21 15:17:17 -0700915func (c *configImpl) HostPrebuiltTag() string {
916 if runtime.GOOS == "linux" {
917 return "linux-x86"
918 } else if runtime.GOOS == "darwin" {
919 return "darwin-x86"
920 } else {
921 panic("Unsupported OS")
922 }
923}
Dan Willemsenf173d592017-04-27 14:28:00 -0700924
Dan Willemsen8122bd52017-10-12 20:20:41 -0700925func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -0700926 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
927 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -0700928 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
929 if _, err := os.Stat(asan); err == nil {
930 return asan
931 }
Dan Willemsenf173d592017-04-27 14:28:00 -0700932 }
933 }
934 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
935}
Dan Willemsen3d60b112018-04-04 22:25:56 -0700936
937func (c *configImpl) SetBuildBrokenDupRules(val bool) {
938 c.brokenDupRules = val
939}
940
941func (c *configImpl) BuildBrokenDupRules() bool {
942 return c.brokenDupRules
943}
Dan Willemsen6ab79db2018-05-02 00:06:28 -0700944
Dan Willemsen25e6f092019-04-09 10:22:43 -0700945func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
946 c.brokenUsesNetwork = val
947}
948
949func (c *configImpl) BuildBrokenUsesNetwork() bool {
950 return c.brokenUsesNetwork
951}
952
Dan Willemsene3336352020-01-02 19:10:38 -0800953func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
954 c.brokenNinjaEnvVars = val
955}
956
957func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
958 return c.brokenNinjaEnvVars
959}
960
Dan Willemsen6ab79db2018-05-02 00:06:28 -0700961func (c *configImpl) SetTargetDeviceDir(dir string) {
962 c.targetDeviceDir = dir
963}
964
965func (c *configImpl) TargetDeviceDir() string {
966 return c.targetDeviceDir
967}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -0700968
Patrice Arruda219eef32020-06-01 17:29:30 +0000969func (c *configImpl) BuildDateTime() string {
970 return c.buildDateTime
971}
972
973func (c *configImpl) MetricsUploaderApp() string {
974 if p, ok := c.environ.Get("ANDROID_ENABLE_METRICS_UPLOAD"); ok {
975 return p
976 }
977 return ""
978}