Merge "Support moving sources in srcjars in soong_zip"
diff --git a/OWNERS b/OWNERS
index 85c70df..4ae045d 100644
--- a/OWNERS
+++ b/OWNERS
@@ -1,4 +1,5 @@
-per-file * = asmundak@google.com,ccross@android.com,dwillemsen@google.com,jungjw@google.com
+per-file * = asmundak@google.com,ccross@android.com,dwillemsen@google.com,jungjw@google.com,paulduffin@google.com
+
 per-file ndk_*.go, *gen_stub_libs.py = danalbert@google.com
 per-file clang.go,global.go = srhines@google.com, chh@google.com, pirama@google.com, yikong@google.com
 per-file tidy.go = srhines@google.com, chh@google.com
diff --git a/cmd/soong_ui/main.go b/cmd/soong_ui/main.go
index f5276c3..b909779 100644
--- a/cmd/soong_ui/main.go
+++ b/cmd/soong_ui/main.go
@@ -61,10 +61,8 @@
 		config: func(ctx build.Context, args ...string) build.Config {
 			return build.NewConfig(ctx, args...)
 		},
-		stdio: func() terminal.StdioInterface {
-			return terminal.StdioImpl{}
-		},
-		run: make,
+		stdio: stdio,
+		run:   make,
 	}, {
 		flag:        "--dumpvar-mode",
 		description: "print the value of the legacy make variable VAR to stdout",
@@ -77,6 +75,12 @@
 		config:      dumpVarConfig,
 		stdio:       customStdio,
 		run:         dumpVars,
+	}, {
+		flag:        "--build-mode",
+		description: "build modules based on the specified build action",
+		config:      buildActionConfig,
+		stdio:       stdio,
+		run:         make,
 	},
 }
 
@@ -158,7 +162,7 @@
 	stat.AddOutput(status.NewVerboseLog(log, filepath.Join(logsDir, "verbose.log")))
 	stat.AddOutput(status.NewErrorLog(log, filepath.Join(logsDir, "error.log")))
 
-	defer met.Dump(filepath.Join(logsDir, "build_metrics"))
+	defer met.Dump(filepath.Join(logsDir, "soong_metrics"))
 
 	if start, ok := os.LookupEnv("TRACE_BEGIN_SOONG"); ok {
 		if !strings.HasSuffix(start, "N") {
@@ -184,13 +188,13 @@
 func dumpVar(ctx build.Context, config build.Config, args []string, _ string) {
 	flags := flag.NewFlagSet("dumpvar", flag.ExitOnError)
 	flags.Usage = func() {
-		fmt.Fprintf(os.Stderr, "usage: %s --dumpvar-mode [--abs] <VAR>\n\n", os.Args[0])
-		fmt.Fprintln(os.Stderr, "In dumpvar mode, print the value of the legacy make variable VAR to stdout")
-		fmt.Fprintln(os.Stderr, "")
+		fmt.Fprintf(ctx.Writer, "usage: %s --dumpvar-mode [--abs] <VAR>\n\n", os.Args[0])
+		fmt.Fprintln(ctx.Writer, "In dumpvar mode, print the value of the legacy make variable VAR to stdout")
+		fmt.Fprintln(ctx.Writer, "")
 
-		fmt.Fprintln(os.Stderr, "'report_config' is a special case that prints the human-readable config banner")
-		fmt.Fprintln(os.Stderr, "from the beginning of the build.")
-		fmt.Fprintln(os.Stderr, "")
+		fmt.Fprintln(ctx.Writer, "'report_config' is a special case that prints the human-readable config banner")
+		fmt.Fprintln(ctx.Writer, "from the beginning of the build.")
+		fmt.Fprintln(ctx.Writer, "")
 		flags.PrintDefaults()
 	}
 	abs := flags.Bool("abs", false, "Print the absolute path of the value")
@@ -234,15 +238,15 @@
 func dumpVars(ctx build.Context, config build.Config, args []string, _ string) {
 	flags := flag.NewFlagSet("dumpvars", flag.ExitOnError)
 	flags.Usage = func() {
-		fmt.Fprintf(os.Stderr, "usage: %s --dumpvars-mode [--vars=\"VAR VAR ...\"]\n\n", os.Args[0])
-		fmt.Fprintln(os.Stderr, "In dumpvars mode, dump the values of one or more legacy make variables, in")
-		fmt.Fprintln(os.Stderr, "shell syntax. The resulting output may be sourced directly into a shell to")
-		fmt.Fprintln(os.Stderr, "set corresponding shell variables.")
-		fmt.Fprintln(os.Stderr, "")
+		fmt.Fprintf(ctx.Writer, "usage: %s --dumpvars-mode [--vars=\"VAR VAR ...\"]\n\n", os.Args[0])
+		fmt.Fprintln(ctx.Writer, "In dumpvars mode, dump the values of one or more legacy make variables, in")
+		fmt.Fprintln(ctx.Writer, "shell syntax. The resulting output may be sourced directly into a shell to")
+		fmt.Fprintln(ctx.Writer, "set corresponding shell variables.")
+		fmt.Fprintln(ctx.Writer, "")
 
-		fmt.Fprintln(os.Stderr, "'report_config' is a special case that dumps a variable containing the")
-		fmt.Fprintln(os.Stderr, "human-readable config banner from the beginning of the build.")
-		fmt.Fprintln(os.Stderr, "")
+		fmt.Fprintln(ctx.Writer, "'report_config' is a special case that dumps a variable containing the")
+		fmt.Fprintln(ctx.Writer, "human-readable config banner from the beginning of the build.")
+		fmt.Fprintln(ctx.Writer, "")
 		flags.PrintDefaults()
 	}
 
@@ -299,6 +303,10 @@
 	}
 }
 
+func stdio() terminal.StdioInterface {
+	return terminal.StdioImpl{}
+}
+
 func customStdio() terminal.StdioInterface {
 	return terminal.NewCustomStdio(os.Stdin, os.Stderr, os.Stderr)
 }
@@ -308,6 +316,88 @@
 	return build.NewConfig(ctx)
 }
 
+func buildActionConfig(ctx build.Context, args ...string) build.Config {
+	flags := flag.NewFlagSet("build-mode", flag.ContinueOnError)
+	flags.Usage = func() {
+		fmt.Fprintf(ctx.Writer, "usage: %s --build-mode --dir=<path> <build action> [<build arg 1> <build arg 2> ...]\n\n", os.Args[0])
+		fmt.Fprintln(ctx.Writer, "In build mode, build the set of modules based on the specified build")
+		fmt.Fprintln(ctx.Writer, "action. The --dir flag is required to determine what is needed to")
+		fmt.Fprintln(ctx.Writer, "build in the source tree based on the build action. See below for")
+		fmt.Fprintln(ctx.Writer, "the list of acceptable build action flags.")
+		fmt.Fprintln(ctx.Writer, "")
+		flags.PrintDefaults()
+	}
+
+	buildActionFlags := []struct {
+		name              string
+		description       string
+		action            build.BuildAction
+		buildDependencies bool
+		set               bool
+	}{{
+		name:              "all-modules",
+		description:       "Build action: build from the top of the source tree.",
+		action:            build.BUILD_MODULES_IN_A_DIRECTORY,
+		buildDependencies: true,
+	}, {
+		name:              "modules-in-a-dir-no-deps",
+		description:       "Build action: builds all of the modules in the current directory without their dependencies.",
+		action:            build.BUILD_MODULES_IN_A_DIRECTORY,
+		buildDependencies: false,
+	}, {
+		name:              "modules-in-dirs-no-deps",
+		description:       "Build action: builds all of the modules in the supplied directories without their dependencies.",
+		action:            build.BUILD_MODULES_IN_DIRECTORIES,
+		buildDependencies: false,
+	}, {
+		name:              "modules-in-a-dir",
+		description:       "Build action: builds all of the modules in the current directory and their dependencies.",
+		action:            build.BUILD_MODULES_IN_A_DIRECTORY,
+		buildDependencies: true,
+	}, {
+		name:              "modules-in-dirs",
+		description:       "Build action: builds all of the modules in the supplied directories and their dependencies.",
+		action:            build.BUILD_MODULES_IN_DIRECTORIES,
+		buildDependencies: true,
+	}}
+	for i, flag := range buildActionFlags {
+		flags.BoolVar(&buildActionFlags[i].set, flag.name, false, flag.description)
+	}
+	dir := flags.String("dir", "", "Directory of the executed build command.")
+
+	// Only interested in the first two args which defines the build action and the directory.
+	// The remaining arguments are passed down to the config.
+	const numBuildActionFlags = 2
+	if len(args) < numBuildActionFlags {
+		flags.Usage()
+		ctx.Fatalln("Improper build action arguments.")
+	}
+	flags.Parse(args[0:numBuildActionFlags])
+
+	// The next block of code is to validate that exactly one build action is set and the dir flag
+	// is specified.
+	buildActionCount := 0
+	var buildAction build.BuildAction
+	buildDependency := false
+	for _, flag := range buildActionFlags {
+		if flag.set {
+			buildActionCount++
+			buildAction = flag.action
+			buildDependency = flag.buildDependencies
+		}
+	}
+	if buildActionCount != 1 {
+		ctx.Fatalln("Build action not defined.")
+	}
+	if *dir == "" {
+		ctx.Fatalln("-dir not specified.")
+	}
+
+	// Remove the build action flags from the args as they are not recognized by the config.
+	args = args[numBuildActionFlags:]
+	return build.NewBuildActionConfig(buildAction, *dir, buildDependency, ctx, args...)
+}
+
 func make(ctx build.Context, config build.Config, _ []string, logsDir string) {
 	if config.IsVerbose() {
 		writer := ctx.Writer
diff --git a/dexpreopt/config.go b/dexpreopt/config.go
index 5a1bd74..a2f1af4 100644
--- a/dexpreopt/config.go
+++ b/dexpreopt/config.go
@@ -121,8 +121,9 @@
 	UsesLibraries                []string
 	LibraryPaths                 map[string]android.Path
 
-	Archs           []android.ArchType
-	DexPreoptImages []android.Path
+	Archs               []android.ArchType
+	DexPreoptImages     []android.Path
+	DexPreoptImagesDeps []android.Paths
 
 	PreoptBootClassPathDexFiles     android.Paths // file paths of boot class path files
 	PreoptBootClassPathDexLocations []string      // virtual locations of boot class path files
@@ -257,6 +258,9 @@
 	config.ModuleConfig.StripInputPath = constructPath(ctx, config.StripInputPath)
 	config.ModuleConfig.StripOutputPath = constructWritablePath(ctx, config.StripOutputPath)
 
+	// This needs to exist, but dependencies are already handled in Make, so we don't need to pass them through JSON.
+	config.ModuleConfig.DexPreoptImagesDeps = make([]android.Paths, len(config.ModuleConfig.DexPreoptImages))
+
 	return config.ModuleConfig, nil
 }
 
diff --git a/dexpreopt/dexpreopt.go b/dexpreopt/dexpreopt.go
index 0be37d0..e02e60f 100644
--- a/dexpreopt/dexpreopt.go
+++ b/dexpreopt/dexpreopt.go
@@ -125,7 +125,8 @@
 
 			for i, arch := range module.Archs {
 				image := module.DexPreoptImages[i]
-				dexpreoptCommand(ctx, global, module, rule, arch, profile, image, appImage, generateDM)
+				imageDeps := module.DexPreoptImagesDeps[i]
+				dexpreoptCommand(ctx, global, module, rule, arch, profile, image, imageDeps, appImage, generateDM)
 			}
 		}
 	}
@@ -190,7 +191,7 @@
 }
 
 func dexpreoptCommand(ctx android.PathContext, global GlobalConfig, module ModuleConfig, rule *android.RuleBuilder,
-	arch android.ArchType, profile, bootImage android.Path, appImage, generateDM bool) {
+	arch android.ArchType, profile, bootImage android.Path, bootImageDeps android.Paths, appImage, generateDM bool) {
 
 	// HACK: make soname in Soong-generated .odex files match Make.
 	base := filepath.Base(module.DexLocation)
@@ -353,7 +354,7 @@
 		Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
 		Flag("${class_loader_context_arg}").
 		Flag("${stored_class_loader_context_arg}").
-		FlagWithArg("--boot-image=", bootImageLocation).Implicit(bootImage).
+		FlagWithArg("--boot-image=", bootImageLocation).Implicits(bootImageDeps).
 		FlagWithInput("--dex-file=", module.DexPath).
 		FlagWithArg("--dex-location=", dexLocationArg).
 		FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
diff --git a/dexpreopt/dexpreopt_test.go b/dexpreopt/dexpreopt_test.go
index 0402f87..7f1fe42 100644
--- a/dexpreopt/dexpreopt_test.go
+++ b/dexpreopt/dexpreopt_test.go
@@ -38,6 +38,7 @@
 		LibraryPaths:                    nil,
 		Archs:                           []android.ArchType{android.Arm},
 		DexPreoptImages:                 android.Paths{android.PathForTesting("system/framework/arm/boot.art")},
+		DexPreoptImagesDeps:             []android.Paths{android.Paths{}},
 		PreoptBootClassPathDexFiles:     nil,
 		PreoptBootClassPathDexLocations: nil,
 		PreoptExtractedApk:              false,
diff --git a/java/builder.go b/java/builder.go
index e1a912b..a48e8b1 100644
--- a/java/builder.go
+++ b/java/builder.go
@@ -148,15 +148,16 @@
 }
 
 type javaBuilderFlags struct {
-	javacFlags    string
-	bootClasspath classpath
-	classpath     classpath
-	processorPath classpath
-	processor     string
-	systemModules classpath
-	aidlFlags     string
-	aidlDeps      android.Paths
-	javaVersion   string
+	javacFlags        string
+	bootClasspath     classpath
+	classpath         classpath
+	processorPath     classpath
+	processor         string
+	systemModules     classpath
+	systemModulesDeps android.Paths
+	aidlFlags         string
+	aidlDeps          android.Paths
+	javaVersion       string
 
 	errorProneExtraJavacFlags string
 	errorProneProcessorPath   classpath
@@ -248,7 +249,7 @@
 
 	var bootClasspath string
 	if flags.javaVersion == "1.9" {
-		deps = append(deps, flags.systemModules...)
+		deps = append(deps, flags.systemModulesDeps...)
 		bootClasspath = flags.systemModules.FormJavaSystemModulesPath("--system=", ctx.Device())
 	} else {
 		deps = append(deps, flags.bootClasspath...)
@@ -430,7 +431,7 @@
 	if len(*x) > 1 {
 		panic("more than one system module")
 	} else if len(*x) == 1 {
-		return optName + strings.TrimSuffix((*x)[0].String(), "lib/modules")
+		return optName + (*x)[0].String()
 	} else if forceEmpty {
 		return optName + "none"
 	} else {
diff --git a/java/dexpreopt.go b/java/dexpreopt.go
index 23d2aa6..ed12fe6 100644
--- a/java/dexpreopt.go
+++ b/java/dexpreopt.go
@@ -132,8 +132,10 @@
 	}
 
 	var images android.Paths
+	var imagesDeps []android.Paths
 	for _, arch := range archs {
 		images = append(images, bootImage.images[arch])
+		imagesDeps = append(imagesDeps, bootImage.imagesDeps[arch])
 	}
 
 	dexLocation := android.InstallPathToOnDevicePath(ctx, d.installPath)
@@ -173,8 +175,9 @@
 		UsesLibraries:                d.usesLibs,
 		LibraryPaths:                 d.libraryPaths,
 
-		Archs:           archs,
-		DexPreoptImages: images,
+		Archs:               archs,
+		DexPreoptImages:     images,
+		DexPreoptImagesDeps: imagesDeps,
 
 		// We use the dex paths and dex locations of the default boot image, as it
 		// contains the full dexpreopt boot classpath. Other images may just contain a subset of
diff --git a/java/dexpreopt_bootjars.go b/java/dexpreopt_bootjars.go
index 2a1a901..eb735c1 100644
--- a/java/dexpreopt_bootjars.go
+++ b/java/dexpreopt_bootjars.go
@@ -58,9 +58,32 @@
 	symbolsDir   android.OutputPath
 	targets      []android.Target
 	images       map[android.ArchType]android.OutputPath
+	imagesDeps   map[android.ArchType]android.Paths
 	zip          android.WritablePath
 }
 
+func (image bootImageConfig) moduleFiles(ctx android.PathContext, dir android.OutputPath, exts ...string) []android.OutputPath {
+	ret := make([]android.OutputPath, 0, len(image.modules)*len(exts))
+
+	// dex preopt on the bootclasspath produces multiple files.  The first dex file
+	// is converted into to 'name'.art (to match the legacy assumption that 'name'.art
+	// exists), and the rest are converted to 'name'-<jar>.art.
+	// In addition, each .art file has an associated .oat and .vdex file, and an
+	// unstripped .oat file
+	for i, m := range image.modules {
+		name := image.name
+		if i != 0 {
+			name += "-" + m
+		}
+
+		for _, ext := range exts {
+			ret = append(ret, dir.Join(ctx, name+ext))
+		}
+	}
+
+	return ret
+}
+
 type bootImage struct {
 	bootImageConfig
 
@@ -302,49 +325,38 @@
 	installDir := filepath.Join("/system/framework", arch.String())
 	vdexInstallDir := filepath.Join("/system/framework")
 
-	var extraFiles android.WritablePaths
 	var vdexInstalls android.RuleBuilderInstalls
 	var unstrippedInstalls android.RuleBuilderInstalls
 
 	var zipFiles android.WritablePaths
 
-	// dex preopt on the bootclasspath produces multiple files.  The first dex file
-	// is converted into to 'name'.art (to match the legacy assumption that 'name'.art
-	// exists), and the rest are converted to 'name'-<jar>.art.
-	// In addition, each .art file has an associated .oat and .vdex file, and an
-	// unstripped .oat file
-	for i, m := range image.modules {
-		name := image.name
-		if i != 0 {
-			name += "-" + m
-		}
+	for _, artOrOat := range image.moduleFiles(ctx, outputDir, ".art", ".oat") {
+		cmd.ImplicitOutput(artOrOat)
+		zipFiles = append(zipFiles, artOrOat)
 
-		art := outputDir.Join(ctx, name+".art")
-		oat := outputDir.Join(ctx, name+".oat")
-		vdex := outputDir.Join(ctx, name+".vdex")
-		unstrippedOat := symbolsDir.Join(ctx, name+".oat")
+		// Install the .oat and .art files
+		rule.Install(artOrOat, filepath.Join(installDir, artOrOat.Base()))
+	}
 
-		extraFiles = append(extraFiles, art, oat, vdex, unstrippedOat)
-
-		zipFiles = append(zipFiles, art, oat, vdex)
-
-		// Install the .oat and .art files.
-		rule.Install(art, filepath.Join(installDir, art.Base()))
-		rule.Install(oat, filepath.Join(installDir, oat.Base()))
+	for _, vdex := range image.moduleFiles(ctx, outputDir, ".vdex") {
+		cmd.ImplicitOutput(vdex)
+		zipFiles = append(zipFiles, vdex)
 
 		// The vdex files are identical between architectures, install them to a shared location.  The Make rules will
 		// only use the install rules for one architecture, and will create symlinks into the architecture-specific
 		// directories.
 		vdexInstalls = append(vdexInstalls,
 			android.RuleBuilderInstall{vdex, filepath.Join(vdexInstallDir, vdex.Base())})
+	}
+
+	for _, unstrippedOat := range image.moduleFiles(ctx, symbolsDir, ".oat") {
+		cmd.ImplicitOutput(unstrippedOat)
 
 		// Install the unstripped oat files.  The Make rules will put these in $(TARGET_OUT_UNSTRIPPED)
 		unstrippedInstalls = append(unstrippedInstalls,
 			android.RuleBuilderInstall{unstrippedOat, filepath.Join(installDir, unstrippedOat.Base())})
 	}
 
-	cmd.ImplicitOutputs(extraFiles)
-
 	rule.Build(pctx, ctx, image.name+"JarsDexpreopt_"+arch.String(), "dexpreopt "+image.name+" jars "+arch.String())
 
 	// save output and installed files for makevars
@@ -496,6 +508,7 @@
 			for _, arch := range arches {
 				ctx.Strict("DEXPREOPT_IMAGE_VDEX_BUILT_INSTALLED_"+current.name+"_"+arch.String(), current.vdexInstalls[arch].String())
 				ctx.Strict("DEXPREOPT_IMAGE_"+current.name+"_"+arch.String(), current.images[arch].String())
+				ctx.Strict("DEXPREOPT_IMAGE_DEPS_"+current.name+"_"+arch.String(), strings.Join(current.imagesDeps[arch].Strings(), " "))
 				ctx.Strict("DEXPREOPT_IMAGE_BUILT_INSTALLED_"+current.name+"_"+arch.String(), current.installs[arch].String())
 				ctx.Strict("DEXPREOPT_IMAGE_UNSTRIPPED_BUILT_INSTALLED_"+current.name+"_"+arch.String(), current.unstrippedInstalls[arch].String())
 				if current.zip != nil {
diff --git a/java/dexpreopt_config.go b/java/dexpreopt_config.go
index d903f45..c396d3e 100644
--- a/java/dexpreopt_config.go
+++ b/java/dexpreopt_config.go
@@ -137,27 +137,35 @@
 
 		dir := android.PathForOutput(ctx, ctx.Config().DeviceName(), "dex_bootjars")
 		symbolsDir := android.PathForOutput(ctx, ctx.Config().DeviceName(), "dex_bootjars_unstripped")
-		images := make(map[android.ArchType]android.OutputPath)
 		zip := dir.Join(ctx, "boot.zip")
 
 		targets := dexpreoptTargets(ctx)
 
-		for _, target := range targets {
-			images[target.Arch.ArchType] = dir.Join(ctx,
-				"system/framework", target.Arch.ArchType.String()).Join(ctx, "boot.art")
-		}
-
-		return bootImageConfig{
+		imageConfig := bootImageConfig{
 			name:         "boot",
 			modules:      nonUpdatableBootModules,
 			dexLocations: nonUpdatableBootLocations,
 			dexPaths:     nonUpdatableBootDexPaths,
 			dir:          dir,
 			symbolsDir:   symbolsDir,
-			images:       images,
+			images:       make(map[android.ArchType]android.OutputPath),
+			imagesDeps:   make(map[android.ArchType]android.Paths),
 			targets:      targets,
 			zip:          zip,
 		}
+
+		for _, target := range targets {
+			imageDir := dir.Join(ctx, "system/framework", target.Arch.ArchType.String())
+			imageConfig.images[target.Arch.ArchType] = imageDir.Join(ctx, "boot.art")
+
+			imagesDeps := make([]android.Path, 0, len(imageConfig.modules)*3)
+			for _, dep := range imageConfig.moduleFiles(ctx, imageDir, ".art", ".oat", ".vdex") {
+				imagesDeps = append(imagesDeps, dep)
+			}
+			imageConfig.imagesDeps[target.Arch.ArchType] = imagesDeps
+		}
+
+		return imageConfig
 	}).(bootImageConfig)
 }
 
@@ -196,16 +204,10 @@
 
 		dir := android.PathForOutput(ctx, ctx.Config().DeviceName(), "dex_apexjars")
 		symbolsDir := android.PathForOutput(ctx, ctx.Config().DeviceName(), "dex_apexjars_unstripped")
-		images := make(map[android.ArchType]android.OutputPath)
 
 		targets := dexpreoptTargets(ctx)
 
-		for _, target := range targets {
-			images[target.Arch.ArchType] = dir.Join(ctx,
-				"system/framework", target.Arch.ArchType.String(), "apex.art")
-		}
-
-		return bootImageConfig{
+		imageConfig := bootImageConfig{
 			name:         "apex",
 			modules:      imageModules,
 			dexLocations: bootLocations,
@@ -213,8 +215,22 @@
 			dir:          dir,
 			symbolsDir:   symbolsDir,
 			targets:      targets,
-			images:       images,
+			images:       make(map[android.ArchType]android.OutputPath),
+			imagesDeps:   make(map[android.ArchType]android.Paths),
 		}
+
+		for _, target := range targets {
+			imageDir := dir.Join(ctx, "system/framework", target.Arch.ArchType.String())
+			imageConfig.images[target.Arch.ArchType] = imageDir.Join(ctx, "apex.art")
+
+			imagesDeps := make([]android.Path, 0, len(imageConfig.modules)*3)
+			for _, dep := range imageConfig.moduleFiles(ctx, imageDir, ".art", ".oat", ".vdex") {
+				imagesDeps = append(imagesDeps, dep)
+			}
+			imageConfig.imagesDeps[target.Arch.ArchType] = imagesDeps
+		}
+
+		return imageConfig
 	}).(bootImageConfig)
 }
 
diff --git a/java/droiddoc.go b/java/droiddoc.go
index a8cf1c0..be1b281 100644
--- a/java/droiddoc.go
+++ b/java/droiddoc.go
@@ -692,10 +692,11 @@
 				panic("Found two system module dependencies")
 			}
 			sm := module.(*SystemModules)
-			if sm.outputFile == nil {
+			if sm.outputDir == nil && len(sm.outputDeps) == 0 {
 				panic("Missing directory for system module dependency")
 			}
-			deps.systemModules = sm.outputFile
+			deps.systemModules = sm.outputDir
+			deps.systemModulesDeps = sm.outputDeps
 		}
 	})
 	// do not pass exclude_srcs directly when expanding srcFiles since exclude_srcs
@@ -776,6 +777,7 @@
 		if deps.systemModules != nil {
 			systemModules = append(systemModules, deps.systemModules)
 		}
+		implicits = append(implicits, deps.systemModulesDeps...)
 		bootClasspathArgs = systemModules.FormJavaSystemModulesPath("--system ", ctx.Device())
 		bootClasspathArgs = bootClasspathArgs + " --patch-module java.base=."
 	}
diff --git a/java/java.go b/java/java.go
index 4b38451..a2e9ab0 100644
--- a/java/java.go
+++ b/java/java.go
@@ -628,6 +628,7 @@
 	srcs               android.Paths
 	srcJars            android.Paths
 	systemModules      android.Path
+	systemModulesDeps  android.Paths
 	aidlPreprocess     android.OptionalPath
 	kotlinStdlib       android.Paths
 	kotlinAnnotations  android.Paths
@@ -835,10 +836,11 @@
 					panic("Found two system module dependencies")
 				}
 				sm := module.(*SystemModules)
-				if sm.outputFile == nil {
+				if sm.outputDir == nil || len(sm.outputDeps) == 0 {
 					panic("Missing directory for system module dependency")
 				}
-				deps.systemModules = sm.outputFile
+				deps.systemModules = sm.outputDir
+				deps.systemModulesDeps = sm.outputDeps
 			}
 		}
 	})
@@ -968,6 +970,7 @@
 	// systemModules
 	if deps.systemModules != nil {
 		flags.systemModules = append(flags.systemModules, deps.systemModules)
+		flags.systemModulesDeps = append(flags.systemModulesDeps, deps.systemModulesDeps...)
 	}
 
 	// aidl flags.
diff --git a/java/sdk_test.go b/java/sdk_test.go
index 915333e..953c372 100644
--- a/java/sdk_test.go
+++ b/java/sdk_test.go
@@ -254,7 +254,7 @@
 			if testcase.system == "none" {
 				system = "--system=none"
 			} else if testcase.system != "" {
-				system = "--system=" + filepath.Join(buildDir, ".intermediates", testcase.system, "android_common", "system") + "/"
+				system = "--system=" + filepath.Join(buildDir, ".intermediates", testcase.system, "android_common", "system")
 			}
 
 			checkClasspath := func(t *testing.T, ctx *android.TestContext) {
diff --git a/java/system_modules.go b/java/system_modules.go
index 5a86f3c..f71f452 100644
--- a/java/system_modules.go
+++ b/java/system_modules.go
@@ -61,7 +61,7 @@
 		"moduleName", "classpath", "outDir", "workDir")
 )
 
-func TransformJarsToSystemModules(ctx android.ModuleContext, moduleName string, jars android.Paths) android.WritablePath {
+func TransformJarsToSystemModules(ctx android.ModuleContext, moduleName string, jars android.Paths) (android.Path, android.Paths) {
 	outDir := android.PathForModuleOut(ctx, "system")
 	workDir := android.PathForModuleOut(ctx, "modules")
 	outputFile := android.PathForModuleOut(ctx, "system/lib/modules")
@@ -84,7 +84,7 @@
 		},
 	})
 
-	return outputFile
+	return outDir, outputs.Paths()
 }
 
 func SystemModulesFactory() android.Module {
@@ -101,7 +101,8 @@
 
 	properties SystemModulesProperties
 
-	outputFile android.Path
+	outputDir  android.Path
+	outputDeps android.Paths
 }
 
 type SystemModulesProperties struct {
@@ -117,7 +118,7 @@
 		jars = append(jars, dep.HeaderJars()...)
 	})
 
-	system.outputFile = TransformJarsToSystemModules(ctx, "java.base", jars)
+	system.outputDir, system.outputDeps = TransformJarsToSystemModules(ctx, "java.base", jars)
 }
 
 func (system *SystemModules) DepsMutator(ctx android.BottomUpMutatorContext) {
@@ -127,16 +128,22 @@
 func (system *SystemModules) AndroidMk() android.AndroidMkData {
 	return android.AndroidMkData{
 		Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
-			makevar := "SOONG_SYSTEM_MODULES_" + name
 			fmt.Fprintln(w)
-			fmt.Fprintln(w, makevar, ":=", system.outputFile.String())
-			fmt.Fprintln(w, ".KATI_READONLY", ":=", makevar)
+
+			makevar := "SOONG_SYSTEM_MODULES_" + name
+			fmt.Fprintln(w, makevar, ":=$=", system.outputDir.String())
+			fmt.Fprintln(w)
+
+			makevar = "SOONG_SYSTEM_MODULES_LIBS_" + name
+			fmt.Fprintln(w, makevar, ":=$=", strings.Join(system.properties.Libs, " "))
+			fmt.Fprintln(w)
+
+			makevar = "SOONG_SYSTEM_MODULE_DEPS_" + name
+			fmt.Fprintln(w, makevar, ":=$=", strings.Join(system.outputDeps.Strings(), " "))
+			fmt.Fprintln(w)
+
 			fmt.Fprintln(w, name+":", "$("+makevar+")")
 			fmt.Fprintln(w, ".PHONY:", name)
-			fmt.Fprintln(w)
-			makevar = "SOONG_SYSTEM_MODULES_LIBS_" + name
-			fmt.Fprintln(w, makevar, ":=", strings.Join(system.properties.Libs, " "))
-			fmt.Fprintln(w, ".KATI_READONLY :=", makevar)
 		},
 	}
 }
diff --git a/ui/build/context.go b/ui/build/context.go
index 7ff98ef..3945ce0 100644
--- a/ui/build/context.go
+++ b/ui/build/context.go
@@ -70,7 +70,7 @@
 	if c.Metrics != nil {
 		realTime := end - begin
 		c.Metrics.SetTimeMetrics(
-			metrics_proto.PerfInfo{
+			soong_metrics_proto.PerfInfo{
 				Desc:      &desc,
 				Name:      &name,
 				StartTime: &begin,
diff --git a/ui/build/paths/config.go b/ui/build/paths/config.go
index a50a880..c9946e2 100644
--- a/ui/build/paths/config.go
+++ b/ui/build/paths/config.go
@@ -103,7 +103,6 @@
 	"rsync":    Allowed,
 	"sh":       Allowed,
 	"tar":      Allowed,
-	"timeout":  Allowed,
 	"tr":       Allowed,
 	"unzip":    Allowed,
 	"zip":      Allowed,
@@ -166,6 +165,7 @@
 	"stat":      LinuxOnlyPrebuilt,
 	"tail":      LinuxOnlyPrebuilt,
 	"tee":       LinuxOnlyPrebuilt,
+	"timeout":   LinuxOnlyPrebuilt,
 	"touch":     LinuxOnlyPrebuilt,
 	"true":      LinuxOnlyPrebuilt,
 	"uname":     LinuxOnlyPrebuilt,
diff --git a/ui/metrics/metrics.go b/ui/metrics/metrics.go
index 790b67a..bc86f0a 100644
--- a/ui/metrics/metrics.go
+++ b/ui/metrics/metrics.go
@@ -33,19 +33,19 @@
 )
 
 type Metrics struct {
-	metrics    metrics_proto.MetricsBase
+	metrics    soong_metrics_proto.MetricsBase
 	TimeTracer TimeTracer
 }
 
 func New() (metrics *Metrics) {
 	m := &Metrics{
-		metrics:    metrics_proto.MetricsBase{},
+		metrics:    soong_metrics_proto.MetricsBase{},
 		TimeTracer: &timeTracerImpl{},
 	}
 	return m
 }
 
-func (m *Metrics) SetTimeMetrics(perf metrics_proto.PerfInfo) {
+func (m *Metrics) SetTimeMetrics(perf soong_metrics_proto.PerfInfo) {
 	switch perf.GetName() {
 	case RunKati:
 		m.metrics.KatiRuns = append(m.metrics.KatiRuns, &perf)
@@ -76,11 +76,11 @@
 		case "TARGET_BUILD_VARIANT":
 			switch v {
 			case "user":
-				m.metrics.TargetBuildVariant = metrics_proto.MetricsBase_USER.Enum()
+				m.metrics.TargetBuildVariant = soong_metrics_proto.MetricsBase_USER.Enum()
 			case "userdebug":
-				m.metrics.TargetBuildVariant = metrics_proto.MetricsBase_USERDEBUG.Enum()
+				m.metrics.TargetBuildVariant = soong_metrics_proto.MetricsBase_USERDEBUG.Enum()
 			case "eng":
-				m.metrics.TargetBuildVariant = metrics_proto.MetricsBase_ENG.Enum()
+				m.metrics.TargetBuildVariant = soong_metrics_proto.MetricsBase_ENG.Enum()
 			default:
 				// ignored
 			}
@@ -112,18 +112,18 @@
 	}
 }
 
-func (m *Metrics) getArch(arch string) *metrics_proto.MetricsBase_ARCH {
+func (m *Metrics) getArch(arch string) *soong_metrics_proto.MetricsBase_Arch {
 	switch arch {
 	case "arm":
-		return metrics_proto.MetricsBase_ARM.Enum()
+		return soong_metrics_proto.MetricsBase_ARM.Enum()
 	case "arm64":
-		return metrics_proto.MetricsBase_ARM64.Enum()
+		return soong_metrics_proto.MetricsBase_ARM64.Enum()
 	case "x86":
-		return metrics_proto.MetricsBase_X86.Enum()
+		return soong_metrics_proto.MetricsBase_X86.Enum()
 	case "x86_64":
-		return metrics_proto.MetricsBase_X86_64.Enum()
+		return soong_metrics_proto.MetricsBase_X86_64.Enum()
 	default:
-		return metrics_proto.MetricsBase_UNKNOWN.Enum()
+		return soong_metrics_proto.MetricsBase_UNKNOWN.Enum()
 	}
 }
 
@@ -148,7 +148,7 @@
 		return err
 	}
 	tempPath := outputPath + ".tmp"
-	err = ioutil.WriteFile(tempPath, []byte(data), 0777)
+	err = ioutil.WriteFile(tempPath, []byte(data), 0644)
 	if err != nil {
 		return err
 	}
diff --git a/ui/metrics/metrics_proto/metrics.pb.go b/ui/metrics/metrics_proto/metrics.pb.go
index feefc89..5486ec1 100644
--- a/ui/metrics/metrics_proto/metrics.pb.go
+++ b/ui/metrics/metrics_proto/metrics.pb.go
@@ -1,11 +1,13 @@
 // Code generated by protoc-gen-go. DO NOT EDIT.
 // source: metrics.proto
 
-package metrics_proto
+package soong_metrics_proto
 
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
+import (
+	fmt "fmt"
+	proto "github.com/golang/protobuf/proto"
+	math "math"
+)
 
 // Reference imports to suppress errors if they are not otherwise used.
 var _ = proto.Marshal
@@ -16,65 +18,70 @@
 // is compatible with the proto package it is being compiled against.
 // A compilation error at this line likely means your copy of the
 // proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
 
-type MetricsBase_BUILDVARIANT int32
+type MetricsBase_BuildVariant int32
 
 const (
-	MetricsBase_USER      MetricsBase_BUILDVARIANT = 0
-	MetricsBase_USERDEBUG MetricsBase_BUILDVARIANT = 1
-	MetricsBase_ENG       MetricsBase_BUILDVARIANT = 2
+	MetricsBase_USER      MetricsBase_BuildVariant = 0
+	MetricsBase_USERDEBUG MetricsBase_BuildVariant = 1
+	MetricsBase_ENG       MetricsBase_BuildVariant = 2
 )
 
-var MetricsBase_BUILDVARIANT_name = map[int32]string{
+var MetricsBase_BuildVariant_name = map[int32]string{
 	0: "USER",
 	1: "USERDEBUG",
 	2: "ENG",
 }
-var MetricsBase_BUILDVARIANT_value = map[string]int32{
+
+var MetricsBase_BuildVariant_value = map[string]int32{
 	"USER":      0,
 	"USERDEBUG": 1,
 	"ENG":       2,
 }
 
-func (x MetricsBase_BUILDVARIANT) Enum() *MetricsBase_BUILDVARIANT {
-	p := new(MetricsBase_BUILDVARIANT)
+func (x MetricsBase_BuildVariant) Enum() *MetricsBase_BuildVariant {
+	p := new(MetricsBase_BuildVariant)
 	*p = x
 	return p
 }
-func (x MetricsBase_BUILDVARIANT) String() string {
-	return proto.EnumName(MetricsBase_BUILDVARIANT_name, int32(x))
+
+func (x MetricsBase_BuildVariant) String() string {
+	return proto.EnumName(MetricsBase_BuildVariant_name, int32(x))
 }
-func (x *MetricsBase_BUILDVARIANT) UnmarshalJSON(data []byte) error {
-	value, err := proto.UnmarshalJSONEnum(MetricsBase_BUILDVARIANT_value, data, "MetricsBase_BUILDVARIANT")
+
+func (x *MetricsBase_BuildVariant) UnmarshalJSON(data []byte) error {
+	value, err := proto.UnmarshalJSONEnum(MetricsBase_BuildVariant_value, data, "MetricsBase_BuildVariant")
 	if err != nil {
 		return err
 	}
-	*x = MetricsBase_BUILDVARIANT(value)
+	*x = MetricsBase_BuildVariant(value)
 	return nil
 }
-func (MetricsBase_BUILDVARIANT) EnumDescriptor() ([]byte, []int) {
-	return fileDescriptor_metrics_9e7b895801991242, []int{0, 0}
+
+func (MetricsBase_BuildVariant) EnumDescriptor() ([]byte, []int) {
+	return fileDescriptor_6039342a2ba47b72, []int{0, 0}
 }
 
-type MetricsBase_ARCH int32
+type MetricsBase_Arch int32
 
 const (
-	MetricsBase_UNKNOWN MetricsBase_ARCH = 0
-	MetricsBase_ARM     MetricsBase_ARCH = 1
-	MetricsBase_ARM64   MetricsBase_ARCH = 2
-	MetricsBase_X86     MetricsBase_ARCH = 3
-	MetricsBase_X86_64  MetricsBase_ARCH = 4
+	MetricsBase_UNKNOWN MetricsBase_Arch = 0
+	MetricsBase_ARM     MetricsBase_Arch = 1
+	MetricsBase_ARM64   MetricsBase_Arch = 2
+	MetricsBase_X86     MetricsBase_Arch = 3
+	MetricsBase_X86_64  MetricsBase_Arch = 4
 )
 
-var MetricsBase_ARCH_name = map[int32]string{
+var MetricsBase_Arch_name = map[int32]string{
 	0: "UNKNOWN",
 	1: "ARM",
 	2: "ARM64",
 	3: "X86",
 	4: "X86_64",
 }
-var MetricsBase_ARCH_value = map[string]int32{
+
+var MetricsBase_Arch_value = map[string]int32{
 	"UNKNOWN": 0,
 	"ARM":     1,
 	"ARM64":   2,
@@ -82,63 +89,70 @@
 	"X86_64":  4,
 }
 
-func (x MetricsBase_ARCH) Enum() *MetricsBase_ARCH {
-	p := new(MetricsBase_ARCH)
+func (x MetricsBase_Arch) Enum() *MetricsBase_Arch {
+	p := new(MetricsBase_Arch)
 	*p = x
 	return p
 }
-func (x MetricsBase_ARCH) String() string {
-	return proto.EnumName(MetricsBase_ARCH_name, int32(x))
+
+func (x MetricsBase_Arch) String() string {
+	return proto.EnumName(MetricsBase_Arch_name, int32(x))
 }
-func (x *MetricsBase_ARCH) UnmarshalJSON(data []byte) error {
-	value, err := proto.UnmarshalJSONEnum(MetricsBase_ARCH_value, data, "MetricsBase_ARCH")
+
+func (x *MetricsBase_Arch) UnmarshalJSON(data []byte) error {
+	value, err := proto.UnmarshalJSONEnum(MetricsBase_Arch_value, data, "MetricsBase_Arch")
 	if err != nil {
 		return err
 	}
-	*x = MetricsBase_ARCH(value)
+	*x = MetricsBase_Arch(value)
 	return nil
 }
-func (MetricsBase_ARCH) EnumDescriptor() ([]byte, []int) {
-	return fileDescriptor_metrics_9e7b895801991242, []int{0, 1}
+
+func (MetricsBase_Arch) EnumDescriptor() ([]byte, []int) {
+	return fileDescriptor_6039342a2ba47b72, []int{0, 1}
 }
 
-type ModuleTypeInfo_BUILDSYSTEM int32
+type ModuleTypeInfo_BuildSystem int32
 
 const (
-	ModuleTypeInfo_UNKNOWN ModuleTypeInfo_BUILDSYSTEM = 0
-	ModuleTypeInfo_SOONG   ModuleTypeInfo_BUILDSYSTEM = 1
-	ModuleTypeInfo_MAKE    ModuleTypeInfo_BUILDSYSTEM = 2
+	ModuleTypeInfo_UNKNOWN ModuleTypeInfo_BuildSystem = 0
+	ModuleTypeInfo_SOONG   ModuleTypeInfo_BuildSystem = 1
+	ModuleTypeInfo_MAKE    ModuleTypeInfo_BuildSystem = 2
 )
 
-var ModuleTypeInfo_BUILDSYSTEM_name = map[int32]string{
+var ModuleTypeInfo_BuildSystem_name = map[int32]string{
 	0: "UNKNOWN",
 	1: "SOONG",
 	2: "MAKE",
 }
-var ModuleTypeInfo_BUILDSYSTEM_value = map[string]int32{
+
+var ModuleTypeInfo_BuildSystem_value = map[string]int32{
 	"UNKNOWN": 0,
 	"SOONG":   1,
 	"MAKE":    2,
 }
 
-func (x ModuleTypeInfo_BUILDSYSTEM) Enum() *ModuleTypeInfo_BUILDSYSTEM {
-	p := new(ModuleTypeInfo_BUILDSYSTEM)
+func (x ModuleTypeInfo_BuildSystem) Enum() *ModuleTypeInfo_BuildSystem {
+	p := new(ModuleTypeInfo_BuildSystem)
 	*p = x
 	return p
 }
-func (x ModuleTypeInfo_BUILDSYSTEM) String() string {
-	return proto.EnumName(ModuleTypeInfo_BUILDSYSTEM_name, int32(x))
+
+func (x ModuleTypeInfo_BuildSystem) String() string {
+	return proto.EnumName(ModuleTypeInfo_BuildSystem_name, int32(x))
 }
-func (x *ModuleTypeInfo_BUILDSYSTEM) UnmarshalJSON(data []byte) error {
-	value, err := proto.UnmarshalJSONEnum(ModuleTypeInfo_BUILDSYSTEM_value, data, "ModuleTypeInfo_BUILDSYSTEM")
+
+func (x *ModuleTypeInfo_BuildSystem) UnmarshalJSON(data []byte) error {
+	value, err := proto.UnmarshalJSONEnum(ModuleTypeInfo_BuildSystem_value, data, "ModuleTypeInfo_BuildSystem")
 	if err != nil {
 		return err
 	}
-	*x = ModuleTypeInfo_BUILDSYSTEM(value)
+	*x = ModuleTypeInfo_BuildSystem(value)
 	return nil
 }
-func (ModuleTypeInfo_BUILDSYSTEM) EnumDescriptor() ([]byte, []int) {
-	return fileDescriptor_metrics_9e7b895801991242, []int{2, 0}
+
+func (ModuleTypeInfo_BuildSystem) EnumDescriptor() ([]byte, []int) {
+	return fileDescriptor_6039342a2ba47b72, []int{2, 0}
 }
 
 type MetricsBase struct {
@@ -151,17 +165,17 @@
 	// The target product information, eg. aosp_arm.
 	TargetProduct *string `protobuf:"bytes,4,opt,name=target_product,json=targetProduct" json:"target_product,omitempty"`
 	// The target build variant information, eg. eng.
-	TargetBuildVariant *MetricsBase_BUILDVARIANT `protobuf:"varint,5,opt,name=target_build_variant,json=targetBuildVariant,enum=build_metrics.MetricsBase_BUILDVARIANT,def=2" json:"target_build_variant,omitempty"`
+	TargetBuildVariant *MetricsBase_BuildVariant `protobuf:"varint,5,opt,name=target_build_variant,json=targetBuildVariant,enum=soong_build_metrics.MetricsBase_BuildVariant,def=2" json:"target_build_variant,omitempty"`
 	// The target arch information, eg. arm.
-	TargetArch *MetricsBase_ARCH `protobuf:"varint,6,opt,name=target_arch,json=targetArch,enum=build_metrics.MetricsBase_ARCH,def=0" json:"target_arch,omitempty"`
+	TargetArch *MetricsBase_Arch `protobuf:"varint,6,opt,name=target_arch,json=targetArch,enum=soong_build_metrics.MetricsBase_Arch,def=0" json:"target_arch,omitempty"`
 	// The target arch variant information, eg. armv7-a-neon.
 	TargetArchVariant *string `protobuf:"bytes,7,opt,name=target_arch_variant,json=targetArchVariant" json:"target_arch_variant,omitempty"`
 	// The target cpu variant information, eg. generic.
 	TargetCpuVariant *string `protobuf:"bytes,8,opt,name=target_cpu_variant,json=targetCpuVariant" json:"target_cpu_variant,omitempty"`
 	// The host arch information, eg. x86_64.
-	HostArch *MetricsBase_ARCH `protobuf:"varint,9,opt,name=host_arch,json=hostArch,enum=build_metrics.MetricsBase_ARCH,def=0" json:"host_arch,omitempty"`
+	HostArch *MetricsBase_Arch `protobuf:"varint,9,opt,name=host_arch,json=hostArch,enum=soong_build_metrics.MetricsBase_Arch,def=0" json:"host_arch,omitempty"`
 	// The host 2nd arch information, eg. x86.
-	Host_2NdArch *MetricsBase_ARCH `protobuf:"varint,10,opt,name=host_2nd_arch,json=host2ndArch,enum=build_metrics.MetricsBase_ARCH,def=0" json:"host_2nd_arch,omitempty"`
+	Host_2NdArch *MetricsBase_Arch `protobuf:"varint,10,opt,name=host_2nd_arch,json=host2ndArch,enum=soong_build_metrics.MetricsBase_Arch,def=0" json:"host_2nd_arch,omitempty"`
 	// The host os information, eg. linux.
 	HostOs *string `protobuf:"bytes,11,opt,name=host_os,json=hostOs" json:"host_os,omitempty"`
 	// The host os extra information, eg. Linux-4.17.0-3rodete2-amd64-x86_64-Debian-GNU.
@@ -191,16 +205,17 @@
 func (m *MetricsBase) String() string { return proto.CompactTextString(m) }
 func (*MetricsBase) ProtoMessage()    {}
 func (*MetricsBase) Descriptor() ([]byte, []int) {
-	return fileDescriptor_metrics_9e7b895801991242, []int{0}
+	return fileDescriptor_6039342a2ba47b72, []int{0}
 }
+
 func (m *MetricsBase) XXX_Unmarshal(b []byte) error {
 	return xxx_messageInfo_MetricsBase.Unmarshal(m, b)
 }
 func (m *MetricsBase) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
 	return xxx_messageInfo_MetricsBase.Marshal(b, m, deterministic)
 }
-func (dst *MetricsBase) XXX_Merge(src proto.Message) {
-	xxx_messageInfo_MetricsBase.Merge(dst, src)
+func (m *MetricsBase) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_MetricsBase.Merge(m, src)
 }
 func (m *MetricsBase) XXX_Size() int {
 	return xxx_messageInfo_MetricsBase.Size(m)
@@ -211,10 +226,10 @@
 
 var xxx_messageInfo_MetricsBase proto.InternalMessageInfo
 
-const Default_MetricsBase_TargetBuildVariant MetricsBase_BUILDVARIANT = MetricsBase_ENG
-const Default_MetricsBase_TargetArch MetricsBase_ARCH = MetricsBase_UNKNOWN
-const Default_MetricsBase_HostArch MetricsBase_ARCH = MetricsBase_UNKNOWN
-const Default_MetricsBase_Host_2NdArch MetricsBase_ARCH = MetricsBase_UNKNOWN
+const Default_MetricsBase_TargetBuildVariant MetricsBase_BuildVariant = MetricsBase_ENG
+const Default_MetricsBase_TargetArch MetricsBase_Arch = MetricsBase_UNKNOWN
+const Default_MetricsBase_HostArch MetricsBase_Arch = MetricsBase_UNKNOWN
+const Default_MetricsBase_Host_2NdArch MetricsBase_Arch = MetricsBase_UNKNOWN
 
 func (m *MetricsBase) GetBuildDateTimestamp() int64 {
 	if m != nil && m.BuildDateTimestamp != nil {
@@ -244,14 +259,14 @@
 	return ""
 }
 
-func (m *MetricsBase) GetTargetBuildVariant() MetricsBase_BUILDVARIANT {
+func (m *MetricsBase) GetTargetBuildVariant() MetricsBase_BuildVariant {
 	if m != nil && m.TargetBuildVariant != nil {
 		return *m.TargetBuildVariant
 	}
 	return Default_MetricsBase_TargetBuildVariant
 }
 
-func (m *MetricsBase) GetTargetArch() MetricsBase_ARCH {
+func (m *MetricsBase) GetTargetArch() MetricsBase_Arch {
 	if m != nil && m.TargetArch != nil {
 		return *m.TargetArch
 	}
@@ -272,14 +287,14 @@
 	return ""
 }
 
-func (m *MetricsBase) GetHostArch() MetricsBase_ARCH {
+func (m *MetricsBase) GetHostArch() MetricsBase_Arch {
 	if m != nil && m.HostArch != nil {
 		return *m.HostArch
 	}
 	return Default_MetricsBase_HostArch
 }
 
-func (m *MetricsBase) GetHost_2NdArch() MetricsBase_ARCH {
+func (m *MetricsBase) GetHost_2NdArch() MetricsBase_Arch {
 	if m != nil && m.Host_2NdArch != nil {
 		return *m.Host_2NdArch
 	}
@@ -378,16 +393,17 @@
 func (m *PerfInfo) String() string { return proto.CompactTextString(m) }
 func (*PerfInfo) ProtoMessage()    {}
 func (*PerfInfo) Descriptor() ([]byte, []int) {
-	return fileDescriptor_metrics_9e7b895801991242, []int{1}
+	return fileDescriptor_6039342a2ba47b72, []int{1}
 }
+
 func (m *PerfInfo) XXX_Unmarshal(b []byte) error {
 	return xxx_messageInfo_PerfInfo.Unmarshal(m, b)
 }
 func (m *PerfInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
 	return xxx_messageInfo_PerfInfo.Marshal(b, m, deterministic)
 }
-func (dst *PerfInfo) XXX_Merge(src proto.Message) {
-	xxx_messageInfo_PerfInfo.Merge(dst, src)
+func (m *PerfInfo) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_PerfInfo.Merge(m, src)
 }
 func (m *PerfInfo) XXX_Size() int {
 	return xxx_messageInfo_PerfInfo.Size(m)
@@ -435,7 +451,7 @@
 
 type ModuleTypeInfo struct {
 	// The build system, eg. Soong or Make.
-	BuildSystem *ModuleTypeInfo_BUILDSYSTEM `protobuf:"varint,1,opt,name=build_system,json=buildSystem,enum=build_metrics.ModuleTypeInfo_BUILDSYSTEM,def=0" json:"build_system,omitempty"`
+	BuildSystem *ModuleTypeInfo_BuildSystem `protobuf:"varint,1,opt,name=build_system,json=buildSystem,enum=soong_build_metrics.ModuleTypeInfo_BuildSystem,def=0" json:"build_system,omitempty"`
 	// The module type, eg. java_library, cc_binary, and etc.
 	ModuleType *string `protobuf:"bytes,2,opt,name=module_type,json=moduleType" json:"module_type,omitempty"`
 	// The number of logical modules.
@@ -449,16 +465,17 @@
 func (m *ModuleTypeInfo) String() string { return proto.CompactTextString(m) }
 func (*ModuleTypeInfo) ProtoMessage()    {}
 func (*ModuleTypeInfo) Descriptor() ([]byte, []int) {
-	return fileDescriptor_metrics_9e7b895801991242, []int{2}
+	return fileDescriptor_6039342a2ba47b72, []int{2}
 }
+
 func (m *ModuleTypeInfo) XXX_Unmarshal(b []byte) error {
 	return xxx_messageInfo_ModuleTypeInfo.Unmarshal(m, b)
 }
 func (m *ModuleTypeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
 	return xxx_messageInfo_ModuleTypeInfo.Marshal(b, m, deterministic)
 }
-func (dst *ModuleTypeInfo) XXX_Merge(src proto.Message) {
-	xxx_messageInfo_ModuleTypeInfo.Merge(dst, src)
+func (m *ModuleTypeInfo) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_ModuleTypeInfo.Merge(m, src)
 }
 func (m *ModuleTypeInfo) XXX_Size() int {
 	return xxx_messageInfo_ModuleTypeInfo.Size(m)
@@ -469,9 +486,9 @@
 
 var xxx_messageInfo_ModuleTypeInfo proto.InternalMessageInfo
 
-const Default_ModuleTypeInfo_BuildSystem ModuleTypeInfo_BUILDSYSTEM = ModuleTypeInfo_UNKNOWN
+const Default_ModuleTypeInfo_BuildSystem ModuleTypeInfo_BuildSystem = ModuleTypeInfo_UNKNOWN
 
-func (m *ModuleTypeInfo) GetBuildSystem() ModuleTypeInfo_BUILDSYSTEM {
+func (m *ModuleTypeInfo) GetBuildSystem() ModuleTypeInfo_BuildSystem {
 	if m != nil && m.BuildSystem != nil {
 		return *m.BuildSystem
 	}
@@ -493,65 +510,65 @@
 }
 
 func init() {
-	proto.RegisterType((*MetricsBase)(nil), "build_metrics.MetricsBase")
-	proto.RegisterType((*PerfInfo)(nil), "build_metrics.PerfInfo")
-	proto.RegisterType((*ModuleTypeInfo)(nil), "build_metrics.ModuleTypeInfo")
-	proto.RegisterEnum("build_metrics.MetricsBase_BUILDVARIANT", MetricsBase_BUILDVARIANT_name, MetricsBase_BUILDVARIANT_value)
-	proto.RegisterEnum("build_metrics.MetricsBase_ARCH", MetricsBase_ARCH_name, MetricsBase_ARCH_value)
-	proto.RegisterEnum("build_metrics.ModuleTypeInfo_BUILDSYSTEM", ModuleTypeInfo_BUILDSYSTEM_name, ModuleTypeInfo_BUILDSYSTEM_value)
+	proto.RegisterEnum("soong_build_metrics.MetricsBase_BuildVariant", MetricsBase_BuildVariant_name, MetricsBase_BuildVariant_value)
+	proto.RegisterEnum("soong_build_metrics.MetricsBase_Arch", MetricsBase_Arch_name, MetricsBase_Arch_value)
+	proto.RegisterEnum("soong_build_metrics.ModuleTypeInfo_BuildSystem", ModuleTypeInfo_BuildSystem_name, ModuleTypeInfo_BuildSystem_value)
+	proto.RegisterType((*MetricsBase)(nil), "soong_build_metrics.MetricsBase")
+	proto.RegisterType((*PerfInfo)(nil), "soong_build_metrics.PerfInfo")
+	proto.RegisterType((*ModuleTypeInfo)(nil), "soong_build_metrics.ModuleTypeInfo")
 }
 
-func init() { proto.RegisterFile("metrics.proto", fileDescriptor_metrics_9e7b895801991242) }
+func init() { proto.RegisterFile("metrics.proto", fileDescriptor_6039342a2ba47b72) }
 
-var fileDescriptor_metrics_9e7b895801991242 = []byte{
-	// 783 bytes of a gzipped FileDescriptorProto
-	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x55, 0xdd, 0x6e, 0xdb, 0x36,
-	0x14, 0xae, 0x62, 0x25, 0x96, 0x8e, 0x62, 0x57, 0x61, 0x02, 0x44, 0xc5, 0x50, 0x34, 0x30, 0xf6,
-	0x93, 0x01, 0x9b, 0x57, 0x18, 0x81, 0x11, 0x04, 0xbb, 0xb1, 0x13, 0xa3, 0x35, 0x5a, 0xdb, 0x85,
-	0x6c, 0x67, 0xdd, 0x2e, 0x46, 0x68, 0x12, 0xdd, 0x68, 0xb3, 0x44, 0x81, 0xa4, 0x8a, 0xf9, 0x21,
-	0xf6, 0x8c, 0x7b, 0x91, 0x5d, 0x0c, 0x3c, 0xb4, 0x5c, 0xa5, 0x17, 0x29, 0x72, 0x47, 0x9d, 0xef,
-	0x87, 0xdf, 0x91, 0xc8, 0x23, 0x68, 0x65, 0x4c, 0x89, 0x34, 0x96, 0xdd, 0x42, 0x70, 0xc5, 0x49,
-	0xeb, 0x8f, 0x32, 0x5d, 0x27, 0x74, 0x5b, 0xec, 0xfc, 0xe7, 0x80, 0x37, 0x31, 0xeb, 0x61, 0x24,
-	0x19, 0x79, 0x09, 0x27, 0x86, 0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82, 0xf6, 0x84, 0x27, 0xe5, 0x9a, 0x2d, 0x36, 0x05, 0xc3, 0x54, 0x4b, 0x38, 0x34, 0xef,
-	0x4d, 0x6e, 0xa4, 0x62, 0x19, 0xa6, 0x6b, 0xf7, 0xbe, 0xff, 0xfc, 0x42, 0xdc, 0x13, 0x99, 0xe1,
-	0x32, 0xff, 0x75, 0xbe, 0x18, 0x4d, 0x6a, 0x57, 0x03, 0x25, 0x73, 0xb4, 0x21, 0x2f, 0xc0, 0xcb,
-	0x50, 0x43, 0xd5, 0xa6, 0xa8, 0xfa, 0x83, 0x6c, 0x67, 0x43, 0xbe, 0x86, 0x76, 0x5e, 0x66, 0x94,
-	0xaf, 0xa8, 0x29, 0x4a, 0xec, 0xb4, 0x15, 0x1e, 0xe6, 0x65, 0x36, 0x5b, 0x99, 0xfd, 0x64, 0xe7,
-	0x27, 0xf0, 0x6a, 0x7b, 0xdd, 0xff, 0x0a, 0x2e, 0xec, 0xcf, 0x67, 0xb3, 0xa9, 0xfe, 0x5c, 0x0e,
-	0xd8, 0x93, 0xc1, 0x9b, 0x91, 0xbf, 0x37, 0x3c, 0x7a, 0xdd, 0xf8, 0xad, 0xfa, 0x25, 0x50, 0xfc,
-	0x25, 0xfc, 0x1f, 0x00, 0x00, 0xff, 0xff, 0xd4, 0x8d, 0x19, 0x89, 0x22, 0x06, 0x00, 0x00,
+var fileDescriptor_6039342a2ba47b72 = []byte{
+	// 769 bytes of a gzipped FileDescriptorProto
+	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x55, 0x6f, 0x6b, 0xdb, 0x46,
+	0x18, 0xaf, 0x62, 0x25, 0x96, 0x1e, 0xc5, 0xae, 0x7a, 0xc9, 0xa8, 0xca, 0x08, 0x33, 0x66, 0x1d,
+	0x7e, 0xb1, 0xba, 0xc5, 0x14, 0x53, 0x4c, 0x19, 0xd8, 0x89, 0x29, 0x25, 0xd8, 0x2e, 0x4a, 0xd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	0x00,
 }
diff --git a/ui/metrics/metrics_proto/metrics.proto b/ui/metrics/metrics_proto/metrics.proto
index b3de2f4..93034eb 100644
--- a/ui/metrics/metrics_proto/metrics.proto
+++ b/ui/metrics/metrics_proto/metrics.proto
@@ -14,10 +14,8 @@
 
 syntax = "proto2";
 
-option optimize_for = LITE_RUNTIME;
-
-package build_metrics;
-option go_package = "metrics_proto";
+package soong_build_metrics;
+option go_package = "soong_metrics_proto";
 
 message MetricsBase {
   // Timestamp generated when the build starts.
@@ -32,15 +30,15 @@
   // The target product information, eg. aosp_arm.
   optional string target_product = 4;
 
-  enum BUILDVARIANT {
+  enum BuildVariant {
     USER = 0;
     USERDEBUG = 1;
     ENG = 2;
   }
   // The target build variant information, eg. eng.
-  optional BUILDVARIANT target_build_variant = 5 [default = ENG];
+  optional BuildVariant target_build_variant = 5 [default = ENG];
 
-  enum ARCH {
+  enum Arch {
     UNKNOWN = 0;
     ARM = 1;
     ARM64 = 2;
@@ -48,7 +46,7 @@
     X86_64 = 4;
   }
   // The target arch information, eg. arm.
-  optional ARCH target_arch = 6 [default = UNKNOWN];
+  optional Arch target_arch = 6 [default = UNKNOWN];
 
   // The target arch variant information, eg. armv7-a-neon.
   optional string target_arch_variant = 7;
@@ -57,10 +55,10 @@
   optional string target_cpu_variant = 8;
 
   // The host arch information, eg. x86_64.
-  optional ARCH host_arch = 9 [default = UNKNOWN];
+  optional Arch host_arch = 9 [default = UNKNOWN];
 
   // The host 2nd arch information, eg. x86.
-  optional ARCH host_2nd_arch = 10 [default = UNKNOWN];
+  optional Arch host_2nd_arch = 10 [default = UNKNOWN];
 
   // The host os information, eg. linux.
   optional string host_os = 11;
@@ -113,13 +111,13 @@
 }
 
 message ModuleTypeInfo {
-  enum BUILDSYSTEM {
+  enum BuildSystem {
     UNKNOWN = 0;
     SOONG = 1;
     MAKE = 2;
   }
   // The build system, eg. Soong or Make.
-  optional BUILDSYSTEM build_system = 1 [default = UNKNOWN];
+  optional BuildSystem build_system = 1 [default = UNKNOWN];
 
   // The module type, eg. java_library, cc_binary, and etc.
   optional string module_type = 2;
diff --git a/ui/metrics/time.go b/ui/metrics/time.go
index 7e8801a..b8baf16 100644
--- a/ui/metrics/time.go
+++ b/ui/metrics/time.go
@@ -30,7 +30,7 @@
 
 type TimeTracer interface {
 	Begin(name, desc string, thread tracer.Thread)
-	End(thread tracer.Thread) metrics_proto.PerfInfo
+	End(thread tracer.Thread) soong_metrics_proto.PerfInfo
 }
 
 type timeTracerImpl struct {
@@ -51,11 +51,11 @@
 	t.activeEvents = append(t.activeEvents, timeEvent{name: name, desc: desc, atNanos: atNanos})
 }
 
-func (t *timeTracerImpl) End(thread tracer.Thread) metrics_proto.PerfInfo {
+func (t *timeTracerImpl) End(thread tracer.Thread) soong_metrics_proto.PerfInfo {
 	return t.endAt(t.now())
 }
 
-func (t *timeTracerImpl) endAt(atNanos uint64) metrics_proto.PerfInfo {
+func (t *timeTracerImpl) endAt(atNanos uint64) soong_metrics_proto.PerfInfo {
 	if len(t.activeEvents) < 1 {
 		panic("Internal error: No pending events for endAt to end!")
 	}
@@ -63,7 +63,7 @@
 	t.activeEvents = t.activeEvents[:len(t.activeEvents)-1]
 	realTime := atNanos - lastEvent.atNanos
 
-	return metrics_proto.PerfInfo{
+	return soong_metrics_proto.PerfInfo{
 		Desc:      &lastEvent.desc,
 		Name:      &lastEvent.name,
 		StartTime: &lastEvent.atNanos,
diff --git a/ui/terminal/smart_status.go b/ui/terminal/smart_status.go
index 8fa9eff..82c04d4 100644
--- a/ui/terminal/smart_status.go
+++ b/ui/terminal/smart_status.go
@@ -17,8 +17,11 @@
 import (
 	"fmt"
 	"io"
+	"os"
+	"os/signal"
 	"strings"
 	"sync"
+	"syscall"
 
 	"android/soong/ui/status"
 )
@@ -30,18 +33,30 @@
 	lock sync.Mutex
 
 	haveBlankLine bool
+
+	termWidth       int
+	sigwinch        chan os.Signal
+	sigwinchHandled chan bool
 }
 
 // NewSmartStatusOutput returns a StatusOutput that represents the
 // current build status similarly to Ninja's built-in terminal
 // output.
 func NewSmartStatusOutput(w io.Writer, formatter formatter) status.StatusOutput {
-	return &smartStatusOutput{
+	s := &smartStatusOutput{
 		writer:    w,
 		formatter: formatter,
 
 		haveBlankLine: true,
+
+		sigwinch: make(chan os.Signal),
 	}
+
+	s.updateTermSize()
+
+	s.startSigwinch()
+
+	return s
 }
 
 func (s *smartStatusOutput) Message(level status.MsgLevel, message string) {
@@ -101,6 +116,8 @@
 	s.lock.Lock()
 	defer s.lock.Unlock()
 
+	s.stopSigwinch()
+
 	s.requestLine()
 }
 
@@ -137,16 +154,8 @@
 
 	// Limit line width to the terminal width, otherwise we'll wrap onto
 	// another line and we won't delete the previous line.
-	//
-	// Run this on every line in case the window has been resized while
-	// we're printing. This could be optimized to only re-run when we get
-	// SIGWINCH if it ever becomes too time consuming.
-	if max, ok := termWidth(s.writer); ok {
-		if len(str) > max {
-			// TODO: Just do a max. Ninja elides the middle, but that's
-			// more complicated and these lines aren't that important.
-			str = str[:max]
-		}
+	if s.termWidth > 0 {
+		str = s.elide(str)
 	}
 
 	// Move to the beginning on the line, turn on bold, print the output,
@@ -156,3 +165,38 @@
 	fmt.Fprint(s.writer, start, str, end)
 	s.haveBlankLine = false
 }
+
+func (s *smartStatusOutput) elide(str string) string {
+	if len(str) > s.termWidth {
+		// TODO: Just do a max. Ninja elides the middle, but that's
+		// more complicated and these lines aren't that important.
+		str = str[:s.termWidth]
+	}
+
+	return str
+}
+
+func (s *smartStatusOutput) startSigwinch() {
+	signal.Notify(s.sigwinch, syscall.SIGWINCH)
+	go func() {
+		for _ = range s.sigwinch {
+			s.lock.Lock()
+			s.updateTermSize()
+			s.lock.Unlock()
+			if s.sigwinchHandled != nil {
+				s.sigwinchHandled <- true
+			}
+		}
+	}()
+}
+
+func (s *smartStatusOutput) stopSigwinch() {
+	signal.Stop(s.sigwinch)
+	close(s.sigwinch)
+}
+
+func (s *smartStatusOutput) updateTermSize() {
+	if w, ok := termWidth(s.writer); ok {
+		s.termWidth = w
+	}
+}
diff --git a/ui/terminal/status_test.go b/ui/terminal/status_test.go
index a87a7f0..106d651 100644
--- a/ui/terminal/status_test.go
+++ b/ui/terminal/status_test.go
@@ -17,6 +17,7 @@
 import (
 	"bytes"
 	"fmt"
+	"syscall"
 	"testing"
 
 	"android/soong/ui/status"
@@ -252,6 +253,8 @@
 func TestSmartStatusOutputWidthChange(t *testing.T) {
 	smart := &fakeSmartTerminal{termWidth: 40}
 	stat := NewStatusOutput(smart, "", false)
+	smartStat := stat.(*smartStatusOutput)
+	smartStat.sigwinchHandled = make(chan bool)
 
 	runner := newRunner(stat, 2)
 
@@ -260,6 +263,9 @@
 
 	runner.startAction(action)
 	smart.termWidth = 30
+	// Fake a SIGWINCH
+	smartStat.sigwinch <- syscall.SIGWINCH
+	<-smartStat.sigwinchHandled
 	runner.finishAction(result)
 
 	stat.Flush()