blob: 665d2f0fa901d60ea2a89be596791a2a94de9425 [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 (
Nan Zhang2e6a4ff2018-02-14 13:27:26 -080018 "io/ioutil"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080019 "log"
20 "os"
Dan Willemsen1e704462016-08-21 15:17:17 -070021 "path/filepath"
22 "runtime"
23 "strconv"
24 "strings"
Nan Zhang2e6a4ff2018-02-14 13:27:26 -080025 "time"
Jeff Gastonefc1b412017-03-29 17:29:06 -070026
27 "android/soong/shared"
Dan Willemsen1e704462016-08-21 15:17:17 -070028)
29
30type Config struct{ *configImpl }
31
32type configImpl struct {
33 // From the environment
34 arguments []string
35 goma bool
36 environ *Environment
Dan Willemsen2d31a442018-10-20 21:33:41 -070037 distDir string
Dan Willemsen1e704462016-08-21 15:17:17 -070038
39 // From the arguments
Colin Cross37193492017-11-16 17:55:00 -080040 parallel int
41 keepGoing int
42 verbose bool
43 checkbuild bool
44 dist bool
45 skipMake bool
Dan Willemsen1e704462016-08-21 15:17:17 -070046
47 // From the product config
Dan Willemsen6ab79db2018-05-02 00:06:28 -070048 katiArgs []string
49 ninjaArgs []string
50 katiSuffix string
51 targetDevice string
52 targetDeviceDir string
Dan Willemsen3d60b112018-04-04 22:25:56 -070053
Dan Willemsend8aa39d2018-08-27 15:01:03 -070054 pdkBuild bool
55
Dan Willemsen60977462019-04-18 09:40:15 -070056 brokenDupRules bool
57 brokenUsesNetwork bool
Dan Willemsen18490112018-05-25 16:30:04 -070058
59 pathReplaced bool
Dan Willemsen1e704462016-08-21 15:17:17 -070060}
61
Dan Willemsenc2af0be2017-01-20 14:10:01 -080062const srcDirFileCheck = "build/soong/root.bp"
63
Patrice Arruda9450d0b2019-07-08 11:06:46 -070064var buildFiles = []string{"Android.mk", "Android.bp"}
65
Patrice Arruda13848222019-04-22 17:12:02 -070066type BuildAction uint
67
68const (
69 // Builds all of the modules and their dependencies of a specified directory, relative to the root
70 // directory of the source tree.
71 BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
72
73 // Builds all of the modules and their dependencies of a list of specified directories. All specified
74 // directories are relative to the root directory of the source tree.
75 BUILD_MODULES_IN_DIRECTORIES
Patrice Arruda39282062019-06-20 16:35:12 -070076
77 // Build a list of specified modules. If none was specified, simply build the whole source tree.
78 BUILD_MODULES
Patrice Arruda13848222019-04-22 17:12:02 -070079)
80
81// checkTopDir validates that the current directory is at the root directory of the source tree.
82func checkTopDir(ctx Context) {
83 if _, err := os.Stat(srcDirFileCheck); err != nil {
84 if os.IsNotExist(err) {
85 ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
86 }
87 ctx.Fatalln("Error verifying tree state:", err)
88 }
89}
90
Dan Willemsen1e704462016-08-21 15:17:17 -070091func NewConfig(ctx Context, args ...string) Config {
92 ret := &configImpl{
93 environ: OsEnvironment(),
94 }
95
Dan Willemsen9b587492017-07-10 22:13:00 -070096 // Sane default matching ninja
97 ret.parallel = runtime.NumCPU() + 2
98 ret.keepGoing = 1
99
100 ret.parseArgs(ctx, args)
101
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800102 // Make sure OUT_DIR is set appropriately
Dan Willemsen02f3add2017-05-12 13:50:19 -0700103 if outDir, ok := ret.environ.Get("OUT_DIR"); ok {
104 ret.environ.Set("OUT_DIR", filepath.Clean(outDir))
105 } else {
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800106 outDir := "out"
107 if baseDir, ok := ret.environ.Get("OUT_DIR_COMMON_BASE"); ok {
108 if wd, err := os.Getwd(); err != nil {
109 ctx.Fatalln("Failed to get working directory:", err)
110 } else {
111 outDir = filepath.Join(baseDir, filepath.Base(wd))
112 }
113 }
114 ret.environ.Set("OUT_DIR", outDir)
115 }
116
Dan Willemsen2d31a442018-10-20 21:33:41 -0700117 if distDir, ok := ret.environ.Get("DIST_DIR"); ok {
118 ret.distDir = filepath.Clean(distDir)
119 } else {
120 ret.distDir = filepath.Join(ret.OutDir(), "dist")
121 }
Dan Willemsend50e89f2018-10-16 17:49:25 -0700122
Dan Willemsen1e704462016-08-21 15:17:17 -0700123 ret.environ.Unset(
124 // We're already using it
125 "USE_SOONG_UI",
126
127 // We should never use GOROOT/GOPATH from the shell environment
128 "GOROOT",
129 "GOPATH",
130
131 // These should only come from Soong, not the environment.
132 "CLANG",
133 "CLANG_CXX",
134 "CCC_CC",
135 "CCC_CXX",
136
137 // Used by the goma compiler wrapper, but should only be set by
138 // gomacc
139 "GOMACC_PATH",
Dan Willemsen0c3919e2017-03-02 15:49:10 -0800140
141 // We handle this above
142 "OUT_DIR_COMMON_BASE",
Dan Willemsen68a09852017-04-18 13:56:57 -0700143
Dan Willemsen2d31a442018-10-20 21:33:41 -0700144 // This is handled above too, and set for individual commands later
145 "DIST_DIR",
146
Dan Willemsen68a09852017-04-18 13:56:57 -0700147 // Variables that have caused problems in the past
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700148 "CDPATH",
Dan Willemsen68a09852017-04-18 13:56:57 -0700149 "DISPLAY",
150 "GREP_OPTIONS",
Dan Willemsenebfe33a2018-05-01 10:07:50 -0700151 "NDK_ROOT",
Dan Willemsen00fcb262018-08-15 15:35:38 -0700152 "POSIXLY_CORRECT",
Dan Willemsenc40e10b2017-07-11 14:30:00 -0700153
154 // Drop make flags
155 "MAKEFLAGS",
156 "MAKELEVEL",
157 "MFLAGS",
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700158
159 // Set in envsetup.sh, reset in makefiles
160 "ANDROID_JAVA_TOOLCHAIN",
Colin Cross7f09c402018-07-11 14:49:31 -0700161
162 // Set by envsetup.sh, but shouldn't be used inside the build because envsetup.sh is optional
163 "ANDROID_BUILD_TOP",
164 "ANDROID_HOST_OUT",
165 "ANDROID_PRODUCT_OUT",
166 "ANDROID_HOST_OUT_TESTCASES",
167 "ANDROID_TARGET_OUT_TESTCASES",
168 "ANDROID_TOOLCHAIN",
169 "ANDROID_TOOLCHAIN_2ND_ARCH",
170 "ANDROID_DEV_SCRIPTS",
171 "ANDROID_EMULATOR_PREBUILTS",
172 "ANDROID_PRE_BUILD_PATHS",
Dan Willemsenf99915f2018-10-25 22:04:42 -0700173
174 // Only set in multiproduct_kati after config generation
175 "EMPTY_NINJA_FILE",
Dan Willemsen1e704462016-08-21 15:17:17 -0700176 )
177
178 // Tell python not to spam the source tree with .pyc files.
179 ret.environ.Set("PYTHONDONTWRITEBYTECODE", "1")
180
Dan Willemsen32a669b2018-03-08 19:42:00 -0800181 ret.environ.Set("TMPDIR", absPath(ctx, ret.TempDir()))
182
Dan Willemsen70c1ff82019-08-21 14:56:13 -0700183 // Always set ASAN_SYMBOLIZER_PATH so that ASAN-based tools can symbolize any crashes
184 symbolizerPath := filepath.Join("prebuilts/clang/host", ret.HostPrebuiltTag(),
185 "llvm-binutils-stable/llvm-symbolizer")
186 ret.environ.Set("ASAN_SYMBOLIZER_PATH", absPath(ctx, symbolizerPath))
187
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800188 // Precondition: the current directory is the top of the source tree
Patrice Arruda13848222019-04-22 17:12:02 -0700189 checkTopDir(ctx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800190
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700191 if srcDir := absPath(ctx, "."); strings.ContainsRune(srcDir, ' ') {
192 log.Println("You are building in a directory whose absolute path contains a space character:")
193 log.Println()
194 log.Printf("%q\n", srcDir)
195 log.Println()
196 log.Fatalln("Directory names containing spaces are not supported")
Dan Willemsendb8457c2017-05-12 16:38:17 -0700197 }
198
199 if outDir := ret.OutDir(); strings.ContainsRune(outDir, ' ') {
200 log.Println("The absolute path of your output directory ($OUT_DIR) contains a space character:")
201 log.Println()
202 log.Printf("%q\n", outDir)
203 log.Println()
204 log.Fatalln("Directory names containing spaces are not supported")
205 }
206
207 if distDir := ret.DistDir(); strings.ContainsRune(distDir, ' ') {
208 log.Println("The absolute path of your dist directory ($DIST_DIR) contains a space character:")
209 log.Println()
210 log.Printf("%q\n", distDir)
211 log.Println()
212 log.Fatalln("Directory names containing spaces are not supported")
213 }
214
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700215 // Configure Java-related variables, including adding it to $PATH
Tobias Thierere59aeff2017-12-20 22:40:39 +0000216 java8Home := filepath.Join("prebuilts/jdk/jdk8", ret.HostPrebuiltTag())
217 java9Home := filepath.Join("prebuilts/jdk/jdk9", ret.HostPrebuiltTag())
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700218 javaHome := func() string {
219 if override, ok := ret.environ.Get("OVERRIDE_ANDROID_JAVA_HOME"); ok {
220 return override
221 }
Colin Cross997262f2018-06-19 22:49:39 -0700222 return java9Home
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700223 }()
224 absJavaHome := absPath(ctx, javaHome)
225
Dan Willemsened869522018-01-08 14:58:46 -0800226 ret.configureLocale(ctx)
227
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700228 newPath := []string{filepath.Join(absJavaHome, "bin")}
229 if path, ok := ret.environ.Get("PATH"); ok && path != "" {
230 newPath = append(newPath, path)
231 }
232 ret.environ.Unset("OVERRIDE_ANDROID_JAVA_HOME")
233 ret.environ.Set("JAVA_HOME", absJavaHome)
234 ret.environ.Set("ANDROID_JAVA_HOME", javaHome)
Tobias Thierere59aeff2017-12-20 22:40:39 +0000235 ret.environ.Set("ANDROID_JAVA8_HOME", java8Home)
236 ret.environ.Set("ANDROID_JAVA9_HOME", java9Home)
Dan Willemsend9e8f0a2017-10-30 13:42:06 -0700237 ret.environ.Set("PATH", strings.Join(newPath, string(filepath.ListSeparator)))
238
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800239 outDir := ret.OutDir()
240 buildDateTimeFile := filepath.Join(outDir, "build_date.txt")
241 var content string
242 if buildDateTime, ok := ret.environ.Get("BUILD_DATETIME"); ok && buildDateTime != "" {
243 content = buildDateTime
244 } else {
245 content = strconv.FormatInt(time.Now().Unix(), 10)
246 }
Nan Zhang17f27672018-12-12 16:01:49 -0800247 if ctx.Metrics != nil {
248 ctx.Metrics.SetBuildDateTime(content)
249 }
Nan Zhang2e6a4ff2018-02-14 13:27:26 -0800250 err := ioutil.WriteFile(buildDateTimeFile, []byte(content), 0777)
251 if err != nil {
252 ctx.Fatalln("Failed to write BUILD_DATETIME to file:", err)
253 }
254 ret.environ.Set("BUILD_DATETIME_FILE", buildDateTimeFile)
255
Dan Willemsen9b587492017-07-10 22:13:00 -0700256 return Config{ret}
257}
258
Patrice Arruda13848222019-04-22 17:12:02 -0700259// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
260// processed based on the build action and extracts any arguments that belongs to the build action.
Dan Willemsence41e942019-07-29 23:39:30 -0700261func NewBuildActionConfig(action BuildAction, dir string, ctx Context, args ...string) Config {
262 return NewConfig(ctx, getConfigArgs(action, dir, ctx, args)...)
Patrice Arruda13848222019-04-22 17:12:02 -0700263}
264
265// getConfigArgs processes the command arguments based on the build action and creates a set of new
266// arguments to be accepted by Config.
Dan Willemsence41e942019-07-29 23:39:30 -0700267func getConfigArgs(action BuildAction, dir string, ctx Context, args []string) []string {
Patrice Arruda13848222019-04-22 17:12:02 -0700268 // The next block of code verifies that the current directory is the root directory of the source
269 // tree. It then finds the relative path of dir based on the root directory of the source tree
270 // and verify that dir is inside of the source tree.
271 checkTopDir(ctx)
272 topDir, err := os.Getwd()
273 if err != nil {
274 ctx.Fatalf("Error retrieving top directory: %v", err)
275 }
Patrice Arrudababa9a92019-07-03 10:47:34 -0700276 dir, err = filepath.EvalSymlinks(dir)
277 if err != nil {
278 ctx.Fatalf("Unable to evaluate symlink of %s: %v", dir, err)
279 }
Patrice Arruda13848222019-04-22 17:12:02 -0700280 dir, err = filepath.Abs(dir)
281 if err != nil {
282 ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
283 }
284 relDir, err := filepath.Rel(topDir, dir)
285 if err != nil {
286 ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
287 }
288 // If there are ".." in the path, it's not in the source tree.
289 if strings.Contains(relDir, "..") {
290 ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
291 }
292
293 configArgs := args[:]
294
295 // If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
296 // GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
297 targetNamePrefix := "MODULES-IN-"
298 if inList("GET-INSTALL-PATH", configArgs) {
299 targetNamePrefix = "GET-INSTALL-PATH-IN-"
300 configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
301 }
302
Patrice Arruda13848222019-04-22 17:12:02 -0700303 var targets []string
304
305 switch action {
Patrice Arruda39282062019-06-20 16:35:12 -0700306 case BUILD_MODULES:
307 // No additional processing is required when building a list of specific modules or all modules.
Patrice Arruda13848222019-04-22 17:12:02 -0700308 case BUILD_MODULES_IN_A_DIRECTORY:
309 // If dir is the root source tree, all the modules are built of the source tree are built so
310 // no need to find the build file.
311 if topDir == dir {
312 break
313 }
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700314
Patrice Arruda13848222019-04-22 17:12:02 -0700315 buildFile := findBuildFile(ctx, relDir)
316 if buildFile == "" {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700317 ctx.Fatalf("Build file not found for %s directory", relDir)
Patrice Arruda13848222019-04-22 17:12:02 -0700318 }
Patrice Arruda13848222019-04-22 17:12:02 -0700319 targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
320 case BUILD_MODULES_IN_DIRECTORIES:
321 newConfigArgs, dirs := splitArgs(configArgs)
322 configArgs = newConfigArgs
Dan Willemsence41e942019-07-29 23:39:30 -0700323 targets = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
Patrice Arruda13848222019-04-22 17:12:02 -0700324 }
325
326 // Tidy only override all other specified targets.
327 tidyOnly := os.Getenv("WITH_TIDY_ONLY")
328 if tidyOnly == "true" || tidyOnly == "1" {
329 configArgs = append(configArgs, "tidy_only")
330 } else {
331 configArgs = append(configArgs, targets...)
332 }
333
334 return configArgs
335}
336
337// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
338func convertToTarget(dir string, targetNamePrefix string) string {
339 return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
340}
341
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700342// hasBuildFile returns true if dir contains an Android build file.
343func hasBuildFile(ctx Context, dir string) bool {
344 for _, buildFile := range buildFiles {
345 _, err := os.Stat(filepath.Join(dir, buildFile))
346 if err == nil {
347 return true
348 }
349 if !os.IsNotExist(err) {
350 ctx.Fatalf("Error retrieving the build file stats: %v", err)
351 }
352 }
353 return false
354}
355
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700356// findBuildFile finds a build file (makefile or blueprint file) by looking if there is a build file
357// in the current and any sub directory of dir. If a build file is not found, traverse the path
358// up by one directory and repeat again until either a build file is found or reached to the root
359// source tree. The returned filename of build file is "Android.mk". If one was not found, a blank
360// string is returned.
Patrice Arruda13848222019-04-22 17:12:02 -0700361func findBuildFile(ctx Context, dir string) string {
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700362 // If the string is empty or ".", assume it is top directory of the source tree.
363 if dir == "" || dir == "." {
Patrice Arruda13848222019-04-22 17:12:02 -0700364 return ""
365 }
366
Patrice Arruda0dcf27f2019-07-08 17:03:33 -0700367 found := false
368 for buildDir := dir; buildDir != "."; buildDir = filepath.Dir(buildDir) {
369 err := filepath.Walk(buildDir, func(path string, info os.FileInfo, err error) error {
370 if err != nil {
371 return err
372 }
373 if found {
374 return filepath.SkipDir
375 }
376 if info.IsDir() {
377 return nil
378 }
379 for _, buildFile := range buildFiles {
380 if info.Name() == buildFile {
381 found = true
382 return filepath.SkipDir
383 }
384 }
385 return nil
386 })
387 if err != nil {
388 ctx.Fatalf("Error finding Android build file: %v", err)
389 }
390
391 if found {
392 return filepath.Join(buildDir, "Android.mk")
Patrice Arruda13848222019-04-22 17:12:02 -0700393 }
394 }
395
396 return ""
397}
398
399// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
400func splitArgs(args []string) (newArgs []string, dirs []string) {
401 specialArgs := map[string]bool{
402 "showcommands": true,
403 "snod": true,
404 "dist": true,
405 "checkbuild": true,
406 }
407
408 newArgs = []string{}
409 dirs = []string{}
410
411 for _, arg := range args {
412 // It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
413 if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
414 newArgs = append(newArgs, arg)
415 continue
416 }
417
418 if _, ok := specialArgs[arg]; ok {
419 newArgs = append(newArgs, arg)
420 continue
421 }
422
423 dirs = append(dirs, arg)
424 }
425
426 return newArgs, dirs
427}
428
429// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
430// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
431// source root tree where the build action command was invoked. Each directory is validated if the
432// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
Dan Willemsence41e942019-07-29 23:39:30 -0700433func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string) {
Patrice Arruda13848222019-04-22 17:12:02 -0700434 for _, dir := range dirs {
435 // The directory may have specified specific modules to build. ":" is the separator to separate
436 // the directory and the list of modules.
437 s := strings.Split(dir, ":")
438 l := len(s)
439 if l > 2 { // more than one ":" was specified.
440 ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
441 }
442
443 dir = filepath.Join(relDir, s[0])
444 if _, err := os.Stat(dir); err != nil {
445 ctx.Fatalf("couldn't find directory %s", dir)
446 }
447
448 // Verify that if there are any targets specified after ":". Each target is separated by ",".
449 var newTargets []string
450 if l == 2 && s[1] != "" {
451 newTargets = strings.Split(s[1], ",")
452 if inList("", newTargets) {
453 ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
454 }
455 }
456
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700457 // If there are specified targets to build in dir, an android build file must exist for the one
458 // shot build. For the non-targets case, find the appropriate build file and build all the
459 // modules in dir (or the closest one in the dir path).
Patrice Arruda13848222019-04-22 17:12:02 -0700460 if len(newTargets) > 0 {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700461 if !hasBuildFile(ctx, dir) {
Patrice Arruda13848222019-04-22 17:12:02 -0700462 ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
463 }
464 } else {
Patrice Arruda9450d0b2019-07-08 11:06:46 -0700465 buildFile := findBuildFile(ctx, dir)
466 if buildFile == "" {
467 ctx.Fatalf("Build file not found for %s directory", dir)
468 }
469 newTargets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
Patrice Arruda13848222019-04-22 17:12:02 -0700470 }
471
Patrice Arruda13848222019-04-22 17:12:02 -0700472 targets = append(targets, newTargets...)
473 }
474
Dan Willemsence41e942019-07-29 23:39:30 -0700475 return targets
Patrice Arruda13848222019-04-22 17:12:02 -0700476}
477
Dan Willemsen9b587492017-07-10 22:13:00 -0700478func (c *configImpl) parseArgs(ctx Context, args []string) {
479 for i := 0; i < len(args); i++ {
480 arg := strings.TrimSpace(args[i])
Dan Willemsen1e704462016-08-21 15:17:17 -0700481 if arg == "--make-mode" {
Dan Willemsen1e704462016-08-21 15:17:17 -0700482 } else if arg == "showcommands" {
Dan Willemsen9b587492017-07-10 22:13:00 -0700483 c.verbose = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700484 } else if arg == "--skip-make" {
485 c.skipMake = true
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700486 } else if len(arg) > 0 && arg[0] == '-' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700487 parseArgNum := func(def int) int {
488 if len(arg) > 2 {
489 p, err := strconv.ParseUint(arg[2:], 10, 31)
490 if err != nil {
491 ctx.Fatalf("Failed to parse %q: %v", arg, err)
492 }
493 return int(p)
494 } else if i+1 < len(args) {
495 p, err := strconv.ParseUint(args[i+1], 10, 31)
496 if err == nil {
497 i++
498 return int(p)
499 }
500 }
501 return def
502 }
503
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700504 if len(arg) > 1 && arg[1] == 'j' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700505 c.parallel = parseArgNum(c.parallel)
Dan Willemsen6ac63ef2017-10-17 20:35:34 -0700506 } else if len(arg) > 1 && arg[1] == 'k' {
Dan Willemsen9b587492017-07-10 22:13:00 -0700507 c.keepGoing = parseArgNum(0)
Dan Willemsen1e704462016-08-21 15:17:17 -0700508 } else {
509 ctx.Fatalln("Unknown option:", arg)
510 }
Dan Willemsen091525e2017-07-11 14:17:50 -0700511 } else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
512 c.environ.Set(k, v)
Dan Willemsen2d31a442018-10-20 21:33:41 -0700513 } else if arg == "dist" {
514 c.dist = true
Dan Willemsen1e704462016-08-21 15:17:17 -0700515 } else {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700516 if arg == "checkbuild" {
Colin Cross37193492017-11-16 17:55:00 -0800517 c.checkbuild = true
Dan Willemsene0879fc2017-08-04 15:06:27 -0700518 }
Dan Willemsen9b587492017-07-10 22:13:00 -0700519 c.arguments = append(c.arguments, arg)
Dan Willemsen1e704462016-08-21 15:17:17 -0700520 }
521 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700522}
523
Dan Willemsened869522018-01-08 14:58:46 -0800524func (c *configImpl) configureLocale(ctx Context) {
525 cmd := Command(ctx, Config{c}, "locale", "locale", "-a")
526 output, err := cmd.Output()
527
528 var locales []string
529 if err == nil {
530 locales = strings.Split(string(output), "\n")
531 } else {
532 // If we're unable to list the locales, let's assume en_US.UTF-8
533 locales = []string{"en_US.UTF-8"}
534 ctx.Verbosef("Failed to list locales (%q), falling back to %q", err, locales)
535 }
536
537 // gettext uses LANGUAGE, which is passed directly through
538
539 // For LANG and LC_*, only preserve the evaluated version of
540 // LC_MESSAGES
541 user_lang := ""
542 if lc_all, ok := c.environ.Get("LC_ALL"); ok {
543 user_lang = lc_all
544 } else if lc_messages, ok := c.environ.Get("LC_MESSAGES"); ok {
545 user_lang = lc_messages
546 } else if lang, ok := c.environ.Get("LANG"); ok {
547 user_lang = lang
548 }
549
550 c.environ.UnsetWithPrefix("LC_")
551
552 if user_lang != "" {
553 c.environ.Set("LC_MESSAGES", user_lang)
554 }
555
556 // The for LANG, use C.UTF-8 if it exists (Debian currently, proposed
557 // for others)
558 if inList("C.UTF-8", locales) {
559 c.environ.Set("LANG", "C.UTF-8")
Aaron Klingd236e0e2018-08-07 19:21:36 -0500560 } else if inList("C.utf8", locales) {
561 // These normalize to the same thing
562 c.environ.Set("LANG", "C.UTF-8")
Dan Willemsened869522018-01-08 14:58:46 -0800563 } else if inList("en_US.UTF-8", locales) {
564 c.environ.Set("LANG", "en_US.UTF-8")
565 } else if inList("en_US.utf8", locales) {
566 // These normalize to the same thing
567 c.environ.Set("LANG", "en_US.UTF-8")
568 } else {
569 ctx.Fatalln("System doesn't support either C.UTF-8 or en_US.UTF-8")
570 }
571}
572
Dan Willemsen1e704462016-08-21 15:17:17 -0700573// Lunch configures the environment for a specific product similarly to the
574// `lunch` bash function.
575func (c *configImpl) Lunch(ctx Context, product, variant string) {
576 if variant != "eng" && variant != "userdebug" && variant != "user" {
577 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
578 }
579
580 c.environ.Set("TARGET_PRODUCT", product)
581 c.environ.Set("TARGET_BUILD_VARIANT", variant)
582 c.environ.Set("TARGET_BUILD_TYPE", "release")
583 c.environ.Unset("TARGET_BUILD_APPS")
584}
585
586// Tapas configures the environment to build one or more unbundled apps,
587// similarly to the `tapas` bash function.
588func (c *configImpl) Tapas(ctx Context, apps []string, arch, variant string) {
589 if len(apps) == 0 {
590 apps = []string{"all"}
591 }
592 if variant == "" {
593 variant = "eng"
594 }
595
596 if variant != "eng" && variant != "userdebug" && variant != "user" {
597 ctx.Fatalf("Invalid variant %q. Must be one of 'user', 'userdebug' or 'eng'", variant)
598 }
599
600 var product string
601 switch arch {
Dan Willemsen1e704462016-08-21 15:17:17 -0700602 case "arm", "":
603 product = "aosp_arm"
604 case "arm64":
605 product = "aosm_arm64"
606 case "mips":
607 product = "aosp_mips"
608 case "mips64":
609 product = "aosp_mips64"
610 case "x86":
611 product = "aosp_x86"
612 case "x86_64":
613 product = "aosp_x86_64"
614 default:
615 ctx.Fatalf("Invalid architecture: %q", arch)
616 }
617
618 c.environ.Set("TARGET_PRODUCT", product)
619 c.environ.Set("TARGET_BUILD_VARIANT", variant)
620 c.environ.Set("TARGET_BUILD_TYPE", "release")
621 c.environ.Set("TARGET_BUILD_APPS", strings.Join(apps, " "))
622}
623
624func (c *configImpl) Environment() *Environment {
625 return c.environ
626}
627
628func (c *configImpl) Arguments() []string {
629 return c.arguments
630}
631
632func (c *configImpl) OutDir() string {
633 if outDir, ok := c.environ.Get("OUT_DIR"); ok {
Patrice Arruda19bd53e2019-07-08 17:26:47 -0700634 return outDir
Dan Willemsen1e704462016-08-21 15:17:17 -0700635 }
636 return "out"
637}
638
Dan Willemsen8a073a82017-02-04 17:30:44 -0800639func (c *configImpl) DistDir() string {
Dan Willemsen2d31a442018-10-20 21:33:41 -0700640 return c.distDir
Dan Willemsen8a073a82017-02-04 17:30:44 -0800641}
642
Dan Willemsen1e704462016-08-21 15:17:17 -0700643func (c *configImpl) NinjaArgs() []string {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700644 if c.skipMake {
645 return c.arguments
646 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700647 return c.ninjaArgs
648}
649
650func (c *configImpl) SoongOutDir() string {
651 return filepath.Join(c.OutDir(), "soong")
652}
653
Jeff Gastonefc1b412017-03-29 17:29:06 -0700654func (c *configImpl) TempDir() string {
655 return shared.TempDirForOutDir(c.SoongOutDir())
656}
657
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700658func (c *configImpl) FileListDir() string {
659 return filepath.Join(c.OutDir(), ".module_paths")
660}
661
Dan Willemsen1e704462016-08-21 15:17:17 -0700662func (c *configImpl) KatiSuffix() string {
663 if c.katiSuffix != "" {
664 return c.katiSuffix
665 }
666 panic("SetKatiSuffix has not been called")
667}
668
Colin Cross37193492017-11-16 17:55:00 -0800669// Checkbuild returns true if "checkbuild" was one of the build goals, which means that the
670// user is interested in additional checks at the expense of build time.
671func (c *configImpl) Checkbuild() bool {
672 return c.checkbuild
673}
674
Dan Willemsen8a073a82017-02-04 17:30:44 -0800675func (c *configImpl) Dist() bool {
676 return c.dist
677}
678
Dan Willemsen1e704462016-08-21 15:17:17 -0700679func (c *configImpl) IsVerbose() bool {
680 return c.verbose
681}
682
Dan Willemsene0879fc2017-08-04 15:06:27 -0700683func (c *configImpl) SkipMake() bool {
684 return c.skipMake
685}
686
Dan Willemsen1e704462016-08-21 15:17:17 -0700687func (c *configImpl) TargetProduct() string {
688 if v, ok := c.environ.Get("TARGET_PRODUCT"); ok {
689 return v
690 }
691 panic("TARGET_PRODUCT is not defined")
692}
693
Dan Willemsen02781d52017-05-12 19:28:13 -0700694func (c *configImpl) TargetDevice() string {
695 return c.targetDevice
696}
697
698func (c *configImpl) SetTargetDevice(device string) {
699 c.targetDevice = device
700}
701
702func (c *configImpl) TargetBuildVariant() string {
703 if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
704 return v
705 }
706 panic("TARGET_BUILD_VARIANT is not defined")
707}
708
Dan Willemsen1e704462016-08-21 15:17:17 -0700709func (c *configImpl) KatiArgs() []string {
710 return c.katiArgs
711}
712
713func (c *configImpl) Parallel() int {
714 return c.parallel
715}
716
717func (c *configImpl) UseGoma() bool {
718 if v, ok := c.environ.Get("USE_GOMA"); ok {
719 v = strings.TrimSpace(v)
720 if v != "" && v != "false" {
721 return true
722 }
723 }
724 return false
725}
726
Yoshisato Yanagisawa2cb0e5d2019-01-10 10:14:16 +0900727func (c *configImpl) StartGoma() bool {
728 if !c.UseGoma() {
729 return false
730 }
731
732 if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
733 v = strings.TrimSpace(v)
734 if v != "" && v != "false" {
735 return false
736 }
737 }
738 return true
739}
740
Ramy Medhatbbf25672019-07-17 12:30:04 +0000741func (c *configImpl) UseRBE() bool {
742 if v, ok := c.environ.Get("USE_RBE"); ok {
743 v = strings.TrimSpace(v)
744 if v != "" && v != "false" {
745 return true
746 }
747 }
748 return false
749}
750
751func (c *configImpl) StartRBE() bool {
752 if !c.UseRBE() {
753 return false
754 }
755
756 if v, ok := c.environ.Get("NOSTART_RBE"); ok {
757 v = strings.TrimSpace(v)
758 if v != "" && v != "false" {
759 return false
760 }
761 }
762 return true
763}
764
Dan Willemsen1e704462016-08-21 15:17:17 -0700765// RemoteParallel controls how many remote jobs (i.e., commands which contain
Jeff Gastonefc1b412017-03-29 17:29:06 -0700766// gomacc) are run in parallel. Note the parallelism of all other jobs is
Dan Willemsen1e704462016-08-21 15:17:17 -0700767// still limited by Parallel()
768func (c *configImpl) RemoteParallel() int {
769 if v, ok := c.environ.Get("NINJA_REMOTE_NUM_JOBS"); ok {
770 if i, err := strconv.Atoi(v); err == nil {
771 return i
772 }
773 }
774 return 500
775}
776
777func (c *configImpl) SetKatiArgs(args []string) {
778 c.katiArgs = args
779}
780
781func (c *configImpl) SetNinjaArgs(args []string) {
782 c.ninjaArgs = args
783}
784
785func (c *configImpl) SetKatiSuffix(suffix string) {
786 c.katiSuffix = suffix
787}
788
Dan Willemsene0879fc2017-08-04 15:06:27 -0700789func (c *configImpl) LastKatiSuffixFile() string {
790 return filepath.Join(c.OutDir(), "last_kati_suffix")
791}
792
793func (c *configImpl) HasKatiSuffix() bool {
794 return c.katiSuffix != ""
795}
796
Dan Willemsen1e704462016-08-21 15:17:17 -0700797func (c *configImpl) KatiEnvFile() string {
798 return filepath.Join(c.OutDir(), "env"+c.KatiSuffix()+".sh")
799}
800
Dan Willemsen29971232018-09-26 14:58:30 -0700801func (c *configImpl) KatiBuildNinjaFile() string {
802 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiBuildSuffix+".ninja")
Dan Willemsen1e704462016-08-21 15:17:17 -0700803}
804
Dan Willemsenfb1271a2018-09-26 15:00:42 -0700805func (c *configImpl) KatiPackageNinjaFile() string {
806 return filepath.Join(c.OutDir(), "build"+c.KatiSuffix()+katiPackageSuffix+".ninja")
807}
808
Dan Willemsen1e704462016-08-21 15:17:17 -0700809func (c *configImpl) SoongNinjaFile() string {
810 return filepath.Join(c.SoongOutDir(), "build.ninja")
811}
812
813func (c *configImpl) CombinedNinjaFile() string {
Dan Willemsene0879fc2017-08-04 15:06:27 -0700814 if c.katiSuffix == "" {
815 return filepath.Join(c.OutDir(), "combined.ninja")
816 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700817 return filepath.Join(c.OutDir(), "combined"+c.KatiSuffix()+".ninja")
818}
819
820func (c *configImpl) SoongAndroidMk() string {
821 return filepath.Join(c.SoongOutDir(), "Android-"+c.TargetProduct()+".mk")
822}
823
824func (c *configImpl) SoongMakeVarsMk() string {
825 return filepath.Join(c.SoongOutDir(), "make_vars-"+c.TargetProduct()+".mk")
826}
827
Dan Willemsenf052f782017-05-18 15:29:04 -0700828func (c *configImpl) ProductOut() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -0700829 return filepath.Join(c.OutDir(), "target", "product", c.TargetDevice())
Dan Willemsenf052f782017-05-18 15:29:04 -0700830}
831
Dan Willemsen02781d52017-05-12 19:28:13 -0700832func (c *configImpl) DevicePreviousProductConfig() string {
Dan Willemsenf052f782017-05-18 15:29:04 -0700833 return filepath.Join(c.ProductOut(), "previous_build_config.mk")
834}
835
Dan Willemsenfb1271a2018-09-26 15:00:42 -0700836func (c *configImpl) KatiPackageMkDir() string {
837 return filepath.Join(c.ProductOut(), "obj", "CONFIG", "kati_packaging")
838}
839
Dan Willemsenf052f782017-05-18 15:29:04 -0700840func (c *configImpl) hostOutRoot() string {
Dan Willemsen4dc4e142017-09-08 14:35:43 -0700841 return filepath.Join(c.OutDir(), "host")
Dan Willemsenf052f782017-05-18 15:29:04 -0700842}
843
844func (c *configImpl) HostOut() string {
845 return filepath.Join(c.hostOutRoot(), c.HostPrebuiltTag())
846}
847
848// This probably needs to be multi-valued, so not exporting it for now
849func (c *configImpl) hostCrossOut() string {
850 if runtime.GOOS == "linux" {
851 return filepath.Join(c.hostOutRoot(), "windows-x86")
852 } else {
853 return ""
854 }
Dan Willemsen02781d52017-05-12 19:28:13 -0700855}
856
Dan Willemsen1e704462016-08-21 15:17:17 -0700857func (c *configImpl) HostPrebuiltTag() string {
858 if runtime.GOOS == "linux" {
859 return "linux-x86"
860 } else if runtime.GOOS == "darwin" {
861 return "darwin-x86"
862 } else {
863 panic("Unsupported OS")
864 }
865}
Dan Willemsenf173d592017-04-27 14:28:00 -0700866
Dan Willemsen8122bd52017-10-12 20:20:41 -0700867func (c *configImpl) PrebuiltBuildTool(name string) string {
Dan Willemsenf173d592017-04-27 14:28:00 -0700868 if v, ok := c.environ.Get("SANITIZE_HOST"); ok {
869 if sanitize := strings.Fields(v); inList("address", sanitize) {
Dan Willemsen8122bd52017-10-12 20:20:41 -0700870 asan := filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "asan/bin", name)
871 if _, err := os.Stat(asan); err == nil {
872 return asan
873 }
Dan Willemsenf173d592017-04-27 14:28:00 -0700874 }
875 }
876 return filepath.Join("prebuilts/build-tools", c.HostPrebuiltTag(), "bin", name)
877}
Dan Willemsen3d60b112018-04-04 22:25:56 -0700878
879func (c *configImpl) SetBuildBrokenDupRules(val bool) {
880 c.brokenDupRules = val
881}
882
883func (c *configImpl) BuildBrokenDupRules() bool {
884 return c.brokenDupRules
885}
Dan Willemsen6ab79db2018-05-02 00:06:28 -0700886
Dan Willemsen25e6f092019-04-09 10:22:43 -0700887func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
888 c.brokenUsesNetwork = val
889}
890
891func (c *configImpl) BuildBrokenUsesNetwork() bool {
892 return c.brokenUsesNetwork
893}
894
Dan Willemsen6ab79db2018-05-02 00:06:28 -0700895func (c *configImpl) SetTargetDeviceDir(dir string) {
896 c.targetDeviceDir = dir
897}
898
899func (c *configImpl) TargetDeviceDir() string {
900 return c.targetDeviceDir
901}
Dan Willemsenfa42f3c2018-06-15 21:54:47 -0700902
903func (c *configImpl) SetPdkBuild(pdk bool) {
904 c.pdkBuild = pdk
905}
906
907func (c *configImpl) IsPdkBuild() bool {
908 return c.pdkBuild
909}