blob: a60d70e138fa93cc238993f1c8a3291645bd2ecc [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 Willemsend8aa39d2018-08-27 15:01:03 -070056 pdkBuild bool
57
Dan Willemsene3336352020-01-02 19:10:38 -080058 brokenDupRules bool
59 brokenUsesNetwork bool
60 brokenNinjaEnvVars []string
Dan Willemsen18490112018-05-25 16:30:04 -070061
62 pathReplaced bool
Dan Willemsen1e704462016-08-21 15:17:17 -070063}
64
Dan Willemsenc2af0be2017-01-20 14:10:01 -080065const srcDirFileCheck = "build/soong/root.bp"
66
Patrice Arruda9450d0b2019-07-08 11:06:46 -070067var buildFiles = []string{"Android.mk", "Android.bp"}
68
Patrice Arruda13848222019-04-22 17:12:02 -070069type BuildAction uint
70
71const (
72 // Builds all of the modules and their dependencies of a specified directory, relative to the root
73 // directory of the source tree.
74 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
75
76 // Builds all of the modules and their dependencies of a list of specified directories. All specified
77 // directories are relative to the root directory of the source tree.
78 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -070079
80 // Build a list of specified modules. If none was specified, simply build the whole source tree.
81 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -070082)
83
84// checkTopDir validates that the current directory is at the root directory of the source tree.
85func checkTopDir(ctx Context) {
86 if _, err := os.Stat(srcDirFileCheck); err != nil {
87 if os.IsNotExist(err) {
88 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
89 }
90 ctx.Fatalln("Error verifying tree state:", err)
91 }
92}
93
Dan Willemsen1e704462016-08-21 15:17:17 -070094func NewConfig(ctx Context, args ...string) Config {
95 ret := &configImpl{
96 environ: OsEnvironment(),
97 }
98
Dan Willemsen9b587492017-07-10 22:13:00 -070099 // Sane default matching ninja
100 ret.parallel = runtime.NumCPU() + 2
101 ret.keepGoing = 1
102
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800103 ret.totalRAM = detectTotalRAM(ctx)
104
Dan Willemsen9b587492017-07-10 22:13:00 -0700105 ret.parseArgs(ctx, args)
106
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800107 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700108 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
109 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
110 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800111 outDir := "out"
112 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
113 if wd, err := os.Getwd(); err != nil {
114 ctx.Fatalln("Failed to get working directory:", err)
115 } else {
116 outDir = filepath.Join(baseDir, filepath.Base(wd))
117 }
118 }
119 ret.environ.Set("OUT_DIR", outDir)
120 }
121
Dan Willemsen2d31a442018-10-20 21:33:41 -0700122 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
123 ret.distDir = filepath.Clean(distDir)
124 } else {
125 ret.distDir = filepath.Join(ret.OutDir(), "dist")
126 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700127
Dan Willemsen1e704462016-08-21 15:17:17 -0700128 ret.environ.Unset(
129 // We're already using it
130 "USE_SOONG_UI",
131
132 // We should never use GOROOT/GOPATH from the shell environment
133 "GOROOT",
134 "GOPATH",
135
136 // These should only come from Soong, not the environment.
137 "CLANG",
138 "CLANG_CXX",
139 "CCC_CC",
140 "CCC_CXX",
141
142 // Used by the goma compiler wrapper, but should only be set by
143 // gomacc
144 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800145
146 // We handle this above
147 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700148
Dan Willemsen2d31a442018-10-20 21:33:41 -0700149 // This is handled above too, and set for individual commands later
150 "DIST_DIR",
151
Dan Willemsen68a09852017-04-18 13:56:57 -0700152 // Variables that have caused problems in the past
Dan Willemsen1c504d92019-11-18 19:13:53 +0000153 "BASH_ENV",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700154 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700155 "DISPLAY",
156 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700157 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700158 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700159
160 // Drop make flags
161 "MAKEFLAGS",
162 "MAKELEVEL",
163 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700164
165 // Set in envsetup.sh, reset in makefiles
166 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700167
168 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
169 "ANDROID_BUILD_TOP",
170 "ANDROID_HOST_OUT",
171 "ANDROID_PRODUCT_OUT",
172 "ANDROID_HOST_OUT_TESTCASES",
173 "ANDROID_TARGET_OUT_TESTCASES",
174 "ANDROID_TOOLCHAIN",
175 "ANDROID_TOOLCHAIN_2ND_ARCH",
176 "ANDROID_DEV_SCRIPTS",
177 "ANDROID_EMULATOR_PREBUILTS",
178 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsenf99915f2018-10-25 22:04:42 -0700179
180 // Only set in multiproduct_kati after config generation
181 "EMPTY_NINJA_FILE",
Dan Willemsen1e704462016-08-21 15:17:17 -0700182 )
183
184 // Tell python not to spam the source tree with .pyc files.
185 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
186
Dan Willemsen32a669b2018-03-08 19:42:00 -0800187 ret.environ.Set("TMPDIR", absPath(ctx, ret.TempDir()))
188
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700189 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
190 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
191 "llvm-binutils-stable/llvm-symbolizer")
192 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
193
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800194 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700195 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800196
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700197 if srcDir := absPath(ctx, "."); strings.ContainsRune(srcDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700198 ctx.Println("You are building in a directory whose absolute path contains a space character:")
199 ctx.Println()
200 ctx.Printf("%q\n", srcDir)
201 ctx.Println()
202 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700203 }
204
205 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700206 ctx.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
207 ctx.Println()
208 ctx.Printf("%q\n", outDir)
209 ctx.Println()
210 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700211 }
212
213 if distDir := ret.DistDir(); strings.ContainsRune(distDir, ' ') {
Colin Cross1f6faeb2019-09-23 15:52:40 -0700214 ctx.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
215 ctx.Println()
216 ctx.Printf("%q\n", distDir)
217 ctx.Println()
218 ctx.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700219 }
220
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700221 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000222 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
223 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Pete Gillin1f52e932019-10-09 17:10:08 +0100224 java11Home := filepath.Join("prebuilts/jdk/jdk11", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700225 javaHome := func() string {
226 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
227 return override
228 }
Pete Gillina7a3d642019-11-07 18:58:42 +0000229 if toolchain11, ok := ret.environ.Get("EXPERIMENTAL_USE_OPENJDK11_TOOLCHAIN"); ok && toolchain11 != "true" {
230 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 +0100231 }
Pete Gillinabbcdda2019-10-28 16:15:33 +0000232 return java11Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700233 }()
234 absJavaHome := absPath(ctx, javaHome)
235
Dan Willemsened869522018-01-08 14:58:46 -0800236 ret.configureLocale(ctx)
237
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700238 newPath := []string{filepath.Join(absJavaHome, "bin")}
239 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
240 newPath = append(newPath, path)
241 }
Pete Gillin1f52e932019-10-09 17:10:08 +0100242
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700243 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
244 ret.environ.Set("JAVA_HOME", absJavaHome)
245 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000246 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
247 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Pete Gillin1f52e932019-10-09 17:10:08 +0100248 ret.environ.Set("ANDROID_JAVA11_HOME", java11Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700249 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
250
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800251 outDir := ret.OutDir()
252 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800253 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
Colin Cross28f527c2019-11-26 16:19:04 -0800254 ret.buildDateTime = buildDateTime
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800255 } else {
Colin Cross28f527c2019-11-26 16:19:04 -0800256 ret.buildDateTime = strconv.FormatInt(time.Now().Unix(), 10)
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800257 }
Colin Cross28f527c2019-11-26 16:19:04 -0800258
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800259 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
260
Dan Willemsen9b587492017-07-10 22:13:00 -0700261 return Config{ret}
262}
263
Patrice Arruda13848222019-04-22 17:12:02 -0700264// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
265// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700266func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
267 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700268}
269
270// getConfigArgs processes the command arguments based on the build action and creates a set of new
271// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700272func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700273 // The next block of code verifies that the current directory is the root directory of the source
274 // tree. It then finds the relative path of dir based on the root directory of the source tree
275 // and verify that dir is inside of the source tree.
276 checkTopDir(ctx)
277 topDir, err := os.Getwd()
278 if err != nil {
279 ctx.Fatalf("Error retrieving top directory: %v", err)
280 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700281 dir, err = filepath.EvalSymlinks(dir)
282 if err != nil {
283 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
284 }
Patrice Arruda13848222019-04-22 17:12:02 -0700285 dir, err = filepath.Abs(dir)
286 if err != nil {
287 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
288 }
289 relDir, err := filepath.Rel(topDir, dir)
290 if err != nil {
291 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
292 }
293 // If there are ".." in the path, it's not in the source tree.
294 if strings.Contains(relDir, "..") {
295 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
296 }
297
298 configArgs := args[:]
299
300 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
301 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
302 targetNamePrefix := "MODULES-IN-"
303 if inList("GET-INSTALL-PATH", configArgs) {
304 targetNamePrefix = "GET-INSTALL-PATH-IN-"
305 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
306 }
307
Patrice Arruda13848222019-04-22 17:12:02 -0700308 var targets []string
309
310 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700311 case BUILD_MODULES:
312 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700313 case BUILD_MODULES_IN_A_DIRECTORY:
314 // If dir is the root source tree, all the modules are built of the source tree are built so
315 // no need to find the build file.
316 if topDir == dir {
317 break
318 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700319
Patrice Arruda13848222019-04-22 17:12:02 -0700320 buildFile := findBuildFile(ctx, relDir)
321 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700322 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700323 }
Patrice Arruda13848222019-04-22 17:12:02 -0700324 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
325 case BUILD_MODULES_IN_DIRECTORIES:
326 newConfigArgs, dirs := splitArgs(configArgs)
327 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700328 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700329 }
330
331 // Tidy only override all other specified targets.
332 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
333 if tidyOnly == "true" || tidyOnly == "1" {
334 configArgs = append(configArgs, "tidy_only")
335 } else {
336 configArgs = append(configArgs, targets...)
337 }
338
339 return configArgs
340}
341
342// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
343func convertToTarget(dir string, targetNamePrefix string) string {
344 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
345}
346
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700347// hasBuildFile returns true if dir contains an Android build file.
348func hasBuildFile(ctx Context, dir string) bool {
349 for _, buildFile := range buildFiles {
350 _, err := os.Stat(filepath.Join(dir, buildFile))
351 if err == nil {
352 return true
353 }
354 if !os.IsNotExist(err) {
355 ctx.Fatalf("Error retrieving the build file stats: %v", err)
356 }
357 }
358 return false
359}
360
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700361// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
362// in the current and any sub directory of dir. If a build file is not found, traverse the path
363// up by one directory and repeat again until either a build file is found or reached to the root
364// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
365// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700366func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700367 // If the string is empty or ".", assume it is top directory of the source tree.
368 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700369 return ""
370 }
371
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700372 found := false
373 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
374 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
375 if err != nil {
376 return err
377 }
378 if found {
379 return filepath.SkipDir
380 }
381 if info.IsDir() {
382 return nil
383 }
384 for _, buildFile := range buildFiles {
385 if info.Name() == buildFile {
386 found = true
387 return filepath.SkipDir
388 }
389 }
390 return nil
391 })
392 if err != nil {
393 ctx.Fatalf("Error finding Android build file: %v", err)
394 }
395
396 if found {
397 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700398 }
399 }
400
401 return ""
402}
403
404// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
405func splitArgs(args []string) (newArgs []string, dirs []string) {
406 specialArgs := map[string]bool{
407 "showcommands": true,
408 "snod": true,
409 "dist": true,
410 "checkbuild": true,
411 }
412
413 newArgs = []string{}
414 dirs = []string{}
415
416 for _, arg := range args {
417 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
418 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
419 newArgs = append(newArgs, arg)
420 continue
421 }
422
423 if _, ok := specialArgs[arg]; ok {
424 newArgs = append(newArgs, arg)
425 continue
426 }
427
428 dirs = append(dirs, arg)
429 }
430
431 return newArgs, dirs
432}
433
434// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
435// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
436// source root tree where the build action command was invoked. Each directory is validated if the
437// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700438func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700439 for _, dir := range dirs {
440 // The directory may have specified specific modules to build. ":" is the separator to separate
441 // the directory and the list of modules.
442 s := strings.Split(dir, ":")
443 l := len(s)
444 if l > 2 { // more than one ":" was specified.
445 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
446 }
447
448 dir = filepath.Join(relDir, s[0])
449 if _, err := os.Stat(dir); err != nil {
450 ctx.Fatalf("couldn't find directory %s", dir)
451 }
452
453 // Verify that if there are any targets specified after ":". Each target is separated by ",".
454 var newTargets []string
455 if l == 2 && s[1] != "" {
456 newTargets = strings.Split(s[1], ",")
457 if inList("", newTargets) {
458 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
459 }
460 }
461
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700462 // If there are specified targets to build in dir, an android build file must exist for the one
463 // shot build. For the non-targets case, find the appropriate build file and build all the
464 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700465 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700466 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700467 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
468 }
469 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700470 buildFile := findBuildFile(ctx, dir)
471 if buildFile == "" {
472 ctx.Fatalf("Build file not found for %s directory", dir)
473 }
474 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700475 }
476
Patrice Arruda13848222019-04-22 17:12:02 -0700477 targets = append(targets, newTargets...)
478 }
479
Dan Willemsence41e942019-07-29 23:39:30 -0700480 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700481}
482
Dan Willemsen9b587492017-07-10 22:13:00 -0700483func (c *configImpl) parseArgs(ctx Context, args []string) {
484 for i := 0; i < len(args); i++ {
485 arg := strings.TrimSpace(args[i])
Dan Willemsen1e704462016-08-21 15:17:17 -0700486 if arg == "--make-mode" {
Dan Willemsen1e704462016-08-21 15:17:17 -0700487 } else if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700488 c.verbose = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700489 } else if arg == "--skip-make" {
490 c.skipMake = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700491 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700492 parseArgNum := func(def int) int {
493 if len(arg) > 2 {
494 p, err := strconv.ParseUint(arg[2:], 10, 31)
495 if err != nil {
496 ctx.Fatalf("Failed to parse %q: %v", arg, err)
497 }
498 return int(p)
499 } else if i+1 < len(args) {
500 p, err := strconv.ParseUint(args[i+1], 10, 31)
501 if err == nil {
502 i++
503 return int(p)
504 }
505 }
506 return def
507 }
508
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700509 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700510 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700511 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700512 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700513 } else {
514 ctx.Fatalln("Unknown option:", arg)
515 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700516 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
Dan Willemsen6dfe30a2018-09-10 12:41:10 -0700517 if k == "OUT_DIR" {
518 ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
519 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700520 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700521 } else if arg == "dist" {
522 c.dist = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700523 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700524 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800525 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700526 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700527 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700528 }
529 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700530}
531
Dan Willemsened869522018-01-08 14:58:46 -0800532func (c *configImpl) configureLocale(ctx Context) {
533 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
534 output, err := cmd.Output()
535
536 var locales []string
537 if err == nil {
538 locales = strings.Split(string(output), "\n")
539 } else {
540 // If we're unable to list the locales, let's assume en_US.UTF-8
541 locales = []string{"en_US.UTF-8"}
542 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
543 }
544
545 // gettext uses LANGUAGE, which is passed directly through
546
547 // For LANG and LC_*, only preserve the evaluated version of
548 // LC_MESSAGES
549 user_lang := ""
550 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
551 user_lang = lc_all
552 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
553 user_lang = lc_messages
554 } else if lang, ok := c.environ.Get("LANG"); ok {
555 user_lang = lang
556 }
557
558 c.environ.UnsetWithPrefix("LC_")
559
560 if user_lang != "" {
561 c.environ.Set("LC_MESSAGES", user_lang)
562 }
563
564 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
565 // for others)
566 if inList("C.UTF-8", locales) {
567 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500568 } else if inList("C.utf8", locales) {
569 // These normalize to the same thing
570 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800571 } else if inList("en_US.UTF-8", locales) {
572 c.environ.Set("LANG", "en_US.UTF-8")
573 } else if inList("en_US.utf8", locales) {
574 // These normalize to the same thing
575 c.environ.Set("LANG", "en_US.UTF-8")
576 } else {
577 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
578 }
579}
580
Dan Willemsen1e704462016-08-21 15:17:17 -0700581// Lunch configures the environment for a specific product similarly to the
582// `lunch` bash function.
583func (c *configImpl) Lunch(ctx Context, product, variant string) {
584 if variant != "eng" && variant != "userdebug" && variant != "user" {
585 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
586 }
587
588 c.environ.Set("TARGET_PRODUCT", product)
589 c.environ.Set("TARGET_BUILD_VARIANT", variant)
590 c.environ.Set("TARGET_BUILD_TYPE", "release")
591 c.environ.Unset("TARGET_BUILD_APPS")
Martin Stjernholm08802332020-06-04 17:00:01 +0100592 c.environ.Unset("TARGET_BUILD_UNBUNDLED")
Dan Willemsen1e704462016-08-21 15:17:17 -0700593}
594
595// Tapas configures the environment to build one or more unbundled apps,
596// similarly to the `tapas` bash function.
597func (c *configImpl) Tapas(ctx Context, apps []string, arch, variant string) {
598 if len(apps) == 0 {
599 apps = []string{"all"}
600 }
601 if variant == "" {
602 variant = "eng"
603 }
604
605 if variant != "eng" && variant != "userdebug" && variant != "user" {
606 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
607 }
608
609 var product string
610 switch arch {
Dan Willemsen1e704462016-08-21 15:17:17 -0700611 case "arm", "":
612 product = "aosp_arm"
613 case "arm64":
614 product = "aosm_arm64"
Dan Willemsen1e704462016-08-21 15:17:17 -0700615 case "x86":
616 product = "aosp_x86"
617 case "x86_64":
618 product = "aosp_x86_64"
619 default:
620 ctx.Fatalf("Invalid architecture: %q", arch)
621 }
622
623 c.environ.Set("TARGET_PRODUCT", product)
624 c.environ.Set("TARGET_BUILD_VARIANT", variant)
625 c.environ.Set("TARGET_BUILD_TYPE", "release")
626 c.environ.Set("TARGET_BUILD_APPS", strings.Join(apps, " "))
627}
628
629func (c *configImpl) Environment() *Environment {
630 return c.environ
631}
632
633func (c *configImpl) Arguments() []string {
634 return c.arguments
635}
636
637func (c *configImpl) OutDir() string {
638 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700639 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700640 }
641 return "out"
642}
643
Dan Willemsen8a073a82017-02-04 17:30:44 -0800644func (c *configImpl) DistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700645 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800646}
647
Dan Willemsen1e704462016-08-21 15:17:17 -0700648func (c *configImpl) NinjaArgs() []string {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700649 if c.skipMake {
650 return c.arguments
651 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700652 return c.ninjaArgs
653}
654
655func (c *configImpl) SoongOutDir() string {
656 return filepath.Join(c.OutDir(), "soong")
657}
658
Jeff Gastonefc1b412017-03-29 17:29:06 -0700659func (c *configImpl) TempDir() string {
660 return shared.TempDirForOutDir(c.SoongOutDir())
661}
662
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700663func (c *configImpl) FileListDir() string {
664 return filepath.Join(c.OutDir(), ".module_paths")
665}
666
Dan Willemsen1e704462016-08-21 15:17:17 -0700667func (c *configImpl) KatiSuffix() string {
668 if c.katiSuffix != "" {
669 return c.katiSuffix
670 }
671 panic("SetKatiSuffix has not been called")
672}
673
Colin Cross37193492017-11-16 17:55:00 -0800674// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
675// user is interested in additional checks at the expense of build time.
676func (c *configImpl) Checkbuild() bool {
677 return c.checkbuild
678}
679
Dan Willemsen8a073a82017-02-04 17:30:44 -0800680func (c *configImpl) Dist() bool {
681 return c.dist
682}
683
Dan Willemsen1e704462016-08-21 15:17:17 -0700684func (c *configImpl) IsVerbose() bool {
685 return c.verbose
686}
687
Dan Willemsene0879fc2017-08-04 15:06:27 -0700688func (c *configImpl) SkipMake() bool {
689 return c.skipMake
690}
691
Dan Willemsen1e704462016-08-21 15:17:17 -0700692func (c *configImpl) TargetProduct() string {
693 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
694 return v
695 }
696 panic("TARGET_PRODUCT is not defined")
697}
698
Dan Willemsen02781d52017-05-12 19:28:13 -0700699func (c *configImpl) TargetDevice() string {
700 return c.targetDevice
701}
702
703func (c *configImpl) SetTargetDevice(device string) {
704 c.targetDevice = device
705}
706
707func (c *configImpl) TargetBuildVariant() string {
708 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
709 return v
710 }
711 panic("TARGET_BUILD_VARIANT is not defined")
712}
713
Dan Willemsen1e704462016-08-21 15:17:17 -0700714func (c *configImpl) KatiArgs() []string {
715 return c.katiArgs
716}
717
718func (c *configImpl) Parallel() int {
719 return c.parallel
720}
721
Colin Cross8b8bec32019-11-15 13:18:43 -0800722func (c *configImpl) HighmemParallel() int {
723 if i, ok := c.environ.GetInt("NINJA_HIGHMEM_NUM_JOBS"); ok {
724 return i
725 }
726
727 const minMemPerHighmemProcess = 8 * 1024 * 1024 * 1024
728 parallel := c.Parallel()
729 if c.UseRemoteBuild() {
730 // Ninja doesn't support nested pools, and when remote builds are enabled the total ninja parallelism
731 // is set very high (i.e. 500). Using a large value here would cause the total number of running jobs
732 // to be the sum of the sizes of the local and highmem pools, which will cause extra CPU contention.
733 // Return 1/16th of the size of the local pool, rounding up.
734 return (parallel + 15) / 16
735 } else if c.totalRAM == 0 {
736 // Couldn't detect the total RAM, don't restrict highmem processes.
737 return parallel
Dan Willemsen570a2922020-05-26 23:02:29 -0700738 } else if c.totalRAM <= 16*1024*1024*1024 {
739 // Less than 16GB of ram, restrict to 1 highmem processes
740 return 1
Colin Cross8b8bec32019-11-15 13:18:43 -0800741 } else if c.totalRAM <= 32*1024*1024*1024 {
742 // Less than 32GB of ram, restrict to 2 highmem processes
743 return 2
744 } else if p := int(c.totalRAM / minMemPerHighmemProcess); p < parallel {
745 // If less than 8GB total RAM per process, reduce the number of highmem processes
746 return p
747 }
748 // No restriction on highmem processes
749 return parallel
750}
751
Dan Willemsen2bb82d02019-12-27 09:35:42 -0800752func (c *configImpl) TotalRAM() uint64 {
753 return c.totalRAM
754}
755
Dan Willemsen1e704462016-08-21 15:17:17 -0700756func (c *configImpl) UseGoma() bool {
757 if v, ok := c.environ.Get("USE_GOMA"); ok {
758 v = strings.TrimSpace(v)
759 if v != "" && v != "false" {
760 return true
761 }
762 }
763 return false
764}
765
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +0900766func (c *configImpl) StartGoma() bool {
767 if !c.UseGoma() {
768 return false
769 }
770
771 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
772 v = strings.TrimSpace(v)
773 if v != "" && v != "false" {
774 return false
775 }
776 }
777 return true
778}
779
Ramy Medhatbbf25672019-07-17 12:30:04 +0000780func (c *configImpl) UseRBE() bool {
781 if v, ok := c.environ.Get("USE_RBE"); ok {
782 v = strings.TrimSpace(v)
783 if v != "" && v != "false" {
784 return true
785 }
786 }
787 return false
788}
789
790func (c *configImpl) StartRBE() bool {
791 if !c.UseRBE() {
792 return false
793 }
794
795 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
796 v = strings.TrimSpace(v)
797 if v != "" && v != "false" {
798 return false
799 }
800 }
801 return true
802}
803
Patrice Arruda62f1bf22020-07-07 12:48:26 +0000804func (c *configImpl) RBEStatsOutputDir() string {
805 for _, f := range []string{"RBE_output_dir", "FLAG_output_dir"} {
806 if v, ok := c.environ.Get(f); ok {
807 return v
808 }
809 }
810 return ""
811}
812
Colin Cross9016b912019-11-11 14:57:42 -0800813func (c *configImpl) UseRemoteBuild() bool {
814 return c.UseGoma() || c.UseRBE()
815}
816
Dan Willemsen1e704462016-08-21 15:17:17 -0700817// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -0700818// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -0700819// still limited by Parallel()
820func (c *configImpl) RemoteParallel() int {
Colin Cross8b8bec32019-11-15 13:18:43 -0800821 if !c.UseRemoteBuild() {
822 return 0
823 }
824 if i, ok := c.environ.GetInt("NINJA_REMOTE_NUM_JOBS"); ok {
825 return i
Dan Willemsen1e704462016-08-21 15:17:17 -0700826 }
827 return 500
828}
829
830func (c *configImpl) SetKatiArgs(args []string) {
831 c.katiArgs = args
832}
833
834func (c *configImpl) SetNinjaArgs(args []string) {
835 c.ninjaArgs = args
836}
837
838func (c *configImpl) SetKatiSuffix(suffix string) {
839 c.katiSuffix = suffix
840}
841
Dan Willemsene0879fc2017-08-04 15:06:27 -0700842func (c *configImpl) LastKatiSuffixFile() string {
843 return filepath.Join(c.OutDir(), "last_kati_suffix")
844}
845
846func (c *configImpl) HasKatiSuffix() bool {
847 return c.katiSuffix != ""
848}
849
Dan Willemsen1e704462016-08-21 15:17:17 -0700850func (c *configImpl) KatiEnvFile() string {
851 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
852}
853
Dan Willemsen29971232018-09-26 14:58:30 -0700854func (c *configImpl) KatiBuildNinjaFile() string {
855 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -0700856}
857
Dan Willemsenfb1271a2018-09-26 15:00:42 -0700858func (c *configImpl) KatiPackageNinjaFile() string {
859 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
860}
861
Dan Willemsen1e704462016-08-21 15:17:17 -0700862func (c *configImpl) SoongNinjaFile() string {
863 return filepath.Join(c.SoongOutDir(), "build.ninja")
864}
865
866func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700867 if c.katiSuffix == "" {
868 return filepath.Join(c.OutDir(), "combined.ninja")
869 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700870 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
871}
872
873func (c *configImpl) SoongAndroidMk() string {
874 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
875}
876
877func (c *configImpl) SoongMakeVarsMk() string {
878 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
879}
880
Dan Willemsenf052f782017-05-18 15:29:04 -0700881func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -0700882 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -0700883}
884
Dan Willemsen02781d52017-05-12 19:28:13 -0700885func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -0700886 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
887}
888
Dan Willemsenfb1271a2018-09-26 15:00:42 -0700889func (c *configImpl) KatiPackageMkDir() string {
890 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
891}
892
Dan Willemsenf052f782017-05-18 15:29:04 -0700893func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -0700894 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -0700895}
896
897func (c *configImpl) HostOut() string {
898 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
899}
900
901// This probably needs to be multi-valued, so not exporting it for now
902func (c *configImpl) hostCrossOut() string {
903 if runtime.GOOS == "linux" {
904 return filepath.Join(c.hostOutRoot(), "windows-x86")
905 } else {
906 return ""
907 }
Dan Willemsen02781d52017-05-12 19:28:13 -0700908}
909
Dan Willemsen1e704462016-08-21 15:17:17 -0700910func (c *configImpl) HostPrebuiltTag() string {
911 if runtime.GOOS == "linux" {
912 return "linux-x86"
913 } else if runtime.GOOS == "darwin" {
914 return "darwin-x86"
915 } else {
916 panic("Unsupported OS")
917 }
918}
Dan Willemsenf173d592017-04-27 14:28:00 -0700919
Dan Willemsen8122bd52017-10-12 20:20:41 -0700920func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -0700921 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
922 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -0700923 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
924 if _, err := os.Stat(asan); err == nil {
925 return asan
926 }
Dan Willemsenf173d592017-04-27 14:28:00 -0700927 }
928 }
929 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
930}
Dan Willemsen3d60b112018-04-04 22:25:56 -0700931
932func (c *configImpl) SetBuildBrokenDupRules(val bool) {
933 c.brokenDupRules = val
934}
935
936func (c *configImpl) BuildBrokenDupRules() bool {
937 return c.brokenDupRules
938}
Dan Willemsen6ab79db2018-05-02 00:06:28 -0700939
Dan Willemsen25e6f092019-04-09 10:22:43 -0700940func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
941 c.brokenUsesNetwork = val
942}
943
944func (c *configImpl) BuildBrokenUsesNetwork() bool {
945 return c.brokenUsesNetwork
946}
947
Dan Willemsene3336352020-01-02 19:10:38 -0800948func (c *configImpl) SetBuildBrokenNinjaUsesEnvVars(val []string) {
949 c.brokenNinjaEnvVars = val
950}
951
952func (c *configImpl) BuildBrokenNinjaUsesEnvVars() []string {
953 return c.brokenNinjaEnvVars
954}
955
Dan Willemsen6ab79db2018-05-02 00:06:28 -0700956func (c *configImpl) SetTargetDeviceDir(dir string) {
957 c.targetDeviceDir = dir
958}
959
960func (c *configImpl) TargetDeviceDir() string {
961 return c.targetDeviceDir
962}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -0700963
964func (c *configImpl) SetPdkBuild(pdk bool) {
965 c.pdkBuild = pdk
966}
967
968func (c *configImpl) IsPdkBuild() bool {
969 return c.pdkBuild
970}
Patrice Arruda219eef32020-06-01 17:29:30 +0000971
972func (c *configImpl) BuildDateTime() string {
973 return c.buildDateTime
974}
975
976func (c *configImpl) MetricsUploaderApp() string {
977 if p, ok := c.environ.Get("ANDROID_ENABLE_METRICS_UPLOAD"); ok {
978 return p
979 }
980 return ""
981}